Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-html / node_modules / typescript / lib / typingsInstaller.js
1 /*! *****************************************************************************
2 Copyright (c) Microsoft Corporation. All rights reserved.
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4 this file except in compliance with the License. You may obtain a copy of the
5 License at http://www.apache.org/licenses/LICENSE-2.0
6
7 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10 MERCHANTABLITY OR NON-INFRINGEMENT.
11
12 See the Apache Version 2.0 License for specific language governing permissions
13 and limitations under the License.
14 ***************************************************************************** */
15
16
17 "use strict";
18 var __spreadArrays = (this && this.__spreadArrays) || function () {
19     for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
20     for (var r = Array(s), k = 0, i = 0; i < il; i++)
21         for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
22             r[k] = a[j];
23     return r;
24 };
25 var __assign = (this && this.__assign) || function () {
26     __assign = Object.assign || function(t) {
27         for (var s, i = 1, n = arguments.length; i < n; i++) {
28             s = arguments[i];
29             for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
30                 t[p] = s[p];
31         }
32         return t;
33     };
34     return __assign.apply(this, arguments);
35 };
36 var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
37     if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
38     return cooked;
39 };
40 var __generator = (this && this.__generator) || function (thisArg, body) {
41     var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
42     return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
43     function verb(n) { return function (v) { return step([n, v]); }; }
44     function step(op) {
45         if (f) throw new TypeError("Generator is already executing.");
46         while (_) try {
47             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;
48             if (y = 0, t) op = [op[0] & 2, t.value];
49             switch (op[0]) {
50                 case 0: case 1: t = op; break;
51                 case 4: _.label++; return { value: op[1], done: false };
52                 case 5: _.label++; y = op[1]; op = [0]; continue;
53                 case 7: op = _.ops.pop(); _.trys.pop(); continue;
54                 default:
55                     if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
56                     if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
57                     if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
58                     if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
59                     if (t[2]) _.ops.pop();
60                     _.trys.pop(); continue;
61             }
62             op = body.call(thisArg, _);
63         } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
64         if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
65     }
66 };
67 var __extends = (this && this.__extends) || (function () {
68     var extendStatics = function (d, b) {
69         extendStatics = Object.setPrototypeOf ||
70             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
71             function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
72         return extendStatics(d, b);
73     };
74     return function (d, b) {
75         extendStatics(d, b);
76         function __() { this.constructor = d; }
77         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
78     };
79 })();
80 var ts;
81 (function (ts) {
82     // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
83     // If changing the text in this section, be sure to test `configurePrerelease` too.
84     ts.versionMajorMinor = "4.1";
85     /** The version of the TypeScript compiler release */
86     ts.version = "4.1.3";
87     /* @internal */
88     var Comparison;
89     (function (Comparison) {
90         Comparison[Comparison["LessThan"] = -1] = "LessThan";
91         Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
92         Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
93     })(Comparison = ts.Comparison || (ts.Comparison = {}));
94     /* @internal */
95     var NativeCollections;
96     (function (NativeCollections) {
97         /**
98          * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
99          */
100         function tryGetNativeMap() {
101             // Internet Explorer's Map doesn't support iteration, so don't use it.
102             // eslint-disable-next-line no-in-operator
103             return typeof Map !== "undefined" && "entries" in Map.prototype && new Map([[0, 0]]).size === 1 ? Map : undefined;
104         }
105         NativeCollections.tryGetNativeMap = tryGetNativeMap;
106         /**
107          * Returns the native Set implementation if it is available and compatible (i.e. supports iteration).
108          */
109         function tryGetNativeSet() {
110             // Internet Explorer's Set doesn't support iteration, so don't use it.
111             // eslint-disable-next-line no-in-operator
112             return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined;
113         }
114         NativeCollections.tryGetNativeSet = tryGetNativeSet;
115     })(NativeCollections = ts.NativeCollections || (ts.NativeCollections = {}));
116 })(ts || (ts = {}));
117 /* @internal */
118 var ts;
119 (function (ts) {
120     function getCollectionImplementation(name, nativeFactory, shimFactory) {
121         var _a;
122         // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
123         var constructor = (_a = ts.NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](getIterator);
124         if (constructor)
125             return constructor;
126         throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation.");
127     }
128     ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim");
129     ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim");
130     function getIterator(iterable) {
131         if (iterable) {
132             if (isArray(iterable))
133                 return arrayIterator(iterable);
134             if (iterable instanceof ts.Map)
135                 return iterable.entries();
136             if (iterable instanceof ts.Set)
137                 return iterable.values();
138             throw new Error("Iteration not supported.");
139         }
140     }
141     ts.getIterator = getIterator;
142     ts.emptyArray = [];
143     ts.emptyMap = new ts.Map();
144     ts.emptySet = new ts.Set();
145     function createMap() {
146         return new ts.Map();
147     }
148     ts.createMap = createMap;
149     /**
150      * Create a new map from a template object is provided, the map will copy entries from it.
151      * @deprecated Use `new Map(getEntries(template))` instead.
152      */
153     function createMapFromTemplate(template) {
154         var map = new ts.Map();
155         // Copies keys/values from template. Note that for..in will not throw if
156         // template is undefined, and instead will just exit the loop.
157         for (var key in template) {
158             if (hasOwnProperty.call(template, key)) {
159                 map.set(key, template[key]);
160             }
161         }
162         return map;
163     }
164     ts.createMapFromTemplate = createMapFromTemplate;
165     function length(array) {
166         return array ? array.length : 0;
167     }
168     ts.length = length;
169     /**
170      * Iterates through 'array' by index and performs the callback on each element of array until the callback
171      * returns a truthy value, then returns that value.
172      * If no such value is found, the callback is applied to each element of array and undefined is returned.
173      */
174     function forEach(array, callback) {
175         if (array) {
176             for (var i = 0; i < array.length; i++) {
177                 var result = callback(array[i], i);
178                 if (result) {
179                     return result;
180                 }
181             }
182         }
183         return undefined;
184     }
185     ts.forEach = forEach;
186     /**
187      * Like `forEach`, but iterates in reverse order.
188      */
189     function forEachRight(array, callback) {
190         if (array) {
191             for (var i = array.length - 1; i >= 0; i--) {
192                 var result = callback(array[i], i);
193                 if (result) {
194                     return result;
195                 }
196             }
197         }
198         return undefined;
199     }
200     ts.forEachRight = forEachRight;
201     /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
202     function firstDefined(array, callback) {
203         if (array === undefined) {
204             return undefined;
205         }
206         for (var i = 0; i < array.length; i++) {
207             var result = callback(array[i], i);
208             if (result !== undefined) {
209                 return result;
210             }
211         }
212         return undefined;
213     }
214     ts.firstDefined = firstDefined;
215     function firstDefinedIterator(iter, callback) {
216         while (true) {
217             var iterResult = iter.next();
218             if (iterResult.done) {
219                 return undefined;
220             }
221             var result = callback(iterResult.value);
222             if (result !== undefined) {
223                 return result;
224             }
225         }
226     }
227     ts.firstDefinedIterator = firstDefinedIterator;
228     function reduceLeftIterator(iterator, f, initial) {
229         var result = initial;
230         if (iterator) {
231             for (var step = iterator.next(), pos = 0; !step.done; step = iterator.next(), pos++) {
232                 result = f(result, step.value, pos);
233             }
234         }
235         return result;
236     }
237     ts.reduceLeftIterator = reduceLeftIterator;
238     function zipWith(arrayA, arrayB, callback) {
239         var result = [];
240         ts.Debug.assertEqual(arrayA.length, arrayB.length);
241         for (var i = 0; i < arrayA.length; i++) {
242             result.push(callback(arrayA[i], arrayB[i], i));
243         }
244         return result;
245     }
246     ts.zipWith = zipWith;
247     function zipToIterator(arrayA, arrayB) {
248         ts.Debug.assertEqual(arrayA.length, arrayB.length);
249         var i = 0;
250         return {
251             next: function () {
252                 if (i === arrayA.length) {
253                     return { value: undefined, done: true };
254                 }
255                 i++;
256                 return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
257             }
258         };
259     }
260     ts.zipToIterator = zipToIterator;
261     function zipToMap(keys, values) {
262         ts.Debug.assert(keys.length === values.length);
263         var map = new ts.Map();
264         for (var i = 0; i < keys.length; ++i) {
265             map.set(keys[i], values[i]);
266         }
267         return map;
268     }
269     ts.zipToMap = zipToMap;
270     /**
271      * Creates a new array with `element` interspersed in between each element of `input`
272      * if there is more than 1 value in `input`. Otherwise, returns the existing array.
273      */
274     function intersperse(input, element) {
275         if (input.length <= 1) {
276             return input;
277         }
278         var result = [];
279         for (var i = 0, n = input.length; i < n; i++) {
280             if (i)
281                 result.push(element);
282             result.push(input[i]);
283         }
284         return result;
285     }
286     ts.intersperse = intersperse;
287     /**
288      * Iterates through `array` by index and performs the callback on each element of array until the callback
289      * returns a falsey value, then returns false.
290      * If no such value is found, the callback is applied to each element of array and `true` is returned.
291      */
292     function every(array, callback) {
293         if (array) {
294             for (var i = 0; i < array.length; i++) {
295                 if (!callback(array[i], i)) {
296                     return false;
297                 }
298             }
299         }
300         return true;
301     }
302     ts.every = every;
303     function find(array, predicate) {
304         for (var i = 0; i < array.length; i++) {
305             var value = array[i];
306             if (predicate(value, i)) {
307                 return value;
308             }
309         }
310         return undefined;
311     }
312     ts.find = find;
313     function findLast(array, predicate) {
314         for (var i = array.length - 1; i >= 0; i--) {
315             var value = array[i];
316             if (predicate(value, i)) {
317                 return value;
318             }
319         }
320         return undefined;
321     }
322     ts.findLast = findLast;
323     /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
324     function findIndex(array, predicate, startIndex) {
325         for (var i = startIndex || 0; i < array.length; i++) {
326             if (predicate(array[i], i)) {
327                 return i;
328             }
329         }
330         return -1;
331     }
332     ts.findIndex = findIndex;
333     function findLastIndex(array, predicate, startIndex) {
334         for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
335             if (predicate(array[i], i)) {
336                 return i;
337             }
338         }
339         return -1;
340     }
341     ts.findLastIndex = findLastIndex;
342     /**
343      * Returns the first truthy result of `callback`, or else fails.
344      * This is like `forEach`, but never returns undefined.
345      */
346     function findMap(array, callback) {
347         for (var i = 0; i < array.length; i++) {
348             var result = callback(array[i], i);
349             if (result) {
350                 return result;
351             }
352         }
353         return ts.Debug.fail();
354     }
355     ts.findMap = findMap;
356     function contains(array, value, equalityComparer) {
357         if (equalityComparer === void 0) { equalityComparer = equateValues; }
358         if (array) {
359             for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
360                 var v = array_1[_i];
361                 if (equalityComparer(v, value)) {
362                     return true;
363                 }
364             }
365         }
366         return false;
367     }
368     ts.contains = contains;
369     function arraysEqual(a, b, equalityComparer) {
370         if (equalityComparer === void 0) { equalityComparer = equateValues; }
371         return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
372     }
373     ts.arraysEqual = arraysEqual;
374     function indexOfAnyCharCode(text, charCodes, start) {
375         for (var i = start || 0; i < text.length; i++) {
376             if (contains(charCodes, text.charCodeAt(i))) {
377                 return i;
378             }
379         }
380         return -1;
381     }
382     ts.indexOfAnyCharCode = indexOfAnyCharCode;
383     function countWhere(array, predicate) {
384         var count = 0;
385         if (array) {
386             for (var i = 0; i < array.length; i++) {
387                 var v = array[i];
388                 if (predicate(v, i)) {
389                     count++;
390                 }
391             }
392         }
393         return count;
394     }
395     ts.countWhere = countWhere;
396     function filter(array, f) {
397         if (array) {
398             var len = array.length;
399             var i = 0;
400             while (i < len && f(array[i]))
401                 i++;
402             if (i < len) {
403                 var result = array.slice(0, i);
404                 i++;
405                 while (i < len) {
406                     var item = array[i];
407                     if (f(item)) {
408                         result.push(item);
409                     }
410                     i++;
411                 }
412                 return result;
413             }
414         }
415         return array;
416     }
417     ts.filter = filter;
418     function filterMutate(array, f) {
419         var outIndex = 0;
420         for (var i = 0; i < array.length; i++) {
421             if (f(array[i], i, array)) {
422                 array[outIndex] = array[i];
423                 outIndex++;
424             }
425         }
426         array.length = outIndex;
427     }
428     ts.filterMutate = filterMutate;
429     function clear(array) {
430         array.length = 0;
431     }
432     ts.clear = clear;
433     function map(array, f) {
434         var result;
435         if (array) {
436             result = [];
437             for (var i = 0; i < array.length; i++) {
438                 result.push(f(array[i], i));
439             }
440         }
441         return result;
442     }
443     ts.map = map;
444     function mapIterator(iter, mapFn) {
445         return {
446             next: function () {
447                 var iterRes = iter.next();
448                 return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
449             }
450         };
451     }
452     ts.mapIterator = mapIterator;
453     function sameMap(array, f) {
454         if (array) {
455             for (var i = 0; i < array.length; i++) {
456                 var item = array[i];
457                 var mapped = f(item, i);
458                 if (item !== mapped) {
459                     var result = array.slice(0, i);
460                     result.push(mapped);
461                     for (i++; i < array.length; i++) {
462                         result.push(f(array[i], i));
463                     }
464                     return result;
465                 }
466             }
467         }
468         return array;
469     }
470     ts.sameMap = sameMap;
471     /**
472      * Flattens an array containing a mix of array or non-array elements.
473      *
474      * @param array The array to flatten.
475      */
476     function flatten(array) {
477         var result = [];
478         for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
479             var v = array_2[_i];
480             if (v) {
481                 if (isArray(v)) {
482                     addRange(result, v);
483                 }
484                 else {
485                     result.push(v);
486                 }
487             }
488         }
489         return result;
490     }
491     ts.flatten = flatten;
492     /**
493      * Maps an array. If the mapped value is an array, it is spread into the result.
494      *
495      * @param array The array to map.
496      * @param mapfn The callback used to map the result into one or more values.
497      */
498     function flatMap(array, mapfn) {
499         var result;
500         if (array) {
501             for (var i = 0; i < array.length; i++) {
502                 var v = mapfn(array[i], i);
503                 if (v) {
504                     if (isArray(v)) {
505                         result = addRange(result, v);
506                     }
507                     else {
508                         result = append(result, v);
509                     }
510                 }
511             }
512         }
513         return result || ts.emptyArray;
514     }
515     ts.flatMap = flatMap;
516     function flatMapToMutable(array, mapfn) {
517         var result = [];
518         if (array) {
519             for (var i = 0; i < array.length; i++) {
520                 var v = mapfn(array[i], i);
521                 if (v) {
522                     if (isArray(v)) {
523                         addRange(result, v);
524                     }
525                     else {
526                         result.push(v);
527                     }
528                 }
529             }
530         }
531         return result;
532     }
533     ts.flatMapToMutable = flatMapToMutable;
534     function flatMapIterator(iter, mapfn) {
535         var first = iter.next();
536         if (first.done) {
537             return ts.emptyIterator;
538         }
539         var currentIter = getIterator(first.value);
540         return {
541             next: function () {
542                 while (true) {
543                     var currentRes = currentIter.next();
544                     if (!currentRes.done) {
545                         return currentRes;
546                     }
547                     var iterRes = iter.next();
548                     if (iterRes.done) {
549                         return iterRes;
550                     }
551                     currentIter = getIterator(iterRes.value);
552                 }
553             },
554         };
555         function getIterator(x) {
556             var res = mapfn(x);
557             return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
558         }
559     }
560     ts.flatMapIterator = flatMapIterator;
561     function sameFlatMap(array, mapfn) {
562         var result;
563         if (array) {
564             for (var i = 0; i < array.length; i++) {
565                 var item = array[i];
566                 var mapped = mapfn(item, i);
567                 if (result || item !== mapped || isArray(mapped)) {
568                     if (!result) {
569                         result = array.slice(0, i);
570                     }
571                     if (isArray(mapped)) {
572                         addRange(result, mapped);
573                     }
574                     else {
575                         result.push(mapped);
576                     }
577                 }
578             }
579         }
580         return result || array;
581     }
582     ts.sameFlatMap = sameFlatMap;
583     function mapAllOrFail(array, mapFn) {
584         var result = [];
585         for (var i = 0; i < array.length; i++) {
586             var mapped = mapFn(array[i], i);
587             if (mapped === undefined) {
588                 return undefined;
589             }
590             result.push(mapped);
591         }
592         return result;
593     }
594     ts.mapAllOrFail = mapAllOrFail;
595     function mapDefined(array, mapFn) {
596         var result = [];
597         if (array) {
598             for (var i = 0; i < array.length; i++) {
599                 var mapped = mapFn(array[i], i);
600                 if (mapped !== undefined) {
601                     result.push(mapped);
602                 }
603             }
604         }
605         return result;
606     }
607     ts.mapDefined = mapDefined;
608     function mapDefinedIterator(iter, mapFn) {
609         return {
610             next: function () {
611                 while (true) {
612                     var res = iter.next();
613                     if (res.done) {
614                         return res;
615                     }
616                     var value = mapFn(res.value);
617                     if (value !== undefined) {
618                         return { value: value, done: false };
619                     }
620                 }
621             }
622         };
623     }
624     ts.mapDefinedIterator = mapDefinedIterator;
625     function mapDefinedEntries(map, f) {
626         if (!map) {
627             return undefined;
628         }
629         var result = new ts.Map();
630         map.forEach(function (value, key) {
631             var entry = f(key, value);
632             if (entry !== undefined) {
633                 var newKey = entry[0], newValue = entry[1];
634                 if (newKey !== undefined && newValue !== undefined) {
635                     result.set(newKey, newValue);
636                 }
637             }
638         });
639         return result;
640     }
641     ts.mapDefinedEntries = mapDefinedEntries;
642     function mapDefinedValues(set, f) {
643         if (set) {
644             var result_1 = new ts.Set();
645             set.forEach(function (value) {
646                 var newValue = f(value);
647                 if (newValue !== undefined) {
648                     result_1.add(newValue);
649                 }
650             });
651             return result_1;
652         }
653     }
654     ts.mapDefinedValues = mapDefinedValues;
655     function getOrUpdate(map, key, callback) {
656         if (map.has(key)) {
657             return map.get(key);
658         }
659         var value = callback();
660         map.set(key, value);
661         return value;
662     }
663     ts.getOrUpdate = getOrUpdate;
664     function tryAddToSet(set, value) {
665         if (!set.has(value)) {
666             set.add(value);
667             return true;
668         }
669         return false;
670     }
671     ts.tryAddToSet = tryAddToSet;
672     ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
673     function singleIterator(value) {
674         var done = false;
675         return {
676             next: function () {
677                 var wasDone = done;
678                 done = true;
679                 return wasDone ? { value: undefined, done: true } : { value: value, done: false };
680             }
681         };
682     }
683     ts.singleIterator = singleIterator;
684     function spanMap(array, keyfn, mapfn) {
685         var result;
686         if (array) {
687             result = [];
688             var len = array.length;
689             var previousKey = void 0;
690             var key = void 0;
691             var start = 0;
692             var pos = 0;
693             while (start < len) {
694                 while (pos < len) {
695                     var value = array[pos];
696                     key = keyfn(value, pos);
697                     if (pos === 0) {
698                         previousKey = key;
699                     }
700                     else if (key !== previousKey) {
701                         break;
702                     }
703                     pos++;
704                 }
705                 if (start < pos) {
706                     var v = mapfn(array.slice(start, pos), previousKey, start, pos);
707                     if (v) {
708                         result.push(v);
709                     }
710                     start = pos;
711                 }
712                 previousKey = key;
713                 pos++;
714             }
715         }
716         return result;
717     }
718     ts.spanMap = spanMap;
719     function mapEntries(map, f) {
720         if (!map) {
721             return undefined;
722         }
723         var result = new ts.Map();
724         map.forEach(function (value, key) {
725             var _a = f(key, value), newKey = _a[0], newValue = _a[1];
726             result.set(newKey, newValue);
727         });
728         return result;
729     }
730     ts.mapEntries = mapEntries;
731     function some(array, predicate) {
732         if (array) {
733             if (predicate) {
734                 for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
735                     var v = array_3[_i];
736                     if (predicate(v)) {
737                         return true;
738                     }
739                 }
740             }
741             else {
742                 return array.length > 0;
743             }
744         }
745         return false;
746     }
747     ts.some = some;
748     /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
749     function getRangesWhere(arr, pred, cb) {
750         var start;
751         for (var i = 0; i < arr.length; i++) {
752             if (pred(arr[i])) {
753                 start = start === undefined ? i : start;
754             }
755             else {
756                 if (start !== undefined) {
757                     cb(start, i);
758                     start = undefined;
759                 }
760             }
761         }
762         if (start !== undefined)
763             cb(start, arr.length);
764     }
765     ts.getRangesWhere = getRangesWhere;
766     function concatenate(array1, array2) {
767         if (!some(array2))
768             return array1;
769         if (!some(array1))
770             return array2;
771         return __spreadArrays(array1, array2);
772     }
773     ts.concatenate = concatenate;
774     function selectIndex(_, i) {
775         return i;
776     }
777     function indicesOf(array) {
778         return array.map(selectIndex);
779     }
780     ts.indicesOf = indicesOf;
781     function deduplicateRelational(array, equalityComparer, comparer) {
782         // Perform a stable sort of the array. This ensures the first entry in a list of
783         // duplicates remains the first entry in the result.
784         var indices = indicesOf(array);
785         stableSortIndices(array, indices, comparer);
786         var last = array[indices[0]];
787         var deduplicated = [indices[0]];
788         for (var i = 1; i < indices.length; i++) {
789             var index = indices[i];
790             var item = array[index];
791             if (!equalityComparer(last, item)) {
792                 deduplicated.push(index);
793                 last = item;
794             }
795         }
796         // restore original order
797         deduplicated.sort();
798         return deduplicated.map(function (i) { return array[i]; });
799     }
800     function deduplicateEquality(array, equalityComparer) {
801         var result = [];
802         for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
803             var item = array_4[_i];
804             pushIfUnique(result, item, equalityComparer);
805         }
806         return result;
807     }
808     /**
809      * Deduplicates an unsorted array.
810      * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
811      * @param comparer An optional `Comparer` used to sort entries before comparison, though the
812      * result will remain in the original order in `array`.
813      */
814     function deduplicate(array, equalityComparer, comparer) {
815         return array.length === 0 ? [] :
816             array.length === 1 ? array.slice() :
817                 comparer ? deduplicateRelational(array, equalityComparer, comparer) :
818                     deduplicateEquality(array, equalityComparer);
819     }
820     ts.deduplicate = deduplicate;
821     /**
822      * Deduplicates an array that has already been sorted.
823      */
824     function deduplicateSorted(array, comparer) {
825         if (array.length === 0)
826             return ts.emptyArray;
827         var last = array[0];
828         var deduplicated = [last];
829         for (var i = 1; i < array.length; i++) {
830             var next = array[i];
831             switch (comparer(next, last)) {
832                 // equality comparison
833                 case true:
834                 // relational comparison
835                 // falls through
836                 case 0 /* EqualTo */:
837                     continue;
838                 case -1 /* LessThan */:
839                     // If `array` is sorted, `next` should **never** be less than `last`.
840                     return ts.Debug.fail("Array is unsorted.");
841             }
842             deduplicated.push(last = next);
843         }
844         return deduplicated;
845     }
846     function insertSorted(array, insert, compare) {
847         if (array.length === 0) {
848             array.push(insert);
849             return;
850         }
851         var insertIndex = binarySearch(array, insert, identity, compare);
852         if (insertIndex < 0) {
853             array.splice(~insertIndex, 0, insert);
854         }
855     }
856     ts.insertSorted = insertSorted;
857     function sortAndDeduplicate(array, comparer, equalityComparer) {
858         return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
859     }
860     ts.sortAndDeduplicate = sortAndDeduplicate;
861     function arrayIsSorted(array, comparer) {
862         if (array.length < 2)
863             return true;
864         var prevElement = array[0];
865         for (var _i = 0, _a = array.slice(1); _i < _a.length; _i++) {
866             var element = _a[_i];
867             if (comparer(prevElement, element) === 1 /* GreaterThan */) {
868                 return false;
869             }
870             prevElement = element;
871         }
872         return true;
873     }
874     ts.arrayIsSorted = arrayIsSorted;
875     function arrayIsEqualTo(array1, array2, equalityComparer) {
876         if (equalityComparer === void 0) { equalityComparer = equateValues; }
877         if (!array1 || !array2) {
878             return array1 === array2;
879         }
880         if (array1.length !== array2.length) {
881             return false;
882         }
883         for (var i = 0; i < array1.length; i++) {
884             if (!equalityComparer(array1[i], array2[i], i)) {
885                 return false;
886             }
887         }
888         return true;
889     }
890     ts.arrayIsEqualTo = arrayIsEqualTo;
891     function compact(array) {
892         var result;
893         if (array) {
894             for (var i = 0; i < array.length; i++) {
895                 var v = array[i];
896                 if (result || !v) {
897                     if (!result) {
898                         result = array.slice(0, i);
899                     }
900                     if (v) {
901                         result.push(v);
902                     }
903                 }
904             }
905         }
906         return result || array;
907     }
908     ts.compact = compact;
909     /**
910      * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
911      * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
912      * based on the provided comparer.
913      */
914     function relativeComplement(arrayA, arrayB, comparer) {
915         if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
916             return arrayB;
917         var result = [];
918         loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
919             if (offsetB > 0) {
920                 // Ensure `arrayB` is properly sorted.
921                 ts.Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
922             }
923             loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
924                 if (offsetA > startA) {
925                     // Ensure `arrayA` is properly sorted. We only need to perform this check if
926                     // `offsetA` has changed since we entered the loop.
927                     ts.Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
928                 }
929                 switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
930                     case -1 /* LessThan */:
931                         // If B is less than A, B does not exist in arrayA. Add B to the result and
932                         // move to the next element in arrayB without changing the current position
933                         // in arrayA.
934                         result.push(arrayB[offsetB]);
935                         continue loopB;
936                     case 0 /* EqualTo */:
937                         // If B is equal to A, B exists in arrayA. Move to the next element in
938                         // arrayB without adding B to the result or changing the current position
939                         // in arrayA.
940                         continue loopB;
941                     case 1 /* GreaterThan */:
942                         // If B is greater than A, we need to keep looking for B in arrayA. Move to
943                         // the next element in arrayA and recheck.
944                         continue loopA;
945                 }
946             }
947         }
948         return result;
949     }
950     ts.relativeComplement = relativeComplement;
951     function sum(array, prop) {
952         var result = 0;
953         for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
954             var v = array_5[_i];
955             result += v[prop];
956         }
957         return result;
958     }
959     ts.sum = sum;
960     function append(to, value) {
961         if (value === undefined)
962             return to;
963         if (to === undefined)
964             return [value];
965         to.push(value);
966         return to;
967     }
968     ts.append = append;
969     function combine(xs, ys) {
970         if (xs === undefined)
971             return ys;
972         if (ys === undefined)
973             return xs;
974         if (isArray(xs))
975             return isArray(ys) ? concatenate(xs, ys) : append(xs, ys);
976         if (isArray(ys))
977             return append(ys, xs);
978         return [xs, ys];
979     }
980     ts.combine = combine;
981     /**
982      * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
983      * position offset from the end of the array.
984      */
985     function toOffset(array, offset) {
986         return offset < 0 ? array.length + offset : offset;
987     }
988     function addRange(to, from, start, end) {
989         if (from === undefined || from.length === 0)
990             return to;
991         if (to === undefined)
992             return from.slice(start, end);
993         start = start === undefined ? 0 : toOffset(from, start);
994         end = end === undefined ? from.length : toOffset(from, end);
995         for (var i = start; i < end && i < from.length; i++) {
996             if (from[i] !== undefined) {
997                 to.push(from[i]);
998             }
999         }
1000         return to;
1001     }
1002     ts.addRange = addRange;
1003     /**
1004      * @return Whether the value was added.
1005      */
1006     function pushIfUnique(array, toAdd, equalityComparer) {
1007         if (contains(array, toAdd, equalityComparer)) {
1008             return false;
1009         }
1010         else {
1011             array.push(toAdd);
1012             return true;
1013         }
1014     }
1015     ts.pushIfUnique = pushIfUnique;
1016     /**
1017      * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
1018      */
1019     function appendIfUnique(array, toAdd, equalityComparer) {
1020         if (array) {
1021             pushIfUnique(array, toAdd, equalityComparer);
1022             return array;
1023         }
1024         else {
1025             return [toAdd];
1026         }
1027     }
1028     ts.appendIfUnique = appendIfUnique;
1029     function stableSortIndices(array, indices, comparer) {
1030         // sort indices by value then position
1031         indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
1032     }
1033     /**
1034      * Returns a new sorted array.
1035      */
1036     function sort(array, comparer) {
1037         return (array.length === 0 ? array : array.slice().sort(comparer));
1038     }
1039     ts.sort = sort;
1040     function arrayIterator(array) {
1041         var i = 0;
1042         return { next: function () {
1043                 if (i === array.length) {
1044                     return { value: undefined, done: true };
1045                 }
1046                 else {
1047                     i++;
1048                     return { value: array[i - 1], done: false };
1049                 }
1050             } };
1051     }
1052     ts.arrayIterator = arrayIterator;
1053     function arrayReverseIterator(array) {
1054         var i = array.length;
1055         return {
1056             next: function () {
1057                 if (i === 0) {
1058                     return { value: undefined, done: true };
1059                 }
1060                 else {
1061                     i--;
1062                     return { value: array[i], done: false };
1063                 }
1064             }
1065         };
1066     }
1067     ts.arrayReverseIterator = arrayReverseIterator;
1068     /**
1069      * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
1070      */
1071     function stableSort(array, comparer) {
1072         var indices = indicesOf(array);
1073         stableSortIndices(array, indices, comparer);
1074         return indices.map(function (i) { return array[i]; });
1075     }
1076     ts.stableSort = stableSort;
1077     function rangeEquals(array1, array2, pos, end) {
1078         while (pos < end) {
1079             if (array1[pos] !== array2[pos]) {
1080                 return false;
1081             }
1082             pos++;
1083         }
1084         return true;
1085     }
1086     ts.rangeEquals = rangeEquals;
1087     /**
1088      * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
1089      * A negative offset indicates the element should be retrieved from the end of the array.
1090      */
1091     function elementAt(array, offset) {
1092         if (array) {
1093             offset = toOffset(array, offset);
1094             if (offset < array.length) {
1095                 return array[offset];
1096             }
1097         }
1098         return undefined;
1099     }
1100     ts.elementAt = elementAt;
1101     /**
1102      * Returns the first element of an array if non-empty, `undefined` otherwise.
1103      */
1104     function firstOrUndefined(array) {
1105         return array.length === 0 ? undefined : array[0];
1106     }
1107     ts.firstOrUndefined = firstOrUndefined;
1108     function first(array) {
1109         ts.Debug.assert(array.length !== 0);
1110         return array[0];
1111     }
1112     ts.first = first;
1113     /**
1114      * Returns the last element of an array if non-empty, `undefined` otherwise.
1115      */
1116     function lastOrUndefined(array) {
1117         return array.length === 0 ? undefined : array[array.length - 1];
1118     }
1119     ts.lastOrUndefined = lastOrUndefined;
1120     function last(array) {
1121         ts.Debug.assert(array.length !== 0);
1122         return array[array.length - 1];
1123     }
1124     ts.last = last;
1125     /**
1126      * Returns the only element of an array if it contains only one element, `undefined` otherwise.
1127      */
1128     function singleOrUndefined(array) {
1129         return array && array.length === 1
1130             ? array[0]
1131             : undefined;
1132     }
1133     ts.singleOrUndefined = singleOrUndefined;
1134     function singleOrMany(array) {
1135         return array && array.length === 1
1136             ? array[0]
1137             : array;
1138     }
1139     ts.singleOrMany = singleOrMany;
1140     function replaceElement(array, index, value) {
1141         var result = array.slice(0);
1142         result[index] = value;
1143         return result;
1144     }
1145     ts.replaceElement = replaceElement;
1146     /**
1147      * Performs a binary search, finding the index at which `value` occurs in `array`.
1148      * If no such index is found, returns the 2's-complement of first index at which
1149      * `array[index]` exceeds `value`.
1150      * @param array A sorted array whose first element must be no larger than number
1151      * @param value The value to be searched for in the array.
1152      * @param keySelector A callback used to select the search key from `value` and each element of
1153      * `array`.
1154      * @param keyComparer A callback used to compare two keys in a sorted array.
1155      * @param offset An offset into `array` at which to start the search.
1156      */
1157     function binarySearch(array, value, keySelector, keyComparer, offset) {
1158         return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
1159     }
1160     ts.binarySearch = binarySearch;
1161     /**
1162      * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
1163      * If no such index is found, returns the 2's-complement of first index at which
1164      * `array[index]` exceeds `key`.
1165      * @param array A sorted array whose first element must be no larger than number
1166      * @param key The key to be searched for in the array.
1167      * @param keySelector A callback used to select the search key from each element of `array`.
1168      * @param keyComparer A callback used to compare two keys in a sorted array.
1169      * @param offset An offset into `array` at which to start the search.
1170      */
1171     function binarySearchKey(array, key, keySelector, keyComparer, offset) {
1172         if (!some(array)) {
1173             return -1;
1174         }
1175         var low = offset || 0;
1176         var high = array.length - 1;
1177         while (low <= high) {
1178             var middle = low + ((high - low) >> 1);
1179             var midKey = keySelector(array[middle], middle);
1180             switch (keyComparer(midKey, key)) {
1181                 case -1 /* LessThan */:
1182                     low = middle + 1;
1183                     break;
1184                 case 0 /* EqualTo */:
1185                     return middle;
1186                 case 1 /* GreaterThan */:
1187                     high = middle - 1;
1188                     break;
1189             }
1190         }
1191         return ~low;
1192     }
1193     ts.binarySearchKey = binarySearchKey;
1194     function reduceLeft(array, f, initial, start, count) {
1195         if (array && array.length > 0) {
1196             var size = array.length;
1197             if (size > 0) {
1198                 var pos = start === undefined || start < 0 ? 0 : start;
1199                 var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
1200                 var result = void 0;
1201                 if (arguments.length <= 2) {
1202                     result = array[pos];
1203                     pos++;
1204                 }
1205                 else {
1206                     result = initial;
1207                 }
1208                 while (pos <= end) {
1209                     result = f(result, array[pos], pos);
1210                     pos++;
1211                 }
1212                 return result;
1213             }
1214         }
1215         return initial;
1216     }
1217     ts.reduceLeft = reduceLeft;
1218     var hasOwnProperty = Object.prototype.hasOwnProperty;
1219     /**
1220      * Indicates whether a map-like contains an own property with the specified key.
1221      *
1222      * @param map A map-like.
1223      * @param key A property key.
1224      */
1225     function hasProperty(map, key) {
1226         return hasOwnProperty.call(map, key);
1227     }
1228     ts.hasProperty = hasProperty;
1229     /**
1230      * Gets the value of an owned property in a map-like.
1231      *
1232      * @param map A map-like.
1233      * @param key A property key.
1234      */
1235     function getProperty(map, key) {
1236         return hasOwnProperty.call(map, key) ? map[key] : undefined;
1237     }
1238     ts.getProperty = getProperty;
1239     /**
1240      * Gets the owned, enumerable property keys of a map-like.
1241      */
1242     function getOwnKeys(map) {
1243         var keys = [];
1244         for (var key in map) {
1245             if (hasOwnProperty.call(map, key)) {
1246                 keys.push(key);
1247             }
1248         }
1249         return keys;
1250     }
1251     ts.getOwnKeys = getOwnKeys;
1252     function getAllKeys(obj) {
1253         var result = [];
1254         do {
1255             var names = Object.getOwnPropertyNames(obj);
1256             for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
1257                 var name = names_1[_i];
1258                 pushIfUnique(result, name);
1259             }
1260         } while (obj = Object.getPrototypeOf(obj));
1261         return result;
1262     }
1263     ts.getAllKeys = getAllKeys;
1264     function getOwnValues(sparseArray) {
1265         var values = [];
1266         for (var key in sparseArray) {
1267             if (hasOwnProperty.call(sparseArray, key)) {
1268                 values.push(sparseArray[key]);
1269             }
1270         }
1271         return values;
1272     }
1273     ts.getOwnValues = getOwnValues;
1274     var _entries = Object.entries || (function (obj) {
1275         var keys = getOwnKeys(obj);
1276         var result = Array(keys.length);
1277         for (var i = 0; i < keys.length; i++) {
1278             result[i] = [keys[i], obj[keys[i]]];
1279         }
1280         return result;
1281     });
1282     function getEntries(obj) {
1283         return obj ? _entries(obj) : [];
1284     }
1285     ts.getEntries = getEntries;
1286     function arrayOf(count, f) {
1287         var result = new Array(count);
1288         for (var i = 0; i < count; i++) {
1289             result[i] = f(i);
1290         }
1291         return result;
1292     }
1293     ts.arrayOf = arrayOf;
1294     function arrayFrom(iterator, map) {
1295         var result = [];
1296         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
1297             result.push(map ? map(iterResult.value) : iterResult.value);
1298         }
1299         return result;
1300     }
1301     ts.arrayFrom = arrayFrom;
1302     function assign(t) {
1303         var args = [];
1304         for (var _i = 1; _i < arguments.length; _i++) {
1305             args[_i - 1] = arguments[_i];
1306         }
1307         for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1308             var arg = args_1[_a];
1309             if (arg === undefined)
1310                 continue;
1311             for (var p in arg) {
1312                 if (hasProperty(arg, p)) {
1313                     t[p] = arg[p];
1314                 }
1315             }
1316         }
1317         return t;
1318     }
1319     ts.assign = assign;
1320     /**
1321      * Performs a shallow equality comparison of the contents of two map-likes.
1322      *
1323      * @param left A map-like whose properties should be compared.
1324      * @param right A map-like whose properties should be compared.
1325      */
1326     function equalOwnProperties(left, right, equalityComparer) {
1327         if (equalityComparer === void 0) { equalityComparer = equateValues; }
1328         if (left === right)
1329             return true;
1330         if (!left || !right)
1331             return false;
1332         for (var key in left) {
1333             if (hasOwnProperty.call(left, key)) {
1334                 if (!hasOwnProperty.call(right, key))
1335                     return false;
1336                 if (!equalityComparer(left[key], right[key]))
1337                     return false;
1338             }
1339         }
1340         for (var key in right) {
1341             if (hasOwnProperty.call(right, key)) {
1342                 if (!hasOwnProperty.call(left, key))
1343                     return false;
1344             }
1345         }
1346         return true;
1347     }
1348     ts.equalOwnProperties = equalOwnProperties;
1349     function arrayToMap(array, makeKey, makeValue) {
1350         if (makeValue === void 0) { makeValue = identity; }
1351         var result = new ts.Map();
1352         for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1353             var value = array_6[_i];
1354             var key = makeKey(value);
1355             if (key !== undefined)
1356                 result.set(key, makeValue(value));
1357         }
1358         return result;
1359     }
1360     ts.arrayToMap = arrayToMap;
1361     function arrayToNumericMap(array, makeKey, makeValue) {
1362         if (makeValue === void 0) { makeValue = identity; }
1363         var result = [];
1364         for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1365             var value = array_7[_i];
1366             result[makeKey(value)] = makeValue(value);
1367         }
1368         return result;
1369     }
1370     ts.arrayToNumericMap = arrayToNumericMap;
1371     function arrayToMultiMap(values, makeKey, makeValue) {
1372         if (makeValue === void 0) { makeValue = identity; }
1373         var result = createMultiMap();
1374         for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1375             var value = values_1[_i];
1376             result.add(makeKey(value), makeValue(value));
1377         }
1378         return result;
1379     }
1380     ts.arrayToMultiMap = arrayToMultiMap;
1381     function group(values, getGroupId, resultSelector) {
1382         if (resultSelector === void 0) { resultSelector = identity; }
1383         return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
1384     }
1385     ts.group = group;
1386     function clone(object) {
1387         var result = {};
1388         for (var id in object) {
1389             if (hasOwnProperty.call(object, id)) {
1390                 result[id] = object[id];
1391             }
1392         }
1393         return result;
1394     }
1395     ts.clone = clone;
1396     /**
1397      * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
1398      *
1399      * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
1400      */
1401     function extend(first, second) {
1402         var result = {};
1403         for (var id in second) {
1404             if (hasOwnProperty.call(second, id)) {
1405                 result[id] = second[id];
1406             }
1407         }
1408         for (var id in first) {
1409             if (hasOwnProperty.call(first, id)) {
1410                 result[id] = first[id];
1411             }
1412         }
1413         return result;
1414     }
1415     ts.extend = extend;
1416     function copyProperties(first, second) {
1417         for (var id in second) {
1418             if (hasOwnProperty.call(second, id)) {
1419                 first[id] = second[id];
1420             }
1421         }
1422     }
1423     ts.copyProperties = copyProperties;
1424     function maybeBind(obj, fn) {
1425         return fn ? fn.bind(obj) : undefined;
1426     }
1427     ts.maybeBind = maybeBind;
1428     function createMultiMap() {
1429         var map = new ts.Map();
1430         map.add = multiMapAdd;
1431         map.remove = multiMapRemove;
1432         return map;
1433     }
1434     ts.createMultiMap = createMultiMap;
1435     function multiMapAdd(key, value) {
1436         var values = this.get(key);
1437         if (values) {
1438             values.push(value);
1439         }
1440         else {
1441             this.set(key, values = [value]);
1442         }
1443         return values;
1444     }
1445     function multiMapRemove(key, value) {
1446         var values = this.get(key);
1447         if (values) {
1448             unorderedRemoveItem(values, value);
1449             if (!values.length) {
1450                 this.delete(key);
1451             }
1452         }
1453     }
1454     function createUnderscoreEscapedMultiMap() {
1455         return createMultiMap();
1456     }
1457     ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap;
1458     /**
1459      * Tests whether a value is an array.
1460      */
1461     function isArray(value) {
1462         return Array.isArray ? Array.isArray(value) : value instanceof Array;
1463     }
1464     ts.isArray = isArray;
1465     function toArray(value) {
1466         return isArray(value) ? value : [value];
1467     }
1468     ts.toArray = toArray;
1469     /**
1470      * Tests whether a value is string
1471      */
1472     function isString(text) {
1473         return typeof text === "string";
1474     }
1475     ts.isString = isString;
1476     function isNumber(x) {
1477         return typeof x === "number";
1478     }
1479     ts.isNumber = isNumber;
1480     function tryCast(value, test) {
1481         return value !== undefined && test(value) ? value : undefined;
1482     }
1483     ts.tryCast = tryCast;
1484     function cast(value, test) {
1485         if (value !== undefined && test(value))
1486             return value;
1487         return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
1488     }
1489     ts.cast = cast;
1490     /** Does nothing. */
1491     function noop(_) { }
1492     ts.noop = noop;
1493     /** Do nothing and return false */
1494     function returnFalse() { return false; }
1495     ts.returnFalse = returnFalse;
1496     /** Do nothing and return true */
1497     function returnTrue() { return true; }
1498     ts.returnTrue = returnTrue;
1499     /** Do nothing and return undefined */
1500     function returnUndefined() { return undefined; }
1501     ts.returnUndefined = returnUndefined;
1502     /** Returns its argument. */
1503     function identity(x) { return x; }
1504     ts.identity = identity;
1505     /** Returns lower case string */
1506     function toLowerCase(x) { return x.toLowerCase(); }
1507     ts.toLowerCase = toLowerCase;
1508     // We convert the file names to lower case as key for file name on case insensitive file system
1509     // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
1510     // it to lower case, fileName with its lowercase form can exist along side it.
1511     // Handle special characters and make those case sensitive instead
1512     //
1513     // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
1514     // | 1. | i        | 105       | Ascii i                                                                |
1515     // | 2. | I        | 73        | Ascii I                                                                |
1516     // |-------- Special characters ------------------------------------------------------------------------|
1517     // | 3. | \u0130   | 304       | Uppper case I with dot above                                           |
1518     // | 4. | i,\u0307 | 105,775   | i, followed by 775: Lower case of (3rd item)                           |
1519     // | 5. | I,\u0307 | 73,775    | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
1520     // | 6. | \u0131   | 305       | Lower case i without dot, upper case is I (2nd item)                   |
1521     // | 7. | \u00DF   | 223       | Lower case sharp s                                                     |
1522     //
1523     // Because item 3 is special where in its lowercase character has its own
1524     // upper case form we cant convert its case.
1525     // Rest special characters are either already in lower case format or
1526     // they have corresponding upper case character so they dont need special handling
1527     //
1528     // But to avoid having to do string building for most common cases, also ignore
1529     // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
1530     var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
1531     /**
1532      * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
1533      * This function is used in places where we want to make file name as a key on these systems
1534      * It is possible on mac to be able to refer to file name with I with dot on top as a fileName with its lower case form
1535      * But on windows we cannot. Windows can have fileName with I with dot on top next to its lower case and they can not each be referred with the lowercase forms
1536      * Technically we would want this function to be platform sepcific as well but
1537      * our api has till now only taken caseSensitive as the only input and just for some characters we dont want to update API and ensure all customers use those api
1538      * We could use upper case and we would still need to deal with the descripencies but
1539      * we want to continue using lower case since in most cases filenames are lowercasewe and wont need any case changes and avoid having to store another string for the key
1540      * So for this function purpose, we go ahead and assume character I with dot on top it as case sensitive since its very unlikely to use lower case form of that special character
1541      */
1542     function toFileNameLowerCase(x) {
1543         return fileNameLowerCaseRegExp.test(x) ?
1544             x.replace(fileNameLowerCaseRegExp, toLowerCase) :
1545             x;
1546     }
1547     ts.toFileNameLowerCase = toFileNameLowerCase;
1548     /** Throws an error because a function is not implemented. */
1549     function notImplemented() {
1550         throw new Error("Not implemented");
1551     }
1552     ts.notImplemented = notImplemented;
1553     function memoize(callback) {
1554         var value;
1555         return function () {
1556             if (callback) {
1557                 value = callback();
1558                 callback = undefined;
1559             }
1560             return value;
1561         };
1562     }
1563     ts.memoize = memoize;
1564     /** A version of `memoize` that supports a single primitive argument */
1565     function memoizeOne(callback) {
1566         var map = new ts.Map();
1567         return function (arg) {
1568             var key = typeof arg + ":" + arg;
1569             var value = map.get(key);
1570             if (value === undefined && !map.has(key)) {
1571                 value = callback(arg);
1572                 map.set(key, value);
1573             }
1574             return value;
1575         };
1576     }
1577     ts.memoizeOne = memoizeOne;
1578     function compose(a, b, c, d, e) {
1579         if (!!e) {
1580             var args_2 = [];
1581             for (var i = 0; i < arguments.length; i++) {
1582                 args_2[i] = arguments[i];
1583             }
1584             return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
1585         }
1586         else if (d) {
1587             return function (t) { return d(c(b(a(t)))); };
1588         }
1589         else if (c) {
1590             return function (t) { return c(b(a(t))); };
1591         }
1592         else if (b) {
1593             return function (t) { return b(a(t)); };
1594         }
1595         else if (a) {
1596             return function (t) { return a(t); };
1597         }
1598         else {
1599             return function (t) { return t; };
1600         }
1601     }
1602     ts.compose = compose;
1603     var AssertionLevel;
1604     (function (AssertionLevel) {
1605         AssertionLevel[AssertionLevel["None"] = 0] = "None";
1606         AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1607         AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1608         AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1609     })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1610     function equateValues(a, b) {
1611         return a === b;
1612     }
1613     ts.equateValues = equateValues;
1614     /**
1615      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1616      *
1617      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1618      * value of each code-point after applying `toUpperCase` to each string. We always map both
1619      * strings to their upper-case form as some unicode characters do not properly round-trip to
1620      * lowercase (such as `ẞ` (German sharp capital s)).
1621      */
1622     function equateStringsCaseInsensitive(a, b) {
1623         return a === b
1624             || a !== undefined
1625                 && b !== undefined
1626                 && a.toUpperCase() === b.toUpperCase();
1627     }
1628     ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1629     /**
1630      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1631      *
1632      * Case-sensitive comparisons compare both strings one code-point at a time using the
1633      * integer value of each code-point.
1634      */
1635     function equateStringsCaseSensitive(a, b) {
1636         return equateValues(a, b);
1637     }
1638     ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1639     function compareComparableValues(a, b) {
1640         return a === b ? 0 /* EqualTo */ :
1641             a === undefined ? -1 /* LessThan */ :
1642                 b === undefined ? 1 /* GreaterThan */ :
1643                     a < b ? -1 /* LessThan */ :
1644                         1 /* GreaterThan */;
1645     }
1646     /**
1647      * Compare two numeric values for their order relative to each other.
1648      * To compare strings, use any of the `compareStrings` functions.
1649      */
1650     function compareValues(a, b) {
1651         return compareComparableValues(a, b);
1652     }
1653     ts.compareValues = compareValues;
1654     /**
1655      * Compare two TextSpans, first by `start`, then by `length`.
1656      */
1657     function compareTextSpans(a, b) {
1658         return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length);
1659     }
1660     ts.compareTextSpans = compareTextSpans;
1661     function min(a, b, compare) {
1662         return compare(a, b) === -1 /* LessThan */ ? a : b;
1663     }
1664     ts.min = min;
1665     /**
1666      * Compare two strings using a case-insensitive ordinal comparison.
1667      *
1668      * Ordinal comparisons are based on the difference between the unicode code points of both
1669      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1670      * comparisons provide predictable ordering, but place "a" after "B".
1671      *
1672      * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1673      * value of each code-point after applying `toUpperCase` to each string. We always map both
1674      * strings to their upper-case form as some unicode characters do not properly round-trip to
1675      * lowercase (such as `ẞ` (German sharp capital s)).
1676      */
1677     function compareStringsCaseInsensitive(a, b) {
1678         if (a === b)
1679             return 0 /* EqualTo */;
1680         if (a === undefined)
1681             return -1 /* LessThan */;
1682         if (b === undefined)
1683             return 1 /* GreaterThan */;
1684         a = a.toUpperCase();
1685         b = b.toUpperCase();
1686         return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1687     }
1688     ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1689     /**
1690      * Compare two strings using a case-sensitive ordinal comparison.
1691      *
1692      * Ordinal comparisons are based on the difference between the unicode code points of both
1693      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1694      * comparisons provide predictable ordering, but place "a" after "B".
1695      *
1696      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1697      * value of each code-point.
1698      */
1699     function compareStringsCaseSensitive(a, b) {
1700         return compareComparableValues(a, b);
1701     }
1702     ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1703     function getStringComparer(ignoreCase) {
1704         return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1705     }
1706     ts.getStringComparer = getStringComparer;
1707     /**
1708      * Creates a string comparer for use with string collation in the UI.
1709      */
1710     var createUIStringComparer = (function () {
1711         var defaultComparer;
1712         var enUSComparer;
1713         var stringComparerFactory = getStringComparerFactory();
1714         return createStringComparer;
1715         function compareWithCallback(a, b, comparer) {
1716             if (a === b)
1717                 return 0 /* EqualTo */;
1718             if (a === undefined)
1719                 return -1 /* LessThan */;
1720             if (b === undefined)
1721                 return 1 /* GreaterThan */;
1722             var value = comparer(a, b);
1723             return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1724         }
1725         function createIntlCollatorStringComparer(locale) {
1726             // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1727             // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1728             var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1729             return function (a, b) { return compareWithCallback(a, b, comparer); };
1730         }
1731         function createLocaleCompareStringComparer(locale) {
1732             // if the locale is not the default locale (`undefined`), use the fallback comparer.
1733             if (locale !== undefined)
1734                 return createFallbackStringComparer();
1735             return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1736             function compareStrings(a, b) {
1737                 return a.localeCompare(b);
1738             }
1739         }
1740         function createFallbackStringComparer() {
1741             // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1742             // We first sort case insensitively.  So "Aaa" will come before "baa".
1743             // Then we sort case sensitively, so "aaa" will come before "Aaa".
1744             //
1745             // For case insensitive comparisons we always map both strings to their
1746             // upper-case form as some unicode characters do not properly round-trip to
1747             // lowercase (such as `ẞ` (German sharp capital s)).
1748             return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1749             function compareDictionaryOrder(a, b) {
1750                 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1751             }
1752             function compareStrings(a, b) {
1753                 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1754             }
1755         }
1756         function getStringComparerFactory() {
1757             // If the host supports Intl, we use it for comparisons using the default locale.
1758             if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1759                 return createIntlCollatorStringComparer;
1760             }
1761             // If the host does not support Intl, we fall back to localeCompare.
1762             // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1763             if (typeof String.prototype.localeCompare === "function" &&
1764                 typeof String.prototype.toLocaleUpperCase === "function" &&
1765                 "a".localeCompare("B") < 0) {
1766                 return createLocaleCompareStringComparer;
1767             }
1768             // Otherwise, fall back to ordinal comparison:
1769             return createFallbackStringComparer;
1770         }
1771         function createStringComparer(locale) {
1772             // Hold onto common string comparers. This avoids constantly reallocating comparers during
1773             // tests.
1774             if (locale === undefined) {
1775                 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1776             }
1777             else if (locale === "en-US") {
1778                 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1779             }
1780             else {
1781                 return stringComparerFactory(locale);
1782             }
1783         }
1784     })();
1785     var uiComparerCaseSensitive;
1786     var uiLocale;
1787     function getUILocale() {
1788         return uiLocale;
1789     }
1790     ts.getUILocale = getUILocale;
1791     function setUILocale(value) {
1792         if (uiLocale !== value) {
1793             uiLocale = value;
1794             uiComparerCaseSensitive = undefined;
1795         }
1796     }
1797     ts.setUILocale = setUILocale;
1798     /**
1799      * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1800      *
1801      * Ordering is not predictable between different host locales, but is best for displaying
1802      * ordered data for UI presentation. Characters with multiple unicode representations may
1803      * be considered equal.
1804      *
1805      * Case-sensitive comparisons compare strings that differ in base characters, or
1806      * accents/diacritic marks, or case as unequal.
1807      */
1808     function compareStringsCaseSensitiveUI(a, b) {
1809         var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1810         return comparer(a, b);
1811     }
1812     ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1813     function compareProperties(a, b, key, comparer) {
1814         return a === b ? 0 /* EqualTo */ :
1815             a === undefined ? -1 /* LessThan */ :
1816                 b === undefined ? 1 /* GreaterThan */ :
1817                     comparer(a[key], b[key]);
1818     }
1819     ts.compareProperties = compareProperties;
1820     /** True is greater than false. */
1821     function compareBooleans(a, b) {
1822         return compareValues(a ? 1 : 0, b ? 1 : 0);
1823     }
1824     ts.compareBooleans = compareBooleans;
1825     /**
1826      * 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.
1827      * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
1828      *
1829      * If there is a candidate that's the same except for case, return that.
1830      * If there is a candidate that's within one edit of the name, return that.
1831      * Otherwise, return the candidate with the smallest Levenshtein distance,
1832      *    except for candidates:
1833      *      * With no name
1834      *      * Whose length differs from the target name by more than 0.34 of the length of the name.
1835      *      * Whose levenshtein distance is more than 0.4 of the length of the name
1836      *        (0.4 allows 1 substitution/transposition for every 5 characters,
1837      *         and 1 insertion/deletion at 3 characters)
1838      */
1839     function getSpellingSuggestion(name, candidates, getName) {
1840         var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1841         var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
1842         var bestCandidate;
1843         var justCheckExactMatches = false;
1844         var nameLowerCase = name.toLowerCase();
1845         for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1846             var candidate = candidates_1[_i];
1847             var candidateName = getName(candidate);
1848             if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
1849                 var candidateNameLowerCase = candidateName.toLowerCase();
1850                 if (candidateNameLowerCase === nameLowerCase) {
1851                     if (candidateName === name) {
1852                         continue;
1853                     }
1854                     return candidate;
1855                 }
1856                 if (justCheckExactMatches) {
1857                     continue;
1858                 }
1859                 if (candidateName.length < 3) {
1860                     // Don't bother, user would have noticed a 2-character name having an extra character
1861                     continue;
1862                 }
1863                 // Only care about a result better than the best so far.
1864                 var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
1865                 if (distance === undefined) {
1866                     continue;
1867                 }
1868                 if (distance < 3) {
1869                     justCheckExactMatches = true;
1870                     bestCandidate = candidate;
1871                 }
1872                 else {
1873                     ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1874                     bestDistance = distance;
1875                     bestCandidate = candidate;
1876                 }
1877             }
1878         }
1879         return bestCandidate;
1880     }
1881     ts.getSpellingSuggestion = getSpellingSuggestion;
1882     function levenshteinWithMax(s1, s2, max) {
1883         var previous = new Array(s2.length + 1);
1884         var current = new Array(s2.length + 1);
1885         /** Represents any value > max. We don't care about the particular value. */
1886         var big = max + 1;
1887         for (var i = 0; i <= s2.length; i++) {
1888             previous[i] = i;
1889         }
1890         for (var i = 1; i <= s1.length; i++) {
1891             var c1 = s1.charCodeAt(i - 1);
1892             var minJ = i > max ? i - max : 1;
1893             var maxJ = s2.length > max + i ? max + i : s2.length;
1894             current[0] = i;
1895             /** Smallest value of the matrix in the ith column. */
1896             var colMin = i;
1897             for (var j = 1; j < minJ; j++) {
1898                 current[j] = big;
1899             }
1900             for (var j = minJ; j <= maxJ; j++) {
1901                 var dist = c1 === s2.charCodeAt(j - 1)
1902                     ? previous[j - 1]
1903                     : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
1904                 current[j] = dist;
1905                 colMin = Math.min(colMin, dist);
1906             }
1907             for (var j = maxJ + 1; j <= s2.length; j++) {
1908                 current[j] = big;
1909             }
1910             if (colMin > max) {
1911                 // Give up -- everything in this column is > max and it can't get better in future columns.
1912                 return undefined;
1913             }
1914             var temp = previous;
1915             previous = current;
1916             current = temp;
1917         }
1918         var res = previous[s2.length];
1919         return res > max ? undefined : res;
1920     }
1921     function endsWith(str, suffix) {
1922         var expectedPos = str.length - suffix.length;
1923         return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1924     }
1925     ts.endsWith = endsWith;
1926     function removeSuffix(str, suffix) {
1927         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1928     }
1929     ts.removeSuffix = removeSuffix;
1930     function tryRemoveSuffix(str, suffix) {
1931         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1932     }
1933     ts.tryRemoveSuffix = tryRemoveSuffix;
1934     function stringContains(str, substring) {
1935         return str.indexOf(substring) !== -1;
1936     }
1937     ts.stringContains = stringContains;
1938     /**
1939      * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1940      */
1941     function removeMinAndVersionNumbers(fileName) {
1942         // Match a "." or "-" followed by a version number or 'min' at the end of the name
1943         var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
1944         // The "min" or version may both be present, in either order, so try applying the above twice.
1945         return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
1946     }
1947     ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1948     /** Remove an item from an array, moving everything to its right one space left. */
1949     function orderedRemoveItem(array, item) {
1950         for (var i = 0; i < array.length; i++) {
1951             if (array[i] === item) {
1952                 orderedRemoveItemAt(array, i);
1953                 return true;
1954             }
1955         }
1956         return false;
1957     }
1958     ts.orderedRemoveItem = orderedRemoveItem;
1959     /** Remove an item by index from an array, moving everything to its right one space left. */
1960     function orderedRemoveItemAt(array, index) {
1961         // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
1962         for (var i = index; i < array.length - 1; i++) {
1963             array[i] = array[i + 1];
1964         }
1965         array.pop();
1966     }
1967     ts.orderedRemoveItemAt = orderedRemoveItemAt;
1968     function unorderedRemoveItemAt(array, index) {
1969         // Fill in the "hole" left at `index`.
1970         array[index] = array[array.length - 1];
1971         array.pop();
1972     }
1973     ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
1974     /** Remove the *first* occurrence of `item` from the array. */
1975     function unorderedRemoveItem(array, item) {
1976         return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
1977     }
1978     ts.unorderedRemoveItem = unorderedRemoveItem;
1979     /** Remove the *first* element satisfying `predicate`. */
1980     function unorderedRemoveFirstItemWhere(array, predicate) {
1981         for (var i = 0; i < array.length; i++) {
1982             if (predicate(array[i])) {
1983                 unorderedRemoveItemAt(array, i);
1984                 return true;
1985             }
1986         }
1987         return false;
1988     }
1989     function createGetCanonicalFileName(useCaseSensitiveFileNames) {
1990         return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
1991     }
1992     ts.createGetCanonicalFileName = createGetCanonicalFileName;
1993     function patternText(_a) {
1994         var prefix = _a.prefix, suffix = _a.suffix;
1995         return prefix + "*" + suffix;
1996     }
1997     ts.patternText = patternText;
1998     /**
1999      * Given that candidate matches pattern, returns the text matching the '*'.
2000      * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
2001      */
2002     function matchedText(pattern, candidate) {
2003         ts.Debug.assert(isPatternMatch(pattern, candidate));
2004         return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
2005     }
2006     ts.matchedText = matchedText;
2007     /** Return the object corresponding to the best pattern to match `candidate`. */
2008     function findBestPatternMatch(values, getPattern, candidate) {
2009         var matchedValue;
2010         // use length of prefix as betterness criteria
2011         var longestMatchPrefixLength = -1;
2012         for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
2013             var v = values_2[_i];
2014             var pattern = getPattern(v);
2015             if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
2016                 longestMatchPrefixLength = pattern.prefix.length;
2017                 matchedValue = v;
2018             }
2019         }
2020         return matchedValue;
2021     }
2022     ts.findBestPatternMatch = findBestPatternMatch;
2023     function startsWith(str, prefix) {
2024         return str.lastIndexOf(prefix, 0) === 0;
2025     }
2026     ts.startsWith = startsWith;
2027     function removePrefix(str, prefix) {
2028         return startsWith(str, prefix) ? str.substr(prefix.length) : str;
2029     }
2030     ts.removePrefix = removePrefix;
2031     function tryRemovePrefix(str, prefix, getCanonicalFileName) {
2032         if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
2033         return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
2034     }
2035     ts.tryRemovePrefix = tryRemovePrefix;
2036     function isPatternMatch(_a, candidate) {
2037         var prefix = _a.prefix, suffix = _a.suffix;
2038         return candidate.length >= prefix.length + suffix.length &&
2039             startsWith(candidate, prefix) &&
2040             endsWith(candidate, suffix);
2041     }
2042     function and(f, g) {
2043         return function (arg) { return f(arg) && g(arg); };
2044     }
2045     ts.and = and;
2046     function or() {
2047         var fs = [];
2048         for (var _i = 0; _i < arguments.length; _i++) {
2049             fs[_i] = arguments[_i];
2050         }
2051         return function () {
2052             var args = [];
2053             for (var _i = 0; _i < arguments.length; _i++) {
2054                 args[_i] = arguments[_i];
2055             }
2056             for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
2057                 var f = fs_1[_a];
2058                 if (f.apply(void 0, args)) {
2059                     return true;
2060                 }
2061             }
2062             return false;
2063         };
2064     }
2065     ts.or = or;
2066     function not(fn) {
2067         return function () {
2068             var args = [];
2069             for (var _i = 0; _i < arguments.length; _i++) {
2070                 args[_i] = arguments[_i];
2071             }
2072             return !fn.apply(void 0, args);
2073         };
2074     }
2075     ts.not = not;
2076     function assertType(_) { }
2077     ts.assertType = assertType;
2078     function singleElementArray(t) {
2079         return t === undefined ? undefined : [t];
2080     }
2081     ts.singleElementArray = singleElementArray;
2082     function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
2083         unchanged = unchanged || noop;
2084         var newIndex = 0;
2085         var oldIndex = 0;
2086         var newLen = newItems.length;
2087         var oldLen = oldItems.length;
2088         var hasChanges = false;
2089         while (newIndex < newLen && oldIndex < oldLen) {
2090             var newItem = newItems[newIndex];
2091             var oldItem = oldItems[oldIndex];
2092             var compareResult = comparer(newItem, oldItem);
2093             if (compareResult === -1 /* LessThan */) {
2094                 inserted(newItem);
2095                 newIndex++;
2096                 hasChanges = true;
2097             }
2098             else if (compareResult === 1 /* GreaterThan */) {
2099                 deleted(oldItem);
2100                 oldIndex++;
2101                 hasChanges = true;
2102             }
2103             else {
2104                 unchanged(oldItem, newItem);
2105                 newIndex++;
2106                 oldIndex++;
2107             }
2108         }
2109         while (newIndex < newLen) {
2110             inserted(newItems[newIndex++]);
2111             hasChanges = true;
2112         }
2113         while (oldIndex < oldLen) {
2114             deleted(oldItems[oldIndex++]);
2115             hasChanges = true;
2116         }
2117         return hasChanges;
2118     }
2119     ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
2120     function fill(length, cb) {
2121         var result = Array(length);
2122         for (var i = 0; i < length; i++) {
2123             result[i] = cb(i);
2124         }
2125         return result;
2126     }
2127     ts.fill = fill;
2128     function cartesianProduct(arrays) {
2129         var result = [];
2130         cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
2131         return result;
2132     }
2133     ts.cartesianProduct = cartesianProduct;
2134     function cartesianProductWorker(arrays, result, outer, index) {
2135         for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
2136             var element = _a[_i];
2137             var inner = void 0;
2138             if (outer) {
2139                 inner = outer.slice();
2140                 inner.push(element);
2141             }
2142             else {
2143                 inner = [element];
2144             }
2145             if (index === arrays.length - 1) {
2146                 result.push(inner);
2147             }
2148             else {
2149                 cartesianProductWorker(arrays, result, inner, index + 1);
2150             }
2151         }
2152     }
2153     /**
2154      * Returns string left-padded with spaces or zeros until it reaches the given length.
2155      *
2156      * @param s String to pad.
2157      * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
2158      * @param padString Character to use as padding (default " ").
2159      */
2160     function padLeft(s, length, padString) {
2161         if (padString === void 0) { padString = " "; }
2162         return length <= s.length ? s : padString.repeat(length - s.length) + s;
2163     }
2164     ts.padLeft = padLeft;
2165     /**
2166      * Returns string right-padded with spaces until it reaches the given length.
2167      *
2168      * @param s String to pad.
2169      * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
2170      * @param padString Character to use as padding (default " ").
2171      */
2172     function padRight(s, length, padString) {
2173         if (padString === void 0) { padString = " "; }
2174         return length <= s.length ? s : s + padString.repeat(length - s.length);
2175     }
2176     ts.padRight = padRight;
2177     function takeWhile(array, predicate) {
2178         var len = array.length;
2179         var index = 0;
2180         while (index < len && predicate(array[index])) {
2181             index++;
2182         }
2183         return array.slice(0, index);
2184     }
2185     ts.takeWhile = takeWhile;
2186 })(ts || (ts = {}));
2187 /* @internal */
2188 var ts;
2189 (function (ts) {
2190     var LogLevel;
2191     (function (LogLevel) {
2192         LogLevel[LogLevel["Off"] = 0] = "Off";
2193         LogLevel[LogLevel["Error"] = 1] = "Error";
2194         LogLevel[LogLevel["Warning"] = 2] = "Warning";
2195         LogLevel[LogLevel["Info"] = 3] = "Info";
2196         LogLevel[LogLevel["Verbose"] = 4] = "Verbose";
2197     })(LogLevel = ts.LogLevel || (ts.LogLevel = {}));
2198     var Debug;
2199     (function (Debug) {
2200         var typeScriptVersion;
2201         /* eslint-disable prefer-const */
2202         var currentAssertionLevel = 0 /* None */;
2203         Debug.currentLogLevel = LogLevel.Warning;
2204         Debug.isDebugging = false;
2205         function getTypeScriptVersion() {
2206             return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version));
2207         }
2208         Debug.getTypeScriptVersion = getTypeScriptVersion;
2209         function shouldLog(level) {
2210             return Debug.currentLogLevel <= level;
2211         }
2212         Debug.shouldLog = shouldLog;
2213         function logMessage(level, s) {
2214             if (Debug.loggingHost && shouldLog(level)) {
2215                 Debug.loggingHost.log(level, s);
2216             }
2217         }
2218         function log(s) {
2219             logMessage(LogLevel.Info, s);
2220         }
2221         Debug.log = log;
2222         (function (log_1) {
2223             function error(s) {
2224                 logMessage(LogLevel.Error, s);
2225             }
2226             log_1.error = error;
2227             function warn(s) {
2228                 logMessage(LogLevel.Warning, s);
2229             }
2230             log_1.warn = warn;
2231             function log(s) {
2232                 logMessage(LogLevel.Info, s);
2233             }
2234             log_1.log = log;
2235             function trace(s) {
2236                 logMessage(LogLevel.Verbose, s);
2237             }
2238             log_1.trace = trace;
2239         })(log = Debug.log || (Debug.log = {}));
2240         var assertionCache = {};
2241         function getAssertionLevel() {
2242             return currentAssertionLevel;
2243         }
2244         Debug.getAssertionLevel = getAssertionLevel;
2245         function setAssertionLevel(level) {
2246             var prevAssertionLevel = currentAssertionLevel;
2247             currentAssertionLevel = level;
2248             if (level > prevAssertionLevel) {
2249                 // restore assertion functions for the current assertion level (see `shouldAssertFunction`).
2250                 for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) {
2251                     var key = _a[_i];
2252                     var cachedFunc = assertionCache[key];
2253                     if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
2254                         Debug[key] = cachedFunc;
2255                         assertionCache[key] = undefined;
2256                     }
2257                 }
2258             }
2259         }
2260         Debug.setAssertionLevel = setAssertionLevel;
2261         function shouldAssert(level) {
2262             return currentAssertionLevel >= level;
2263         }
2264         Debug.shouldAssert = shouldAssert;
2265         /**
2266          * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
2267          * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
2268          * @param level The minimum assertion level required.
2269          * @param name The name of the current assertion function.
2270          */
2271         function shouldAssertFunction(level, name) {
2272             if (!shouldAssert(level)) {
2273                 assertionCache[name] = { level: level, assertion: Debug[name] };
2274                 Debug[name] = ts.noop;
2275                 return false;
2276             }
2277             return true;
2278         }
2279         function fail(message, stackCrawlMark) {
2280             debugger;
2281             var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
2282             if (Error.captureStackTrace) {
2283                 Error.captureStackTrace(e, stackCrawlMark || fail);
2284             }
2285             throw e;
2286         }
2287         Debug.fail = fail;
2288         function failBadSyntaxKind(node, message, stackCrawlMark) {
2289             return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind);
2290         }
2291         Debug.failBadSyntaxKind = failBadSyntaxKind;
2292         function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
2293             if (!expression) {
2294                 message = message ? "False expression: " + message : "False expression.";
2295                 if (verboseDebugInfo) {
2296                     message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
2297                 }
2298                 fail(message, stackCrawlMark || assert);
2299             }
2300         }
2301         Debug.assert = assert;
2302         function assertEqual(a, b, msg, msg2, stackCrawlMark) {
2303             if (a !== b) {
2304                 var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
2305                 fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual);
2306             }
2307         }
2308         Debug.assertEqual = assertEqual;
2309         function assertLessThan(a, b, msg, stackCrawlMark) {
2310             if (a >= b) {
2311                 fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan);
2312             }
2313         }
2314         Debug.assertLessThan = assertLessThan;
2315         function assertLessThanOrEqual(a, b, stackCrawlMark) {
2316             if (a > b) {
2317                 fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual);
2318             }
2319         }
2320         Debug.assertLessThanOrEqual = assertLessThanOrEqual;
2321         function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
2322             if (a < b) {
2323                 fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual);
2324             }
2325         }
2326         Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
2327         function assertIsDefined(value, message, stackCrawlMark) {
2328             // eslint-disable-next-line no-null/no-null
2329             if (value === undefined || value === null) {
2330                 fail(message, stackCrawlMark || assertIsDefined);
2331             }
2332         }
2333         Debug.assertIsDefined = assertIsDefined;
2334         function checkDefined(value, message, stackCrawlMark) {
2335             assertIsDefined(value, message, stackCrawlMark || checkDefined);
2336             return value;
2337         }
2338         Debug.checkDefined = checkDefined;
2339         /**
2340          * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
2341          * a value is defined at the statement level.
2342          */
2343         Debug.assertDefined = checkDefined;
2344         function assertEachIsDefined(value, message, stackCrawlMark) {
2345             for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2346                 var v = value_1[_i];
2347                 assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
2348             }
2349         }
2350         Debug.assertEachIsDefined = assertEachIsDefined;
2351         function checkEachDefined(value, message, stackCrawlMark) {
2352             assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
2353             return value;
2354         }
2355         Debug.checkEachDefined = checkEachDefined;
2356         /**
2357          * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
2358          * the elements of an array are defined at the statement level.
2359          */
2360         Debug.assertEachDefined = checkEachDefined;
2361         function assertNever(member, message, stackCrawlMark) {
2362             if (message === void 0) { message = "Illegal value:"; }
2363             var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
2364             return fail(message + " " + detail, stackCrawlMark || assertNever);
2365         }
2366         Debug.assertNever = assertNever;
2367         function assertEachNode(nodes, test, message, stackCrawlMark) {
2368             if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
2369                 assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode);
2370             }
2371         }
2372         Debug.assertEachNode = assertEachNode;
2373         function assertNode(node, test, message, stackCrawlMark) {
2374             if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
2375                 assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode);
2376             }
2377         }
2378         Debug.assertNode = assertNode;
2379         function assertNotNode(node, test, message, stackCrawlMark) {
2380             if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
2381                 assert(node === undefined || test === undefined || !test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " should not have passed test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNotNode);
2382             }
2383         }
2384         Debug.assertNotNode = assertNotNode;
2385         function assertOptionalNode(node, test, message, stackCrawlMark) {
2386             if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
2387                 assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode);
2388             }
2389         }
2390         Debug.assertOptionalNode = assertOptionalNode;
2391         function assertOptionalToken(node, kind, message, stackCrawlMark) {
2392             if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
2393                 assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was not a '" + formatSyntaxKind(kind) + "' token."; }, stackCrawlMark || assertOptionalToken);
2394             }
2395         }
2396         Debug.assertOptionalToken = assertOptionalToken;
2397         function assertMissingNode(node, message, stackCrawlMark) {
2398             if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
2399                 assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode);
2400             }
2401         }
2402         Debug.assertMissingNode = assertMissingNode;
2403         function getFunctionName(func) {
2404             if (typeof func !== "function") {
2405                 return "";
2406             }
2407             else if (func.hasOwnProperty("name")) {
2408                 return func.name;
2409             }
2410             else {
2411                 var text = Function.prototype.toString.call(func);
2412                 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
2413                 return match ? match[1] : "";
2414             }
2415         }
2416         Debug.getFunctionName = getFunctionName;
2417         function formatSymbol(symbol) {
2418             return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
2419         }
2420         Debug.formatSymbol = formatSymbol;
2421         /**
2422          * Formats an enum value as a string for debugging and debug assertions.
2423          */
2424         function formatEnum(value, enumObject, isFlags) {
2425             if (value === void 0) { value = 0; }
2426             var members = getEnumMembers(enumObject);
2427             if (value === 0) {
2428                 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
2429             }
2430             if (isFlags) {
2431                 var result = "";
2432                 var remainingFlags = value;
2433                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
2434                     var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
2435                     if (enumValue > value) {
2436                         break;
2437                     }
2438                     if (enumValue !== 0 && enumValue & value) {
2439                         result = "" + result + (result ? "|" : "") + enumName;
2440                         remainingFlags &= ~enumValue;
2441                     }
2442                 }
2443                 if (remainingFlags === 0) {
2444                     return result;
2445                 }
2446             }
2447             else {
2448                 for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
2449                     var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
2450                     if (enumValue === value) {
2451                         return enumName;
2452                     }
2453                 }
2454             }
2455             return value.toString();
2456         }
2457         Debug.formatEnum = formatEnum;
2458         function getEnumMembers(enumObject) {
2459             var result = [];
2460             for (var name in enumObject) {
2461                 var value = enumObject[name];
2462                 if (typeof value === "number") {
2463                     result.push([value, name]);
2464                 }
2465             }
2466             return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
2467         }
2468         function formatSyntaxKind(kind) {
2469             return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
2470         }
2471         Debug.formatSyntaxKind = formatSyntaxKind;
2472         function formatNodeFlags(flags) {
2473             return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
2474         }
2475         Debug.formatNodeFlags = formatNodeFlags;
2476         function formatModifierFlags(flags) {
2477             return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
2478         }
2479         Debug.formatModifierFlags = formatModifierFlags;
2480         function formatTransformFlags(flags) {
2481             return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
2482         }
2483         Debug.formatTransformFlags = formatTransformFlags;
2484         function formatEmitFlags(flags) {
2485             return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
2486         }
2487         Debug.formatEmitFlags = formatEmitFlags;
2488         function formatSymbolFlags(flags) {
2489             return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
2490         }
2491         Debug.formatSymbolFlags = formatSymbolFlags;
2492         function formatTypeFlags(flags) {
2493             return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
2494         }
2495         Debug.formatTypeFlags = formatTypeFlags;
2496         function formatObjectFlags(flags) {
2497             return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
2498         }
2499         Debug.formatObjectFlags = formatObjectFlags;
2500         function formatFlowFlags(flags) {
2501             return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true);
2502         }
2503         Debug.formatFlowFlags = formatFlowFlags;
2504         var isDebugInfoEnabled = false;
2505         var extendedDebugModule;
2506         function extendedDebug() {
2507             enableDebugInfo();
2508             if (!extendedDebugModule) {
2509                 throw new Error("Debugging helpers could not be loaded.");
2510             }
2511             return extendedDebugModule;
2512         }
2513         function printControlFlowGraph(flowNode) {
2514             return console.log(formatControlFlowGraph(flowNode));
2515         }
2516         Debug.printControlFlowGraph = printControlFlowGraph;
2517         function formatControlFlowGraph(flowNode) {
2518             return extendedDebug().formatControlFlowGraph(flowNode);
2519         }
2520         Debug.formatControlFlowGraph = formatControlFlowGraph;
2521         var flowNodeProto;
2522         function attachFlowNodeDebugInfoWorker(flowNode) {
2523             if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
2524                 Object.defineProperties(flowNode, {
2525                     // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2526                     __tsDebuggerDisplay: {
2527                         value: function () {
2528                             var flowHeader = this.flags & 2 /* Start */ ? "FlowStart" :
2529                                 this.flags & 4 /* BranchLabel */ ? "FlowBranchLabel" :
2530                                     this.flags & 8 /* LoopLabel */ ? "FlowLoopLabel" :
2531                                         this.flags & 16 /* Assignment */ ? "FlowAssignment" :
2532                                             this.flags & 32 /* TrueCondition */ ? "FlowTrueCondition" :
2533                                                 this.flags & 64 /* FalseCondition */ ? "FlowFalseCondition" :
2534                                                     this.flags & 128 /* SwitchClause */ ? "FlowSwitchClause" :
2535                                                         this.flags & 256 /* ArrayMutation */ ? "FlowArrayMutation" :
2536                                                             this.flags & 512 /* Call */ ? "FlowCall" :
2537                                                                 this.flags & 1024 /* ReduceLabel */ ? "FlowReduceLabel" :
2538                                                                     this.flags & 1 /* Unreachable */ ? "FlowUnreachable" :
2539                                                                         "UnknownFlow";
2540                             var remainingFlags = this.flags & ~(2048 /* Referenced */ - 1);
2541                             return "" + flowHeader + (remainingFlags ? " (" + formatFlowFlags(remainingFlags) + ")" : "");
2542                         }
2543                     },
2544                     __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
2545                     __debugToString: { value: function () { return formatControlFlowGraph(this); } }
2546                 });
2547             }
2548         }
2549         function attachFlowNodeDebugInfo(flowNode) {
2550             if (isDebugInfoEnabled) {
2551                 if (typeof Object.setPrototypeOf === "function") {
2552                     // if we're in es2015, attach the method to a shared prototype for `FlowNode`
2553                     // so the method doesn't show up in the watch window.
2554                     if (!flowNodeProto) {
2555                         flowNodeProto = Object.create(Object.prototype);
2556                         attachFlowNodeDebugInfoWorker(flowNodeProto);
2557                     }
2558                     Object.setPrototypeOf(flowNode, flowNodeProto);
2559                 }
2560                 else {
2561                     // not running in an es2015 environment, attach the method directly.
2562                     attachFlowNodeDebugInfoWorker(flowNode);
2563                 }
2564             }
2565         }
2566         Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
2567         var nodeArrayProto;
2568         function attachNodeArrayDebugInfoWorker(array) {
2569             if (!("__tsDebuggerDisplay" in array)) { // eslint-disable-line no-in-operator
2570                 Object.defineProperties(array, {
2571                     __tsDebuggerDisplay: {
2572                         value: function (defaultValue) {
2573                             // An `Array` with extra properties is rendered as `[A, B, prop1: 1, prop2: 2]`. Most of
2574                             // these aren't immediately useful so we trim off the `prop1: ..., prop2: ...` part from the
2575                             // formatted string.
2576                             defaultValue = String(defaultValue).replace(/(?:,[\s\w\d_]+:[^,]+)+\]$/, "]");
2577                             return "NodeArray " + defaultValue;
2578                         }
2579                     }
2580                 });
2581             }
2582         }
2583         function attachNodeArrayDebugInfo(array) {
2584             if (isDebugInfoEnabled) {
2585                 if (typeof Object.setPrototypeOf === "function") {
2586                     // if we're in es2015, attach the method to a shared prototype for `NodeArray`
2587                     // so the method doesn't show up in the watch window.
2588                     if (!nodeArrayProto) {
2589                         nodeArrayProto = Object.create(Array.prototype);
2590                         attachNodeArrayDebugInfoWorker(nodeArrayProto);
2591                     }
2592                     Object.setPrototypeOf(array, nodeArrayProto);
2593                 }
2594                 else {
2595                     // not running in an es2015 environment, attach the method directly.
2596                     attachNodeArrayDebugInfoWorker(array);
2597                 }
2598             }
2599         }
2600         Debug.attachNodeArrayDebugInfo = attachNodeArrayDebugInfo;
2601         /**
2602          * Injects debug information into frequently used types.
2603          */
2604         function enableDebugInfo() {
2605             if (isDebugInfoEnabled)
2606                 return;
2607             // avoid recomputing
2608             var weakTypeTextMap;
2609             var weakNodeTextMap;
2610             function getWeakTypeTextMap() {
2611                 if (weakTypeTextMap === undefined) {
2612                     if (typeof WeakMap === "function")
2613                         weakTypeTextMap = new WeakMap();
2614                 }
2615                 return weakTypeTextMap;
2616             }
2617             function getWeakNodeTextMap() {
2618                 if (weakNodeTextMap === undefined) {
2619                     if (typeof WeakMap === "function")
2620                         weakNodeTextMap = new WeakMap();
2621                 }
2622                 return weakNodeTextMap;
2623             }
2624             // Add additional properties in debug mode to assist with debugging.
2625             Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
2626                 // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2627                 __tsDebuggerDisplay: {
2628                     value: function () {
2629                         var symbolHeader = this.flags & 33554432 /* Transient */ ? "TransientSymbol" :
2630                             "Symbol";
2631                         var remainingSymbolFlags = this.flags & ~33554432 /* Transient */;
2632                         return symbolHeader + " '" + ts.symbolName(this) + "'" + (remainingSymbolFlags ? " (" + formatSymbolFlags(remainingSymbolFlags) + ")" : "");
2633                     }
2634                 },
2635                 __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
2636             });
2637             Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
2638                 // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2639                 __tsDebuggerDisplay: {
2640                     value: function () {
2641                         var typeHeader = this.flags & 98304 /* Nullable */ ? "NullableType" :
2642                             this.flags & 384 /* StringOrNumberLiteral */ ? "LiteralType " + JSON.stringify(this.value) :
2643                                 this.flags & 2048 /* BigIntLiteral */ ? "LiteralType " + (this.value.negative ? "-" : "") + this.value.base10Value + "n" :
2644                                     this.flags & 8192 /* UniqueESSymbol */ ? "UniqueESSymbolType" :
2645                                         this.flags & 32 /* Enum */ ? "EnumType" :
2646                                             this.flags & 67359327 /* Intrinsic */ ? "IntrinsicType " + this.intrinsicName :
2647                                                 this.flags & 1048576 /* Union */ ? "UnionType" :
2648                                                     this.flags & 2097152 /* Intersection */ ? "IntersectionType" :
2649                                                         this.flags & 4194304 /* Index */ ? "IndexType" :
2650                                                             this.flags & 8388608 /* IndexedAccess */ ? "IndexedAccessType" :
2651                                                                 this.flags & 16777216 /* Conditional */ ? "ConditionalType" :
2652                                                                     this.flags & 33554432 /* Substitution */ ? "SubstitutionType" :
2653                                                                         this.flags & 262144 /* TypeParameter */ ? "TypeParameter" :
2654                                                                             this.flags & 524288 /* Object */ ?
2655                                                                                 this.objectFlags & 3 /* ClassOrInterface */ ? "InterfaceType" :
2656                                                                                     this.objectFlags & 4 /* Reference */ ? "TypeReference" :
2657                                                                                         this.objectFlags & 8 /* Tuple */ ? "TupleType" :
2658                                                                                             this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" :
2659                                                                                                 this.objectFlags & 32 /* Mapped */ ? "MappedType" :
2660                                                                                                     this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" :
2661                                                                                                         this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" :
2662                                                                                                             "ObjectType" :
2663                                                                                 "Type";
2664                         var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0;
2665                         return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : "");
2666                     }
2667                 },
2668                 __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
2669                 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
2670                 __debugTypeToString: {
2671                     value: function () {
2672                         // avoid recomputing
2673                         var map = getWeakTypeTextMap();
2674                         var text = map === null || map === void 0 ? void 0 : map.get(this);
2675                         if (text === undefined) {
2676                             text = this.checker.typeToString(this);
2677                             map === null || map === void 0 ? void 0 : map.set(this, text);
2678                         }
2679                         return text;
2680                     }
2681                 },
2682             });
2683             var nodeConstructors = [
2684                 ts.objectAllocator.getNodeConstructor(),
2685                 ts.objectAllocator.getIdentifierConstructor(),
2686                 ts.objectAllocator.getTokenConstructor(),
2687                 ts.objectAllocator.getSourceFileConstructor()
2688             ];
2689             for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
2690                 var ctor = nodeConstructors_1[_i];
2691                 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
2692                     Object.defineProperties(ctor.prototype, {
2693                         // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2694                         __tsDebuggerDisplay: {
2695                             value: function () {
2696                                 var nodeHeader = ts.isGeneratedIdentifier(this) ? "GeneratedIdentifier" :
2697                                     ts.isIdentifier(this) ? "Identifier '" + ts.idText(this) + "'" :
2698                                         ts.isPrivateIdentifier(this) ? "PrivateIdentifier '" + ts.idText(this) + "'" :
2699                                             ts.isStringLiteral(this) ? "StringLiteral " + JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...") :
2700                                                 ts.isNumericLiteral(this) ? "NumericLiteral " + this.text :
2701                                                     ts.isBigIntLiteral(this) ? "BigIntLiteral " + this.text + "n" :
2702                                                         ts.isTypeParameterDeclaration(this) ? "TypeParameterDeclaration" :
2703                                                             ts.isParameter(this) ? "ParameterDeclaration" :
2704                                                                 ts.isConstructorDeclaration(this) ? "ConstructorDeclaration" :
2705                                                                     ts.isGetAccessorDeclaration(this) ? "GetAccessorDeclaration" :
2706                                                                         ts.isSetAccessorDeclaration(this) ? "SetAccessorDeclaration" :
2707                                                                             ts.isCallSignatureDeclaration(this) ? "CallSignatureDeclaration" :
2708                                                                                 ts.isConstructSignatureDeclaration(this) ? "ConstructSignatureDeclaration" :
2709                                                                                     ts.isIndexSignatureDeclaration(this) ? "IndexSignatureDeclaration" :
2710                                                                                         ts.isTypePredicateNode(this) ? "TypePredicateNode" :
2711                                                                                             ts.isTypeReferenceNode(this) ? "TypeReferenceNode" :
2712                                                                                                 ts.isFunctionTypeNode(this) ? "FunctionTypeNode" :
2713                                                                                                     ts.isConstructorTypeNode(this) ? "ConstructorTypeNode" :
2714                                                                                                         ts.isTypeQueryNode(this) ? "TypeQueryNode" :
2715                                                                                                             ts.isTypeLiteralNode(this) ? "TypeLiteralNode" :
2716                                                                                                                 ts.isArrayTypeNode(this) ? "ArrayTypeNode" :
2717                                                                                                                     ts.isTupleTypeNode(this) ? "TupleTypeNode" :
2718                                                                                                                         ts.isOptionalTypeNode(this) ? "OptionalTypeNode" :
2719                                                                                                                             ts.isRestTypeNode(this) ? "RestTypeNode" :
2720                                                                                                                                 ts.isUnionTypeNode(this) ? "UnionTypeNode" :
2721                                                                                                                                     ts.isIntersectionTypeNode(this) ? "IntersectionTypeNode" :
2722                                                                                                                                         ts.isConditionalTypeNode(this) ? "ConditionalTypeNode" :
2723                                                                                                                                             ts.isInferTypeNode(this) ? "InferTypeNode" :
2724                                                                                                                                                 ts.isParenthesizedTypeNode(this) ? "ParenthesizedTypeNode" :
2725                                                                                                                                                     ts.isThisTypeNode(this) ? "ThisTypeNode" :
2726                                                                                                                                                         ts.isTypeOperatorNode(this) ? "TypeOperatorNode" :
2727                                                                                                                                                             ts.isIndexedAccessTypeNode(this) ? "IndexedAccessTypeNode" :
2728                                                                                                                                                                 ts.isMappedTypeNode(this) ? "MappedTypeNode" :
2729                                                                                                                                                                     ts.isLiteralTypeNode(this) ? "LiteralTypeNode" :
2730                                                                                                                                                                         ts.isNamedTupleMember(this) ? "NamedTupleMember" :
2731                                                                                                                                                                             ts.isImportTypeNode(this) ? "ImportTypeNode" :
2732                                                                                                                                                                                 formatSyntaxKind(this.kind);
2733                                 return "" + nodeHeader + (this.flags ? " (" + formatNodeFlags(this.flags) + ")" : "");
2734                             }
2735                         },
2736                         __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
2737                         __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
2738                         __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getEffectiveModifierFlagsNoCache(this)); } },
2739                         __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
2740                         __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
2741                         __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
2742                         __debugGetText: {
2743                             value: function (includeTrivia) {
2744                                 if (ts.nodeIsSynthesized(this))
2745                                     return "";
2746                                 // avoid recomputing
2747                                 var map = getWeakNodeTextMap();
2748                                 var text = map === null || map === void 0 ? void 0 : map.get(this);
2749                                 if (text === undefined) {
2750                                     var parseNode = ts.getParseTreeNode(this);
2751                                     var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
2752                                     text = sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
2753                                     map === null || map === void 0 ? void 0 : map.set(this, text);
2754                                 }
2755                                 return text;
2756                             }
2757                         }
2758                     });
2759                 }
2760             }
2761             // attempt to load extended debugging information
2762             try {
2763                 if (ts.sys && ts.sys.require) {
2764                     var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
2765                     var result = ts.sys.require(basePath, "./compiler-debug");
2766                     if (!result.error) {
2767                         result.module.init(ts);
2768                         extendedDebugModule = result.module;
2769                     }
2770                 }
2771             }
2772             catch (_a) {
2773                 // do nothing
2774             }
2775             isDebugInfoEnabled = true;
2776         }
2777         Debug.enableDebugInfo = enableDebugInfo;
2778         function formatDeprecationMessage(name, error, errorAfter, since, message) {
2779             var deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: ";
2780             deprecationMessage += "'" + name + "' ";
2781             deprecationMessage += since ? "has been deprecated since v" + since : "is deprecated";
2782             deprecationMessage += error ? " and can no longer be used." : errorAfter ? " and will no longer be usable after v" + errorAfter + "." : ".";
2783             deprecationMessage += message ? " " + ts.formatStringFromArgs(message, [name], 0) : "";
2784             return deprecationMessage;
2785         }
2786         function createErrorDeprecation(name, errorAfter, since, message) {
2787             var deprecationMessage = formatDeprecationMessage(name, /*error*/ true, errorAfter, since, message);
2788             return function () {
2789                 throw new TypeError(deprecationMessage);
2790             };
2791         }
2792         function createWarningDeprecation(name, errorAfter, since, message) {
2793             var hasWrittenDeprecation = false;
2794             return function () {
2795                 if (!hasWrittenDeprecation) {
2796                     log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message));
2797                     hasWrittenDeprecation = true;
2798                 }
2799             };
2800         }
2801         function createDeprecation(name, options) {
2802             var _a, _b;
2803             if (options === void 0) { options = {}; }
2804             var version = typeof options.typeScriptVersion === "string" ? new ts.Version(options.typeScriptVersion) : (_a = options.typeScriptVersion) !== null && _a !== void 0 ? _a : getTypeScriptVersion();
2805             var errorAfter = typeof options.errorAfter === "string" ? new ts.Version(options.errorAfter) : options.errorAfter;
2806             var warnAfter = typeof options.warnAfter === "string" ? new ts.Version(options.warnAfter) : options.warnAfter;
2807             var since = typeof options.since === "string" ? new ts.Version(options.since) : (_b = options.since) !== null && _b !== void 0 ? _b : warnAfter;
2808             var error = options.error || errorAfter && version.compareTo(errorAfter) <= 0;
2809             var warn = !warnAfter || version.compareTo(warnAfter) >= 0;
2810             return error ? createErrorDeprecation(name, errorAfter, since, options.message) :
2811                 warn ? createWarningDeprecation(name, errorAfter, since, options.message) :
2812                     ts.noop;
2813         }
2814         function wrapFunction(deprecation, func) {
2815             return function () {
2816                 deprecation();
2817                 return func.apply(this, arguments);
2818             };
2819         }
2820         function deprecate(func, options) {
2821             var deprecation = createDeprecation(getFunctionName(func), options);
2822             return wrapFunction(deprecation, func);
2823         }
2824         Debug.deprecate = deprecate;
2825     })(Debug = ts.Debug || (ts.Debug = {}));
2826 })(ts || (ts = {}));
2827 /* @internal */
2828 var ts;
2829 (function (ts) {
2830     // https://semver.org/#spec-item-2
2831     // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2832     // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2833     // > version, and Z is the patch version. Each element MUST increase numerically.
2834     //
2835     // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2836     // value of `0`.
2837     var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2838     // https://semver.org/#spec-item-9
2839     // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2840     // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2841     // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2842     // > MUST NOT include leading zeroes.
2843     var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2844     // https://semver.org/#spec-item-10
2845     // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2846     // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2847     // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2848     var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2849     // https://semver.org/#spec-item-9
2850     // > Numeric identifiers MUST NOT include leading zeroes.
2851     var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2852     /**
2853      * Describes a precise semantic version number, https://semver.org
2854      */
2855     var Version = /** @class */ (function () {
2856         function Version(major, minor, patch, prerelease, build) {
2857             if (minor === void 0) { minor = 0; }
2858             if (patch === void 0) { patch = 0; }
2859             if (prerelease === void 0) { prerelease = ""; }
2860             if (build === void 0) { build = ""; }
2861             if (typeof major === "string") {
2862                 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2863                 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2864             }
2865             ts.Debug.assert(major >= 0, "Invalid argument: major");
2866             ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2867             ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2868             ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2869             ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2870             this.major = major;
2871             this.minor = minor;
2872             this.patch = patch;
2873             this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2874             this.build = build ? build.split(".") : ts.emptyArray;
2875         }
2876         Version.tryParse = function (text) {
2877             var result = tryParseComponents(text);
2878             if (!result)
2879                 return undefined;
2880             var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2881             return new Version(major, minor, patch, prerelease, build);
2882         };
2883         Version.prototype.compareTo = function (other) {
2884             // https://semver.org/#spec-item-11
2885             // > Precedence is determined by the first difference when comparing each of these
2886             // > identifiers from left to right as follows: Major, minor, and patch versions are
2887             // > always compared numerically.
2888             //
2889             // https://semver.org/#spec-item-11
2890             // > Precedence for two pre-release versions with the same major, minor, and patch version
2891             // > MUST be determined by comparing each dot separated identifier from left to right until
2892             // > a difference is found [...]
2893             //
2894             // https://semver.org/#spec-item-11
2895             // > Build metadata does not figure into precedence
2896             if (this === other)
2897                 return 0 /* EqualTo */;
2898             if (other === undefined)
2899                 return 1 /* GreaterThan */;
2900             return ts.compareValues(this.major, other.major)
2901                 || ts.compareValues(this.minor, other.minor)
2902                 || ts.compareValues(this.patch, other.patch)
2903                 || comparePrereleaseIdentifiers(this.prerelease, other.prerelease);
2904         };
2905         Version.prototype.increment = function (field) {
2906             switch (field) {
2907                 case "major": return new Version(this.major + 1, 0, 0);
2908                 case "minor": return new Version(this.major, this.minor + 1, 0);
2909                 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2910                 default: return ts.Debug.assertNever(field);
2911             }
2912         };
2913         Version.prototype.toString = function () {
2914             var result = this.major + "." + this.minor + "." + this.patch;
2915             if (ts.some(this.prerelease))
2916                 result += "-" + this.prerelease.join(".");
2917             if (ts.some(this.build))
2918                 result += "+" + this.build.join(".");
2919             return result;
2920         };
2921         Version.zero = new Version(0, 0, 0);
2922         return Version;
2923     }());
2924     ts.Version = Version;
2925     function tryParseComponents(text) {
2926         var match = versionRegExp.exec(text);
2927         if (!match)
2928             return undefined;
2929         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;
2930         if (prerelease && !prereleaseRegExp.test(prerelease))
2931             return undefined;
2932         if (build && !buildRegExp.test(build))
2933             return undefined;
2934         return {
2935             major: parseInt(major, 10),
2936             minor: parseInt(minor, 10),
2937             patch: parseInt(patch, 10),
2938             prerelease: prerelease,
2939             build: build
2940         };
2941     }
2942     function comparePrereleaseIdentifiers(left, right) {
2943         // https://semver.org/#spec-item-11
2944         // > When major, minor, and patch are equal, a pre-release version has lower precedence
2945         // > than a normal version.
2946         if (left === right)
2947             return 0 /* EqualTo */;
2948         if (left.length === 0)
2949             return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2950         if (right.length === 0)
2951             return -1 /* LessThan */;
2952         // https://semver.org/#spec-item-11
2953         // > Precedence for two pre-release versions with the same major, minor, and patch version
2954         // > MUST be determined by comparing each dot separated identifier from left to right until
2955         // > a difference is found [...]
2956         var length = Math.min(left.length, right.length);
2957         for (var i = 0; i < length; i++) {
2958             var leftIdentifier = left[i];
2959             var rightIdentifier = right[i];
2960             if (leftIdentifier === rightIdentifier)
2961                 continue;
2962             var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2963             var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2964             if (leftIsNumeric || rightIsNumeric) {
2965                 // https://semver.org/#spec-item-11
2966                 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2967                 if (leftIsNumeric !== rightIsNumeric)
2968                     return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2969                 // https://semver.org/#spec-item-11
2970                 // > identifiers consisting of only digits are compared numerically
2971                 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2972                 if (result)
2973                     return result;
2974             }
2975             else {
2976                 // https://semver.org/#spec-item-11
2977                 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2978                 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2979                 if (result)
2980                     return result;
2981             }
2982         }
2983         // https://semver.org/#spec-item-11
2984         // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2985         // > of the preceding identifiers are equal.
2986         return ts.compareValues(left.length, right.length);
2987     }
2988     /**
2989      * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2990      */
2991     var VersionRange = /** @class */ (function () {
2992         function VersionRange(spec) {
2993             this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2994         }
2995         VersionRange.tryParse = function (text) {
2996             var sets = parseRange(text);
2997             if (sets) {
2998                 var range = new VersionRange("");
2999                 range._alternatives = sets;
3000                 return range;
3001             }
3002             return undefined;
3003         };
3004         VersionRange.prototype.test = function (version) {
3005             if (typeof version === "string")
3006                 version = new Version(version);
3007             return testDisjunction(version, this._alternatives);
3008         };
3009         VersionRange.prototype.toString = function () {
3010             return formatDisjunction(this._alternatives);
3011         };
3012         return VersionRange;
3013     }());
3014     ts.VersionRange = VersionRange;
3015     // https://github.com/npm/node-semver#range-grammar
3016     //
3017     // range-set    ::= range ( logical-or range ) *
3018     // range        ::= hyphen | simple ( ' ' simple ) * | ''
3019     // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
3020     var logicalOrRegExp = /\s*\|\|\s*/g;
3021     var whitespaceRegExp = /\s+/g;
3022     // https://github.com/npm/node-semver#range-grammar
3023     //
3024     // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
3025     // xr           ::= 'x' | 'X' | '*' | nr
3026     // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
3027     // qualifier    ::= ( '-' pre )? ( '+' build )?
3028     // pre          ::= parts
3029     // build        ::= parts
3030     // parts        ::= part ( '.' part ) *
3031     // part         ::= nr | [-0-9A-Za-z]+
3032     var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
3033     // https://github.com/npm/node-semver#range-grammar
3034     //
3035     // hyphen       ::= partial ' - ' partial
3036     var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
3037     // https://github.com/npm/node-semver#range-grammar
3038     //
3039     // simple       ::= primitive | partial | tilde | caret
3040     // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
3041     // tilde        ::= '~' partial
3042     // caret        ::= '^' partial
3043     var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
3044     function parseRange(text) {
3045         var alternatives = [];
3046         for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
3047             var range = _a[_i];
3048             if (!range)
3049                 continue;
3050             var comparators = [];
3051             var match = hyphenRegExp.exec(range);
3052             if (match) {
3053                 if (!parseHyphen(match[1], match[2], comparators))
3054                     return undefined;
3055             }
3056             else {
3057                 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
3058                     var simple = _c[_b];
3059                     var match_1 = rangeRegExp.exec(simple);
3060                     if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
3061                         return undefined;
3062                 }
3063             }
3064             alternatives.push(comparators);
3065         }
3066         return alternatives;
3067     }
3068     function parsePartial(text) {
3069         var match = partialRegExp.exec(text);
3070         if (!match)
3071             return undefined;
3072         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];
3073         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);
3074         return { version: version, major: major, minor: minor, patch: patch };
3075     }
3076     function parseHyphen(left, right, comparators) {
3077         var leftResult = parsePartial(left);
3078         if (!leftResult)
3079             return false;
3080         var rightResult = parsePartial(right);
3081         if (!rightResult)
3082             return false;
3083         if (!isWildcard(leftResult.major)) {
3084             comparators.push(createComparator(">=", leftResult.version));
3085         }
3086         if (!isWildcard(rightResult.major)) {
3087             comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
3088                 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
3089                     createComparator("<=", rightResult.version));
3090         }
3091         return true;
3092     }
3093     function parseComparator(operator, text, comparators) {
3094         var result = parsePartial(text);
3095         if (!result)
3096             return false;
3097         var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
3098         if (!isWildcard(major)) {
3099             switch (operator) {
3100                 case "~":
3101                     comparators.push(createComparator(">=", version));
3102                     comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
3103                         "minor")));
3104                     break;
3105                 case "^":
3106                     comparators.push(createComparator(">=", version));
3107                     comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
3108                         version.minor > 0 || isWildcard(patch) ? "minor" :
3109                             "patch")));
3110                     break;
3111                 case "<":
3112                 case ">=":
3113                     comparators.push(createComparator(operator, version));
3114                     break;
3115                 case "<=":
3116                 case ">":
3117                     comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
3118                         isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
3119                             createComparator(operator, version));
3120                     break;
3121                 case "=":
3122                 case undefined:
3123                     if (isWildcard(minor) || isWildcard(patch)) {
3124                         comparators.push(createComparator(">=", version));
3125                         comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
3126                     }
3127                     else {
3128                         comparators.push(createComparator("=", version));
3129                     }
3130                     break;
3131                 default:
3132                     // unrecognized
3133                     return false;
3134             }
3135         }
3136         else if (operator === "<" || operator === ">") {
3137             comparators.push(createComparator("<", Version.zero));
3138         }
3139         return true;
3140     }
3141     function isWildcard(part) {
3142         return part === "*" || part === "x" || part === "X";
3143     }
3144     function createComparator(operator, operand) {
3145         return { operator: operator, operand: operand };
3146     }
3147     function testDisjunction(version, alternatives) {
3148         // an empty disjunction is treated as "*" (all versions)
3149         if (alternatives.length === 0)
3150             return true;
3151         for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
3152             var alternative = alternatives_1[_i];
3153             if (testAlternative(version, alternative))
3154                 return true;
3155         }
3156         return false;
3157     }
3158     function testAlternative(version, comparators) {
3159         for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
3160             var comparator = comparators_1[_i];
3161             if (!testComparator(version, comparator.operator, comparator.operand))
3162                 return false;
3163         }
3164         return true;
3165     }
3166     function testComparator(version, operator, operand) {
3167         var cmp = version.compareTo(operand);
3168         switch (operator) {
3169             case "<": return cmp < 0;
3170             case "<=": return cmp <= 0;
3171             case ">": return cmp > 0;
3172             case ">=": return cmp >= 0;
3173             case "=": return cmp === 0;
3174             default: return ts.Debug.assertNever(operator);
3175         }
3176     }
3177     function formatDisjunction(alternatives) {
3178         return ts.map(alternatives, formatAlternative).join(" || ") || "*";
3179     }
3180     function formatAlternative(comparators) {
3181         return ts.map(comparators, formatComparator).join(" ");
3182     }
3183     function formatComparator(comparator) {
3184         return "" + comparator.operator + comparator.operand;
3185     }
3186 })(ts || (ts = {}));
3187 /*@internal*/
3188 var ts;
3189 (function (ts) {
3190     // The following definitions provide the minimum compatible support for the Web Performance User Timings API
3191     // between browsers and NodeJS:
3192     // eslint-disable-next-line @typescript-eslint/naming-convention
3193     function hasRequiredAPI(performance, PerformanceObserver) {
3194         return typeof performance === "object" &&
3195             typeof performance.timeOrigin === "number" &&
3196             typeof performance.mark === "function" &&
3197             typeof performance.measure === "function" &&
3198             typeof performance.now === "function" &&
3199             typeof PerformanceObserver === "function";
3200     }
3201     function tryGetWebPerformanceHooks() {
3202         if (typeof performance === "object" &&
3203             typeof PerformanceObserver === "function" &&
3204             hasRequiredAPI(performance, PerformanceObserver)) {
3205             return {
3206                 performance: performance,
3207                 PerformanceObserver: PerformanceObserver
3208             };
3209         }
3210     }
3211     function tryGetNodePerformanceHooks() {
3212         if (typeof module === "object" && typeof require === "function") {
3213             try {
3214                 var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver;
3215                 if (hasRequiredAPI(performance_1, PerformanceObserver_1)) {
3216                     // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not
3217                     // match the Web Performance API specification. Node's implementation did not allow
3218                     // optional `start` and `end` arguments for `performance.measure`.
3219                     // See https://github.com/nodejs/node/pull/32651 for more information.
3220                     var version_1 = new ts.Version(process.versions.node);
3221                     var range = new ts.VersionRange("<12.16.3 || 13 <13.13");
3222                     if (range.test(version_1)) {
3223                         return {
3224                             performance: {
3225                                 get timeOrigin() { return performance_1.timeOrigin; },
3226                                 now: function () { return performance_1.now(); },
3227                                 mark: function (name) { return performance_1.mark(name); },
3228                                 measure: function (name, start, end) {
3229                                     if (start === void 0) { start = "nodeStart"; }
3230                                     if (end === undefined) {
3231                                         end = "__performance.measure-fix__";
3232                                         performance_1.mark(end);
3233                                     }
3234                                     performance_1.measure(name, start, end);
3235                                     if (end === "__performance.measure-fix__") {
3236                                         performance_1.clearMarks("__performance.measure-fix__");
3237                                     }
3238                                 }
3239                             },
3240                             PerformanceObserver: PerformanceObserver_1
3241                         };
3242                     }
3243                     return {
3244                         performance: performance_1,
3245                         PerformanceObserver: PerformanceObserver_1
3246                     };
3247                 }
3248             }
3249             catch (_b) {
3250                 // ignore errors
3251             }
3252         }
3253     }
3254     // Unlike with the native Map/Set 'tryGet' functions in corePublic.ts, we eagerly evaluate these
3255     // since we will need them for `timestamp`, below.
3256     var nativePerformanceHooks = tryGetWebPerformanceHooks() || tryGetNodePerformanceHooks();
3257     var nativePerformance = nativePerformanceHooks === null || nativePerformanceHooks === void 0 ? void 0 : nativePerformanceHooks.performance;
3258     function tryGetNativePerformanceHooks() {
3259         return nativePerformanceHooks;
3260     }
3261     ts.tryGetNativePerformanceHooks = tryGetNativePerformanceHooks;
3262     /** Gets a timestamp with (at least) ms resolution */
3263     ts.timestamp = nativePerformance ? function () { return nativePerformance.now(); } :
3264         Date.now ? Date.now :
3265             function () { return +(new Date()); };
3266 })(ts || (ts = {}));
3267 /*@internal*/
3268 /** Performance measurements for the compiler. */
3269 var ts;
3270 (function (ts) {
3271     var performance;
3272     (function (performance) {
3273         var perfHooks;
3274         var perfObserver;
3275         // when set, indicates the implementation of `Performance` to use for user timing.
3276         // when unset, indicates user timing is unavailable or disabled.
3277         var performanceImpl;
3278         function createTimerIf(condition, measureName, startMarkName, endMarkName) {
3279             return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
3280         }
3281         performance.createTimerIf = createTimerIf;
3282         function createTimer(measureName, startMarkName, endMarkName) {
3283             var enterCount = 0;
3284             return {
3285                 enter: enter,
3286                 exit: exit
3287             };
3288             function enter() {
3289                 if (++enterCount === 1) {
3290                     mark(startMarkName);
3291                 }
3292             }
3293             function exit() {
3294                 if (--enterCount === 0) {
3295                     mark(endMarkName);
3296                     measure(measureName, startMarkName, endMarkName);
3297                 }
3298                 else if (enterCount < 0) {
3299                     ts.Debug.fail("enter/exit count does not match.");
3300                 }
3301             }
3302         }
3303         performance.createTimer = createTimer;
3304         performance.nullTimer = { enter: ts.noop, exit: ts.noop };
3305         var counts = new ts.Map();
3306         var durations = new ts.Map();
3307         /**
3308          * Marks a performance event.
3309          *
3310          * @param markName The name of the mark.
3311          */
3312         function mark(markName) {
3313             performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName);
3314         }
3315         performance.mark = mark;
3316         /**
3317          * Adds a performance measurement with the specified name.
3318          *
3319          * @param measureName The name of the performance measurement.
3320          * @param startMarkName The name of the starting mark. If not supplied, the point at which the
3321          *      profiler was enabled is used.
3322          * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
3323          *      used.
3324          */
3325         function measure(measureName, startMarkName, endMarkName) {
3326             performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName);
3327         }
3328         performance.measure = measure;
3329         /**
3330          * Gets the number of times a marker was encountered.
3331          *
3332          * @param markName The name of the mark.
3333          */
3334         function getCount(markName) {
3335             return counts.get(markName) || 0;
3336         }
3337         performance.getCount = getCount;
3338         /**
3339          * Gets the total duration of all measurements with the supplied name.
3340          *
3341          * @param measureName The name of the measure whose durations should be accumulated.
3342          */
3343         function getDuration(measureName) {
3344             return durations.get(measureName) || 0;
3345         }
3346         performance.getDuration = getDuration;
3347         /**
3348          * Iterate over each measure, performing some action
3349          *
3350          * @param cb The action to perform for each measure
3351          */
3352         function forEachMeasure(cb) {
3353             durations.forEach(function (duration, measureName) { return cb(measureName, duration); });
3354         }
3355         performance.forEachMeasure = forEachMeasure;
3356         /**
3357          * Indicates whether the performance API is enabled.
3358          */
3359         function isEnabled() {
3360             return !!performanceImpl;
3361         }
3362         performance.isEnabled = isEnabled;
3363         /** Enables (and resets) performance measurements for the compiler. */
3364         function enable() {
3365             if (!performanceImpl) {
3366                 perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks());
3367                 if (!perfHooks)
3368                     return false;
3369                 perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList));
3370                 perfObserver.observe({ entryTypes: ["mark", "measure"] });
3371                 performanceImpl = perfHooks.performance;
3372             }
3373             return true;
3374         }
3375         performance.enable = enable;
3376         /** Disables performance measurements for the compiler. */
3377         function disable() {
3378             perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect();
3379             performanceImpl = undefined;
3380             counts.clear();
3381             durations.clear();
3382         }
3383         performance.disable = disable;
3384         function updateStatisticsFromList(list) {
3385             for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) {
3386                 var mark_1 = _a[_i];
3387                 counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1);
3388             }
3389             for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) {
3390                 var measure_1 = _c[_b];
3391                 durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration);
3392             }
3393         }
3394     })(performance = ts.performance || (ts.performance = {}));
3395 })(ts || (ts = {}));
3396 /* @internal */
3397 var ts;
3398 (function (ts) {
3399     var _a;
3400     var nullLogger = {
3401         logEvent: ts.noop,
3402         logErrEvent: ts.noop,
3403         logPerfEvent: ts.noop,
3404         logInfoEvent: ts.noop,
3405         logStartCommand: ts.noop,
3406         logStopCommand: ts.noop,
3407         logStartUpdateProgram: ts.noop,
3408         logStopUpdateProgram: ts.noop,
3409         logStartUpdateGraph: ts.noop,
3410         logStopUpdateGraph: ts.noop,
3411         logStartResolveModule: ts.noop,
3412         logStopResolveModule: ts.noop,
3413         logStartParseSourceFile: ts.noop,
3414         logStopParseSourceFile: ts.noop,
3415         logStartReadFile: ts.noop,
3416         logStopReadFile: ts.noop,
3417         logStartBindFile: ts.noop,
3418         logStopBindFile: ts.noop,
3419         logStartScheduledOperation: ts.noop,
3420         logStopScheduledOperation: ts.noop,
3421     };
3422     // Load optional module to enable Event Tracing for Windows
3423     // See https://github.com/microsoft/typescript-etw for more information
3424     var etwModule;
3425     try {
3426         var etwModulePath = (_a = process.env.TS_ETW_MODULE_PATH) !== null && _a !== void 0 ? _a : "./node_modules/@microsoft/typescript-etw";
3427         // require() will throw an exception if the module is not found
3428         // It may also return undefined if not installed properly
3429         etwModule = require(etwModulePath);
3430     }
3431     catch (e) {
3432         etwModule = undefined;
3433     }
3434     /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
3435     ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
3436 })(ts || (ts = {}));
3437 /*@internal*/
3438 /** Tracing events for the compiler. */
3439 var ts;
3440 (function (ts) {
3441     var tracing;
3442     (function (tracing) {
3443         var fs;
3444         var traceCount = 0;
3445         var traceFd;
3446         var legendPath;
3447         var legend = [];
3448         /** Starts tracing for the given project (unless the `fs` module is unavailable). */
3449         function startTracing(configFilePath, traceDir, isBuildMode) {
3450             ts.Debug.assert(!traceFd, "Tracing already started");
3451             if (fs === undefined) {
3452                 try {
3453                     fs = require("fs");
3454                 }
3455                 catch (_a) {
3456                     fs = false;
3457                 }
3458             }
3459             if (!fs) {
3460                 return;
3461             }
3462             if (legendPath === undefined) {
3463                 legendPath = ts.combinePaths(traceDir, "legend.json");
3464             }
3465             // Note that writing will fail later on if it exists and is not a directory
3466             if (!fs.existsSync(traceDir)) {
3467                 fs.mkdirSync(traceDir, { recursive: true });
3468             }
3469             var countPart = isBuildMode ? "." + ++traceCount : "";
3470             var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json");
3471             var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json");
3472             legend.push({
3473                 configFilePath: configFilePath,
3474                 tracePath: tracePath,
3475                 typesPath: typesPath,
3476             });
3477             traceFd = fs.openSync(tracePath, "w");
3478             // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import)
3479             var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 };
3480             fs.writeSync(traceFd, "[\n"
3481                 + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })]
3482                     .map(function (v) { return JSON.stringify(v); }).join(",\n"));
3483         }
3484         tracing.startTracing = startTracing;
3485         /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */
3486         function stopTracing(typeCatalog) {
3487             if (!traceFd) {
3488                 ts.Debug.assert(!fs, "Tracing is not in progress");
3489                 return;
3490             }
3491             ts.Debug.assert(fs);
3492             fs.writeSync(traceFd, "\n]\n");
3493             fs.closeSync(traceFd);
3494             traceFd = undefined;
3495             if (typeCatalog) {
3496                 dumpTypes(typeCatalog);
3497             }
3498             else {
3499                 // We pre-computed this path for convenience, but clear it
3500                 // now that the file won't be created.
3501                 legend[legend.length - 1].typesPath = undefined;
3502             }
3503         }
3504         tracing.stopTracing = stopTracing;
3505         function isTracing() {
3506             return !!traceFd;
3507         }
3508         tracing.isTracing = isTracing;
3509         var Phase;
3510         (function (Phase) {
3511             Phase["Parse"] = "parse";
3512             Phase["Program"] = "program";
3513             Phase["Bind"] = "bind";
3514             Phase["Check"] = "check";
3515             Phase["Emit"] = "emit";
3516         })(Phase = tracing.Phase || (tracing.Phase = {}));
3517         /** Note: `push`/`pop` should be used by default.
3518          * `begin`/`end` are for special cases where we need the data point even if the event never
3519          * terminates (typically for reducing a scenario too big to trace to one that can be completed).
3520          * In the future we might implement an exit handler to dump unfinished events which would
3521          * deprecate these operations.
3522          */
3523         function begin(phase, name, args) {
3524             if (!traceFd)
3525                 return;
3526             writeEvent("B", phase, name, args);
3527         }
3528         tracing.begin = begin;
3529         function end(phase, name, args) {
3530             if (!traceFd)
3531                 return;
3532             writeEvent("E", phase, name, args);
3533         }
3534         tracing.end = end;
3535         function instant(phase, name, args) {
3536             if (!traceFd)
3537                 return;
3538             writeEvent("I", phase, name, args, "\"s\":\"g\"");
3539         }
3540         tracing.instant = instant;
3541         // Used for "Complete" (ph:"X") events
3542         var completeEvents = [];
3543         function push(phase, name, args) {
3544             if (!traceFd)
3545                 return;
3546             completeEvents.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp() });
3547         }
3548         tracing.push = push;
3549         function pop() {
3550             if (!traceFd)
3551                 return;
3552             ts.Debug.assert(completeEvents.length > 0);
3553             var _a = completeEvents.pop(), phase = _a.phase, name = _a.name, args = _a.args, time = _a.time;
3554             var dur = 1000 * ts.timestamp() - time;
3555             writeEvent("X", phase, name, args, "\"dur\":" + dur, time);
3556         }
3557         tracing.pop = pop;
3558         function writeEvent(eventType, phase, name, args, extras, time) {
3559             if (time === void 0) { time = 1000 * ts.timestamp(); }
3560             ts.Debug.assert(traceFd);
3561             ts.Debug.assert(fs);
3562             ts.performance.mark("beginTracing");
3563             fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\"");
3564             if (extras)
3565                 fs.writeSync(traceFd, "," + extras);
3566             if (args)
3567                 fs.writeSync(traceFd, ",\"args\":" + JSON.stringify(args));
3568             fs.writeSync(traceFd, "}");
3569             ts.performance.mark("endTracing");
3570             ts.performance.measure("Tracing", "beginTracing", "endTracing");
3571         }
3572         function indexFromOne(lc) {
3573             return {
3574                 line: lc.line + 1,
3575                 character: lc.character + 1,
3576             };
3577         }
3578         function dumpTypes(types) {
3579             var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
3580             ts.Debug.assert(fs);
3581             ts.performance.mark("beginDumpTypes");
3582             var typesPath = legend[legend.length - 1].typesPath;
3583             var typesFd = fs.openSync(typesPath, "w");
3584             var recursionIdentityMap = new ts.Map();
3585             // Cleverness: no line break here so that the type ID will match the line number
3586             fs.writeSync(typesFd, "[");
3587             var numTypes = types.length;
3588             for (var i = 0; i < numTypes; i++) {
3589                 var type = types[i];
3590                 var objectFlags = type.objectFlags;
3591                 var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol;
3592                 var firstDeclaration = (_b = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _b === void 0 ? void 0 : _b[0];
3593                 var firstFile = firstDeclaration && ts.getSourceFileOfNode(firstDeclaration);
3594                 // It's slow to compute the display text, so skip it unless it's really valuable (or cheap)
3595                 var display = void 0;
3596                 if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) {
3597                     try {
3598                         display = (_c = type.checker) === null || _c === void 0 ? void 0 : _c.typeToString(type);
3599                     }
3600                     catch (_s) {
3601                         display = undefined;
3602                     }
3603                 }
3604                 var indexedAccessProperties = {};
3605                 if (type.flags & 8388608 /* IndexedAccess */) {
3606                     var indexedAccessType = type;
3607                     indexedAccessProperties = {
3608                         indexedAccessObjectType: (_d = indexedAccessType.objectType) === null || _d === void 0 ? void 0 : _d.id,
3609                         indexedAccessIndexType: (_e = indexedAccessType.indexType) === null || _e === void 0 ? void 0 : _e.id,
3610                     };
3611                 }
3612                 var referenceProperties = {};
3613                 if (objectFlags & 4 /* Reference */) {
3614                     var referenceType = type;
3615                     referenceProperties = {
3616                         instantiatedType: (_f = referenceType.target) === null || _f === void 0 ? void 0 : _f.id,
3617                         typeArguments: (_g = referenceType.resolvedTypeArguments) === null || _g === void 0 ? void 0 : _g.map(function (t) { return t.id; }),
3618                     };
3619                 }
3620                 var conditionalProperties = {};
3621                 if (type.flags & 16777216 /* Conditional */) {
3622                     var conditionalType = type;
3623                     conditionalProperties = {
3624                         conditionalCheckType: (_h = conditionalType.checkType) === null || _h === void 0 ? void 0 : _h.id,
3625                         conditionalExtendsType: (_j = conditionalType.extendsType) === null || _j === void 0 ? void 0 : _j.id,
3626                         conditionalTrueType: (_l = (_k = conditionalType.resolvedTrueType) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : -1,
3627                         conditionalFalseType: (_o = (_m = conditionalType.resolvedFalseType) === null || _m === void 0 ? void 0 : _m.id) !== null && _o !== void 0 ? _o : -1,
3628                     };
3629                 }
3630                 // We can't print out an arbitrary object, so just assign each one a unique number.
3631                 // Don't call it an "id" so people don't treat it as a type id.
3632                 var recursionToken = void 0;
3633                 var recursionIdentity = type.checker.getRecursionIdentity(type);
3634                 if (recursionIdentity) {
3635                     recursionToken = recursionIdentityMap.get(recursionIdentity);
3636                     if (!recursionToken) {
3637                         recursionToken = recursionIdentityMap.size;
3638                         recursionIdentityMap.set(recursionIdentity, recursionToken);
3639                     }
3640                 }
3641                 var descriptor = __assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, unionTypes: (type.flags & 1048576 /* Union */) ? (_p = type.types) === null || _p === void 0 ? void 0 : _p.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_q = type.aliasTypeArguments) === null || _q === void 0 ? void 0 : _q.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_r = type.type) === null || _r === void 0 ? void 0 : _r.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), { firstDeclaration: firstDeclaration && {
3642                         path: firstFile.path,
3643                         start: indexFromOne(ts.getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)),
3644                         end: indexFromOne(ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(firstDeclaration), firstDeclaration.end)),
3645                     }, flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display });
3646                 fs.writeSync(typesFd, JSON.stringify(descriptor));
3647                 if (i < numTypes - 1) {
3648                     fs.writeSync(typesFd, ",\n");
3649                 }
3650             }
3651             fs.writeSync(typesFd, "]\n");
3652             fs.closeSync(typesFd);
3653             ts.performance.mark("endDumpTypes");
3654             ts.performance.measure("Dump types", "beginDumpTypes", "endDumpTypes");
3655         }
3656         function dumpLegend() {
3657             if (!legendPath) {
3658                 return;
3659             }
3660             ts.Debug.assert(fs);
3661             fs.writeFileSync(legendPath, JSON.stringify(legend));
3662         }
3663         tracing.dumpLegend = dumpLegend;
3664     })(tracing = ts.tracing || (ts.tracing = {}));
3665 })(ts || (ts = {}));
3666 var ts;
3667 (function (ts) {
3668     // token > SyntaxKind.Identifier => token is a keyword
3669     // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
3670     var SyntaxKind;
3671     (function (SyntaxKind) {
3672         SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
3673         SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
3674         SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
3675         SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
3676         SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
3677         SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
3678         // We detect and preserve #! on the first line
3679         SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
3680         // We detect and provide better error recovery when we encounter a git merge marker.  This
3681         // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
3682         SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
3683         // Literals
3684         SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
3685         SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
3686         SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
3687         SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
3688         SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
3689         SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
3690         SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
3691         // Pseudo-literals
3692         SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
3693         SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
3694         SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
3695         // Punctuation
3696         SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
3697         SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
3698         SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
3699         SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
3700         SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
3701         SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
3702         SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
3703         SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
3704         SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
3705         SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
3706         SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
3707         SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
3708         SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
3709         SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
3710         SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
3711         SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
3712         SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
3713         SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
3714         SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
3715         SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
3716         SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
3717         SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
3718         SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
3719         SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
3720         SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
3721         SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
3722         SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
3723         SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
3724         SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
3725         SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
3726         SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
3727         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
3728         SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
3729         SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
3730         SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
3731         SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
3732         SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
3733         SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
3734         SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
3735         SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
3736         SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
3737         SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
3738         SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
3739         /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
3740         SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
3741         // Assignments
3742         SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
3743         SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
3744         SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
3745         SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
3746         SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
3747         SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
3748         SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
3749         SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
3750         SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
3751         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3752         SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
3753         SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
3754         SyntaxKind[SyntaxKind["BarBarEqualsToken"] = 74] = "BarBarEqualsToken";
3755         SyntaxKind[SyntaxKind["AmpersandAmpersandEqualsToken"] = 75] = "AmpersandAmpersandEqualsToken";
3756         SyntaxKind[SyntaxKind["QuestionQuestionEqualsToken"] = 76] = "QuestionQuestionEqualsToken";
3757         SyntaxKind[SyntaxKind["CaretEqualsToken"] = 77] = "CaretEqualsToken";
3758         // Identifiers and PrivateIdentifiers
3759         SyntaxKind[SyntaxKind["Identifier"] = 78] = "Identifier";
3760         SyntaxKind[SyntaxKind["PrivateIdentifier"] = 79] = "PrivateIdentifier";
3761         // Reserved words
3762         SyntaxKind[SyntaxKind["BreakKeyword"] = 80] = "BreakKeyword";
3763         SyntaxKind[SyntaxKind["CaseKeyword"] = 81] = "CaseKeyword";
3764         SyntaxKind[SyntaxKind["CatchKeyword"] = 82] = "CatchKeyword";
3765         SyntaxKind[SyntaxKind["ClassKeyword"] = 83] = "ClassKeyword";
3766         SyntaxKind[SyntaxKind["ConstKeyword"] = 84] = "ConstKeyword";
3767         SyntaxKind[SyntaxKind["ContinueKeyword"] = 85] = "ContinueKeyword";
3768         SyntaxKind[SyntaxKind["DebuggerKeyword"] = 86] = "DebuggerKeyword";
3769         SyntaxKind[SyntaxKind["DefaultKeyword"] = 87] = "DefaultKeyword";
3770         SyntaxKind[SyntaxKind["DeleteKeyword"] = 88] = "DeleteKeyword";
3771         SyntaxKind[SyntaxKind["DoKeyword"] = 89] = "DoKeyword";
3772         SyntaxKind[SyntaxKind["ElseKeyword"] = 90] = "ElseKeyword";
3773         SyntaxKind[SyntaxKind["EnumKeyword"] = 91] = "EnumKeyword";
3774         SyntaxKind[SyntaxKind["ExportKeyword"] = 92] = "ExportKeyword";
3775         SyntaxKind[SyntaxKind["ExtendsKeyword"] = 93] = "ExtendsKeyword";
3776         SyntaxKind[SyntaxKind["FalseKeyword"] = 94] = "FalseKeyword";
3777         SyntaxKind[SyntaxKind["FinallyKeyword"] = 95] = "FinallyKeyword";
3778         SyntaxKind[SyntaxKind["ForKeyword"] = 96] = "ForKeyword";
3779         SyntaxKind[SyntaxKind["FunctionKeyword"] = 97] = "FunctionKeyword";
3780         SyntaxKind[SyntaxKind["IfKeyword"] = 98] = "IfKeyword";
3781         SyntaxKind[SyntaxKind["ImportKeyword"] = 99] = "ImportKeyword";
3782         SyntaxKind[SyntaxKind["InKeyword"] = 100] = "InKeyword";
3783         SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 101] = "InstanceOfKeyword";
3784         SyntaxKind[SyntaxKind["NewKeyword"] = 102] = "NewKeyword";
3785         SyntaxKind[SyntaxKind["NullKeyword"] = 103] = "NullKeyword";
3786         SyntaxKind[SyntaxKind["ReturnKeyword"] = 104] = "ReturnKeyword";
3787         SyntaxKind[SyntaxKind["SuperKeyword"] = 105] = "SuperKeyword";
3788         SyntaxKind[SyntaxKind["SwitchKeyword"] = 106] = "SwitchKeyword";
3789         SyntaxKind[SyntaxKind["ThisKeyword"] = 107] = "ThisKeyword";
3790         SyntaxKind[SyntaxKind["ThrowKeyword"] = 108] = "ThrowKeyword";
3791         SyntaxKind[SyntaxKind["TrueKeyword"] = 109] = "TrueKeyword";
3792         SyntaxKind[SyntaxKind["TryKeyword"] = 110] = "TryKeyword";
3793         SyntaxKind[SyntaxKind["TypeOfKeyword"] = 111] = "TypeOfKeyword";
3794         SyntaxKind[SyntaxKind["VarKeyword"] = 112] = "VarKeyword";
3795         SyntaxKind[SyntaxKind["VoidKeyword"] = 113] = "VoidKeyword";
3796         SyntaxKind[SyntaxKind["WhileKeyword"] = 114] = "WhileKeyword";
3797         SyntaxKind[SyntaxKind["WithKeyword"] = 115] = "WithKeyword";
3798         // Strict mode reserved words
3799         SyntaxKind[SyntaxKind["ImplementsKeyword"] = 116] = "ImplementsKeyword";
3800         SyntaxKind[SyntaxKind["InterfaceKeyword"] = 117] = "InterfaceKeyword";
3801         SyntaxKind[SyntaxKind["LetKeyword"] = 118] = "LetKeyword";
3802         SyntaxKind[SyntaxKind["PackageKeyword"] = 119] = "PackageKeyword";
3803         SyntaxKind[SyntaxKind["PrivateKeyword"] = 120] = "PrivateKeyword";
3804         SyntaxKind[SyntaxKind["ProtectedKeyword"] = 121] = "ProtectedKeyword";
3805         SyntaxKind[SyntaxKind["PublicKeyword"] = 122] = "PublicKeyword";
3806         SyntaxKind[SyntaxKind["StaticKeyword"] = 123] = "StaticKeyword";
3807         SyntaxKind[SyntaxKind["YieldKeyword"] = 124] = "YieldKeyword";
3808         // Contextual keywords
3809         SyntaxKind[SyntaxKind["AbstractKeyword"] = 125] = "AbstractKeyword";
3810         SyntaxKind[SyntaxKind["AsKeyword"] = 126] = "AsKeyword";
3811         SyntaxKind[SyntaxKind["AssertsKeyword"] = 127] = "AssertsKeyword";
3812         SyntaxKind[SyntaxKind["AnyKeyword"] = 128] = "AnyKeyword";
3813         SyntaxKind[SyntaxKind["AsyncKeyword"] = 129] = "AsyncKeyword";
3814         SyntaxKind[SyntaxKind["AwaitKeyword"] = 130] = "AwaitKeyword";
3815         SyntaxKind[SyntaxKind["BooleanKeyword"] = 131] = "BooleanKeyword";
3816         SyntaxKind[SyntaxKind["ConstructorKeyword"] = 132] = "ConstructorKeyword";
3817         SyntaxKind[SyntaxKind["DeclareKeyword"] = 133] = "DeclareKeyword";
3818         SyntaxKind[SyntaxKind["GetKeyword"] = 134] = "GetKeyword";
3819         SyntaxKind[SyntaxKind["InferKeyword"] = 135] = "InferKeyword";
3820         SyntaxKind[SyntaxKind["IntrinsicKeyword"] = 136] = "IntrinsicKeyword";
3821         SyntaxKind[SyntaxKind["IsKeyword"] = 137] = "IsKeyword";
3822         SyntaxKind[SyntaxKind["KeyOfKeyword"] = 138] = "KeyOfKeyword";
3823         SyntaxKind[SyntaxKind["ModuleKeyword"] = 139] = "ModuleKeyword";
3824         SyntaxKind[SyntaxKind["NamespaceKeyword"] = 140] = "NamespaceKeyword";
3825         SyntaxKind[SyntaxKind["NeverKeyword"] = 141] = "NeverKeyword";
3826         SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 142] = "ReadonlyKeyword";
3827         SyntaxKind[SyntaxKind["RequireKeyword"] = 143] = "RequireKeyword";
3828         SyntaxKind[SyntaxKind["NumberKeyword"] = 144] = "NumberKeyword";
3829         SyntaxKind[SyntaxKind["ObjectKeyword"] = 145] = "ObjectKeyword";
3830         SyntaxKind[SyntaxKind["SetKeyword"] = 146] = "SetKeyword";
3831         SyntaxKind[SyntaxKind["StringKeyword"] = 147] = "StringKeyword";
3832         SyntaxKind[SyntaxKind["SymbolKeyword"] = 148] = "SymbolKeyword";
3833         SyntaxKind[SyntaxKind["TypeKeyword"] = 149] = "TypeKeyword";
3834         SyntaxKind[SyntaxKind["UndefinedKeyword"] = 150] = "UndefinedKeyword";
3835         SyntaxKind[SyntaxKind["UniqueKeyword"] = 151] = "UniqueKeyword";
3836         SyntaxKind[SyntaxKind["UnknownKeyword"] = 152] = "UnknownKeyword";
3837         SyntaxKind[SyntaxKind["FromKeyword"] = 153] = "FromKeyword";
3838         SyntaxKind[SyntaxKind["GlobalKeyword"] = 154] = "GlobalKeyword";
3839         SyntaxKind[SyntaxKind["BigIntKeyword"] = 155] = "BigIntKeyword";
3840         SyntaxKind[SyntaxKind["OfKeyword"] = 156] = "OfKeyword";
3841         // Parse tree nodes
3842         // Names
3843         SyntaxKind[SyntaxKind["QualifiedName"] = 157] = "QualifiedName";
3844         SyntaxKind[SyntaxKind["ComputedPropertyName"] = 158] = "ComputedPropertyName";
3845         // Signature elements
3846         SyntaxKind[SyntaxKind["TypeParameter"] = 159] = "TypeParameter";
3847         SyntaxKind[SyntaxKind["Parameter"] = 160] = "Parameter";
3848         SyntaxKind[SyntaxKind["Decorator"] = 161] = "Decorator";
3849         // TypeMember
3850         SyntaxKind[SyntaxKind["PropertySignature"] = 162] = "PropertySignature";
3851         SyntaxKind[SyntaxKind["PropertyDeclaration"] = 163] = "PropertyDeclaration";
3852         SyntaxKind[SyntaxKind["MethodSignature"] = 164] = "MethodSignature";
3853         SyntaxKind[SyntaxKind["MethodDeclaration"] = 165] = "MethodDeclaration";
3854         SyntaxKind[SyntaxKind["Constructor"] = 166] = "Constructor";
3855         SyntaxKind[SyntaxKind["GetAccessor"] = 167] = "GetAccessor";
3856         SyntaxKind[SyntaxKind["SetAccessor"] = 168] = "SetAccessor";
3857         SyntaxKind[SyntaxKind["CallSignature"] = 169] = "CallSignature";
3858         SyntaxKind[SyntaxKind["ConstructSignature"] = 170] = "ConstructSignature";
3859         SyntaxKind[SyntaxKind["IndexSignature"] = 171] = "IndexSignature";
3860         // Type
3861         SyntaxKind[SyntaxKind["TypePredicate"] = 172] = "TypePredicate";
3862         SyntaxKind[SyntaxKind["TypeReference"] = 173] = "TypeReference";
3863         SyntaxKind[SyntaxKind["FunctionType"] = 174] = "FunctionType";
3864         SyntaxKind[SyntaxKind["ConstructorType"] = 175] = "ConstructorType";
3865         SyntaxKind[SyntaxKind["TypeQuery"] = 176] = "TypeQuery";
3866         SyntaxKind[SyntaxKind["TypeLiteral"] = 177] = "TypeLiteral";
3867         SyntaxKind[SyntaxKind["ArrayType"] = 178] = "ArrayType";
3868         SyntaxKind[SyntaxKind["TupleType"] = 179] = "TupleType";
3869         SyntaxKind[SyntaxKind["OptionalType"] = 180] = "OptionalType";
3870         SyntaxKind[SyntaxKind["RestType"] = 181] = "RestType";
3871         SyntaxKind[SyntaxKind["UnionType"] = 182] = "UnionType";
3872         SyntaxKind[SyntaxKind["IntersectionType"] = 183] = "IntersectionType";
3873         SyntaxKind[SyntaxKind["ConditionalType"] = 184] = "ConditionalType";
3874         SyntaxKind[SyntaxKind["InferType"] = 185] = "InferType";
3875         SyntaxKind[SyntaxKind["ParenthesizedType"] = 186] = "ParenthesizedType";
3876         SyntaxKind[SyntaxKind["ThisType"] = 187] = "ThisType";
3877         SyntaxKind[SyntaxKind["TypeOperator"] = 188] = "TypeOperator";
3878         SyntaxKind[SyntaxKind["IndexedAccessType"] = 189] = "IndexedAccessType";
3879         SyntaxKind[SyntaxKind["MappedType"] = 190] = "MappedType";
3880         SyntaxKind[SyntaxKind["LiteralType"] = 191] = "LiteralType";
3881         SyntaxKind[SyntaxKind["NamedTupleMember"] = 192] = "NamedTupleMember";
3882         SyntaxKind[SyntaxKind["TemplateLiteralType"] = 193] = "TemplateLiteralType";
3883         SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 194] = "TemplateLiteralTypeSpan";
3884         SyntaxKind[SyntaxKind["ImportType"] = 195] = "ImportType";
3885         // Binding patterns
3886         SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 196] = "ObjectBindingPattern";
3887         SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 197] = "ArrayBindingPattern";
3888         SyntaxKind[SyntaxKind["BindingElement"] = 198] = "BindingElement";
3889         // Expression
3890         SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 199] = "ArrayLiteralExpression";
3891         SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 200] = "ObjectLiteralExpression";
3892         SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 201] = "PropertyAccessExpression";
3893         SyntaxKind[SyntaxKind["ElementAccessExpression"] = 202] = "ElementAccessExpression";
3894         SyntaxKind[SyntaxKind["CallExpression"] = 203] = "CallExpression";
3895         SyntaxKind[SyntaxKind["NewExpression"] = 204] = "NewExpression";
3896         SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 205] = "TaggedTemplateExpression";
3897         SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 206] = "TypeAssertionExpression";
3898         SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 207] = "ParenthesizedExpression";
3899         SyntaxKind[SyntaxKind["FunctionExpression"] = 208] = "FunctionExpression";
3900         SyntaxKind[SyntaxKind["ArrowFunction"] = 209] = "ArrowFunction";
3901         SyntaxKind[SyntaxKind["DeleteExpression"] = 210] = "DeleteExpression";
3902         SyntaxKind[SyntaxKind["TypeOfExpression"] = 211] = "TypeOfExpression";
3903         SyntaxKind[SyntaxKind["VoidExpression"] = 212] = "VoidExpression";
3904         SyntaxKind[SyntaxKind["AwaitExpression"] = 213] = "AwaitExpression";
3905         SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 214] = "PrefixUnaryExpression";
3906         SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 215] = "PostfixUnaryExpression";
3907         SyntaxKind[SyntaxKind["BinaryExpression"] = 216] = "BinaryExpression";
3908         SyntaxKind[SyntaxKind["ConditionalExpression"] = 217] = "ConditionalExpression";
3909         SyntaxKind[SyntaxKind["TemplateExpression"] = 218] = "TemplateExpression";
3910         SyntaxKind[SyntaxKind["YieldExpression"] = 219] = "YieldExpression";
3911         SyntaxKind[SyntaxKind["SpreadElement"] = 220] = "SpreadElement";
3912         SyntaxKind[SyntaxKind["ClassExpression"] = 221] = "ClassExpression";
3913         SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression";
3914         SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 223] = "ExpressionWithTypeArguments";
3915         SyntaxKind[SyntaxKind["AsExpression"] = 224] = "AsExpression";
3916         SyntaxKind[SyntaxKind["NonNullExpression"] = 225] = "NonNullExpression";
3917         SyntaxKind[SyntaxKind["MetaProperty"] = 226] = "MetaProperty";
3918         SyntaxKind[SyntaxKind["SyntheticExpression"] = 227] = "SyntheticExpression";
3919         // Misc
3920         SyntaxKind[SyntaxKind["TemplateSpan"] = 228] = "TemplateSpan";
3921         SyntaxKind[SyntaxKind["SemicolonClassElement"] = 229] = "SemicolonClassElement";
3922         // Element
3923         SyntaxKind[SyntaxKind["Block"] = 230] = "Block";
3924         SyntaxKind[SyntaxKind["EmptyStatement"] = 231] = "EmptyStatement";
3925         SyntaxKind[SyntaxKind["VariableStatement"] = 232] = "VariableStatement";
3926         SyntaxKind[SyntaxKind["ExpressionStatement"] = 233] = "ExpressionStatement";
3927         SyntaxKind[SyntaxKind["IfStatement"] = 234] = "IfStatement";
3928         SyntaxKind[SyntaxKind["DoStatement"] = 235] = "DoStatement";
3929         SyntaxKind[SyntaxKind["WhileStatement"] = 236] = "WhileStatement";
3930         SyntaxKind[SyntaxKind["ForStatement"] = 237] = "ForStatement";
3931         SyntaxKind[SyntaxKind["ForInStatement"] = 238] = "ForInStatement";
3932         SyntaxKind[SyntaxKind["ForOfStatement"] = 239] = "ForOfStatement";
3933         SyntaxKind[SyntaxKind["ContinueStatement"] = 240] = "ContinueStatement";
3934         SyntaxKind[SyntaxKind["BreakStatement"] = 241] = "BreakStatement";
3935         SyntaxKind[SyntaxKind["ReturnStatement"] = 242] = "ReturnStatement";
3936         SyntaxKind[SyntaxKind["WithStatement"] = 243] = "WithStatement";
3937         SyntaxKind[SyntaxKind["SwitchStatement"] = 244] = "SwitchStatement";
3938         SyntaxKind[SyntaxKind["LabeledStatement"] = 245] = "LabeledStatement";
3939         SyntaxKind[SyntaxKind["ThrowStatement"] = 246] = "ThrowStatement";
3940         SyntaxKind[SyntaxKind["TryStatement"] = 247] = "TryStatement";
3941         SyntaxKind[SyntaxKind["DebuggerStatement"] = 248] = "DebuggerStatement";
3942         SyntaxKind[SyntaxKind["VariableDeclaration"] = 249] = "VariableDeclaration";
3943         SyntaxKind[SyntaxKind["VariableDeclarationList"] = 250] = "VariableDeclarationList";
3944         SyntaxKind[SyntaxKind["FunctionDeclaration"] = 251] = "FunctionDeclaration";
3945         SyntaxKind[SyntaxKind["ClassDeclaration"] = 252] = "ClassDeclaration";
3946         SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 253] = "InterfaceDeclaration";
3947         SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 254] = "TypeAliasDeclaration";
3948         SyntaxKind[SyntaxKind["EnumDeclaration"] = 255] = "EnumDeclaration";
3949         SyntaxKind[SyntaxKind["ModuleDeclaration"] = 256] = "ModuleDeclaration";
3950         SyntaxKind[SyntaxKind["ModuleBlock"] = 257] = "ModuleBlock";
3951         SyntaxKind[SyntaxKind["CaseBlock"] = 258] = "CaseBlock";
3952         SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 259] = "NamespaceExportDeclaration";
3953         SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 260] = "ImportEqualsDeclaration";
3954         SyntaxKind[SyntaxKind["ImportDeclaration"] = 261] = "ImportDeclaration";
3955         SyntaxKind[SyntaxKind["ImportClause"] = 262] = "ImportClause";
3956         SyntaxKind[SyntaxKind["NamespaceImport"] = 263] = "NamespaceImport";
3957         SyntaxKind[SyntaxKind["NamedImports"] = 264] = "NamedImports";
3958         SyntaxKind[SyntaxKind["ImportSpecifier"] = 265] = "ImportSpecifier";
3959         SyntaxKind[SyntaxKind["ExportAssignment"] = 266] = "ExportAssignment";
3960         SyntaxKind[SyntaxKind["ExportDeclaration"] = 267] = "ExportDeclaration";
3961         SyntaxKind[SyntaxKind["NamedExports"] = 268] = "NamedExports";
3962         SyntaxKind[SyntaxKind["NamespaceExport"] = 269] = "NamespaceExport";
3963         SyntaxKind[SyntaxKind["ExportSpecifier"] = 270] = "ExportSpecifier";
3964         SyntaxKind[SyntaxKind["MissingDeclaration"] = 271] = "MissingDeclaration";
3965         // Module references
3966         SyntaxKind[SyntaxKind["ExternalModuleReference"] = 272] = "ExternalModuleReference";
3967         // JSX
3968         SyntaxKind[SyntaxKind["JsxElement"] = 273] = "JsxElement";
3969         SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 274] = "JsxSelfClosingElement";
3970         SyntaxKind[SyntaxKind["JsxOpeningElement"] = 275] = "JsxOpeningElement";
3971         SyntaxKind[SyntaxKind["JsxClosingElement"] = 276] = "JsxClosingElement";
3972         SyntaxKind[SyntaxKind["JsxFragment"] = 277] = "JsxFragment";
3973         SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 278] = "JsxOpeningFragment";
3974         SyntaxKind[SyntaxKind["JsxClosingFragment"] = 279] = "JsxClosingFragment";
3975         SyntaxKind[SyntaxKind["JsxAttribute"] = 280] = "JsxAttribute";
3976         SyntaxKind[SyntaxKind["JsxAttributes"] = 281] = "JsxAttributes";
3977         SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 282] = "JsxSpreadAttribute";
3978         SyntaxKind[SyntaxKind["JsxExpression"] = 283] = "JsxExpression";
3979         // Clauses
3980         SyntaxKind[SyntaxKind["CaseClause"] = 284] = "CaseClause";
3981         SyntaxKind[SyntaxKind["DefaultClause"] = 285] = "DefaultClause";
3982         SyntaxKind[SyntaxKind["HeritageClause"] = 286] = "HeritageClause";
3983         SyntaxKind[SyntaxKind["CatchClause"] = 287] = "CatchClause";
3984         // Property assignments
3985         SyntaxKind[SyntaxKind["PropertyAssignment"] = 288] = "PropertyAssignment";
3986         SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 289] = "ShorthandPropertyAssignment";
3987         SyntaxKind[SyntaxKind["SpreadAssignment"] = 290] = "SpreadAssignment";
3988         // Enum
3989         SyntaxKind[SyntaxKind["EnumMember"] = 291] = "EnumMember";
3990         // Unparsed
3991         SyntaxKind[SyntaxKind["UnparsedPrologue"] = 292] = "UnparsedPrologue";
3992         SyntaxKind[SyntaxKind["UnparsedPrepend"] = 293] = "UnparsedPrepend";
3993         SyntaxKind[SyntaxKind["UnparsedText"] = 294] = "UnparsedText";
3994         SyntaxKind[SyntaxKind["UnparsedInternalText"] = 295] = "UnparsedInternalText";
3995         SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 296] = "UnparsedSyntheticReference";
3996         // Top-level nodes
3997         SyntaxKind[SyntaxKind["SourceFile"] = 297] = "SourceFile";
3998         SyntaxKind[SyntaxKind["Bundle"] = 298] = "Bundle";
3999         SyntaxKind[SyntaxKind["UnparsedSource"] = 299] = "UnparsedSource";
4000         SyntaxKind[SyntaxKind["InputFiles"] = 300] = "InputFiles";
4001         // JSDoc nodes
4002         SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 301] = "JSDocTypeExpression";
4003         SyntaxKind[SyntaxKind["JSDocNameReference"] = 302] = "JSDocNameReference";
4004         // The * type
4005         SyntaxKind[SyntaxKind["JSDocAllType"] = 303] = "JSDocAllType";
4006         // The ? type
4007         SyntaxKind[SyntaxKind["JSDocUnknownType"] = 304] = "JSDocUnknownType";
4008         SyntaxKind[SyntaxKind["JSDocNullableType"] = 305] = "JSDocNullableType";
4009         SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 306] = "JSDocNonNullableType";
4010         SyntaxKind[SyntaxKind["JSDocOptionalType"] = 307] = "JSDocOptionalType";
4011         SyntaxKind[SyntaxKind["JSDocFunctionType"] = 308] = "JSDocFunctionType";
4012         SyntaxKind[SyntaxKind["JSDocVariadicType"] = 309] = "JSDocVariadicType";
4013         // https://jsdoc.app/about-namepaths.html
4014         SyntaxKind[SyntaxKind["JSDocNamepathType"] = 310] = "JSDocNamepathType";
4015         SyntaxKind[SyntaxKind["JSDocComment"] = 311] = "JSDocComment";
4016         SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 312] = "JSDocTypeLiteral";
4017         SyntaxKind[SyntaxKind["JSDocSignature"] = 313] = "JSDocSignature";
4018         SyntaxKind[SyntaxKind["JSDocTag"] = 314] = "JSDocTag";
4019         SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 315] = "JSDocAugmentsTag";
4020         SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 316] = "JSDocImplementsTag";
4021         SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 317] = "JSDocAuthorTag";
4022         SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 318] = "JSDocDeprecatedTag";
4023         SyntaxKind[SyntaxKind["JSDocClassTag"] = 319] = "JSDocClassTag";
4024         SyntaxKind[SyntaxKind["JSDocPublicTag"] = 320] = "JSDocPublicTag";
4025         SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 321] = "JSDocPrivateTag";
4026         SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 322] = "JSDocProtectedTag";
4027         SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 323] = "JSDocReadonlyTag";
4028         SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 324] = "JSDocCallbackTag";
4029         SyntaxKind[SyntaxKind["JSDocEnumTag"] = 325] = "JSDocEnumTag";
4030         SyntaxKind[SyntaxKind["JSDocParameterTag"] = 326] = "JSDocParameterTag";
4031         SyntaxKind[SyntaxKind["JSDocReturnTag"] = 327] = "JSDocReturnTag";
4032         SyntaxKind[SyntaxKind["JSDocThisTag"] = 328] = "JSDocThisTag";
4033         SyntaxKind[SyntaxKind["JSDocTypeTag"] = 329] = "JSDocTypeTag";
4034         SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 330] = "JSDocTemplateTag";
4035         SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 331] = "JSDocTypedefTag";
4036         SyntaxKind[SyntaxKind["JSDocSeeTag"] = 332] = "JSDocSeeTag";
4037         SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 333] = "JSDocPropertyTag";
4038         // Synthesized list
4039         SyntaxKind[SyntaxKind["SyntaxList"] = 334] = "SyntaxList";
4040         // Transformation nodes
4041         SyntaxKind[SyntaxKind["NotEmittedStatement"] = 335] = "NotEmittedStatement";
4042         SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 336] = "PartiallyEmittedExpression";
4043         SyntaxKind[SyntaxKind["CommaListExpression"] = 337] = "CommaListExpression";
4044         SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 338] = "MergeDeclarationMarker";
4045         SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 339] = "EndOfDeclarationMarker";
4046         SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 340] = "SyntheticReferenceExpression";
4047         // Enum value count
4048         SyntaxKind[SyntaxKind["Count"] = 341] = "Count";
4049         // Markers
4050         SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
4051         SyntaxKind[SyntaxKind["LastAssignment"] = 77] = "LastAssignment";
4052         SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
4053         SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 77] = "LastCompoundAssignment";
4054         SyntaxKind[SyntaxKind["FirstReservedWord"] = 80] = "FirstReservedWord";
4055         SyntaxKind[SyntaxKind["LastReservedWord"] = 115] = "LastReservedWord";
4056         SyntaxKind[SyntaxKind["FirstKeyword"] = 80] = "FirstKeyword";
4057         SyntaxKind[SyntaxKind["LastKeyword"] = 156] = "LastKeyword";
4058         SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 116] = "FirstFutureReservedWord";
4059         SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 124] = "LastFutureReservedWord";
4060         SyntaxKind[SyntaxKind["FirstTypeNode"] = 172] = "FirstTypeNode";
4061         SyntaxKind[SyntaxKind["LastTypeNode"] = 195] = "LastTypeNode";
4062         SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
4063         SyntaxKind[SyntaxKind["LastPunctuation"] = 77] = "LastPunctuation";
4064         SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
4065         SyntaxKind[SyntaxKind["LastToken"] = 156] = "LastToken";
4066         SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
4067         SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
4068         SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
4069         SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
4070         SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
4071         SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
4072         SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
4073         SyntaxKind[SyntaxKind["LastBinaryOperator"] = 77] = "LastBinaryOperator";
4074         SyntaxKind[SyntaxKind["FirstStatement"] = 232] = "FirstStatement";
4075         SyntaxKind[SyntaxKind["LastStatement"] = 248] = "LastStatement";
4076         SyntaxKind[SyntaxKind["FirstNode"] = 157] = "FirstNode";
4077         SyntaxKind[SyntaxKind["FirstJSDocNode"] = 301] = "FirstJSDocNode";
4078         SyntaxKind[SyntaxKind["LastJSDocNode"] = 333] = "LastJSDocNode";
4079         SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 314] = "FirstJSDocTagNode";
4080         SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 333] = "LastJSDocTagNode";
4081         /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 125] = "FirstContextualKeyword";
4082         /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 156] = "LastContextualKeyword";
4083     })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
4084     var NodeFlags;
4085     (function (NodeFlags) {
4086         NodeFlags[NodeFlags["None"] = 0] = "None";
4087         NodeFlags[NodeFlags["Let"] = 1] = "Let";
4088         NodeFlags[NodeFlags["Const"] = 2] = "Const";
4089         NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
4090         NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
4091         NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
4092         NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
4093         NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
4094         NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
4095         NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
4096         NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
4097         NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
4098         NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
4099         NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
4100         NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
4101         NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
4102         NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
4103         NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
4104         NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
4105         NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
4106         NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
4107         // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
4108         // walking the tree if the flags are not set. However, these flags are just a approximation
4109         // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
4110         // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
4111         // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
4112         // However, the removal operation should not occur often and in the case of the
4113         // removal, it is likely that users will add the import anyway.
4114         // The advantage of this approach is its simplicity. For the case of batch compilation,
4115         // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
4116         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
4117         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
4118         NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
4119         /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
4120         /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
4121         NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
4122         /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
4123         /* @internal */ NodeFlags[NodeFlags["Deprecated"] = 134217728] = "Deprecated";
4124         NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
4125         NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
4126         NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
4127         // Parsing context flags
4128         NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
4129         // Exclude these flags when parsing a Type
4130         NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
4131         // Represents all flags that are potentially set once and
4132         // never cleared on SourceFiles which get re-used in between incremental parses.
4133         // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
4134         /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
4135     })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
4136     var ModifierFlags;
4137     (function (ModifierFlags) {
4138         ModifierFlags[ModifierFlags["None"] = 0] = "None";
4139         ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
4140         ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
4141         ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
4142         ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
4143         ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
4144         ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
4145         ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
4146         ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
4147         ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
4148         ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
4149         ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
4150         ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers";
4151         ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated";
4152         ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4153         ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
4154         // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
4155         ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
4156         ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
4157         ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
4158         ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
4159         ModifierFlags[ModifierFlags["All"] = 11263] = "All";
4160     })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
4161     var JsxFlags;
4162     (function (JsxFlags) {
4163         JsxFlags[JsxFlags["None"] = 0] = "None";
4164         /** An element from a named property of the JSX.IntrinsicElements interface */
4165         JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
4166         /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
4167         JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
4168         JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
4169     })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
4170     /* @internal */
4171     var RelationComparisonResult;
4172     (function (RelationComparisonResult) {
4173         RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
4174         RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
4175         RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
4176         RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
4177         RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
4178         RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
4179     })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
4180     var GeneratedIdentifierFlags;
4181     (function (GeneratedIdentifierFlags) {
4182         // Kinds
4183         GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
4184         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
4185         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
4186         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
4187         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
4188         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
4189         // Flags
4190         GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
4191         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
4192         GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
4193         GeneratedIdentifierFlags[GeneratedIdentifierFlags["AllowNameSubstitution"] = 64] = "AllowNameSubstitution";
4194     })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
4195     var TokenFlags;
4196     (function (TokenFlags) {
4197         TokenFlags[TokenFlags["None"] = 0] = "None";
4198         /* @internal */
4199         TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
4200         /* @internal */
4201         TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
4202         /* @internal */
4203         TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
4204         /* @internal */
4205         TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
4206         TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
4207         TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
4208         TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
4209         TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
4210         TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
4211         /* @internal */
4212         TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
4213         /* @internal */
4214         TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
4215         /* @internal */
4216         TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
4217         /* @internal */
4218         TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
4219         /* @internal */
4220         TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
4221         /* @internal */
4222         TokenFlags[TokenFlags["TemplateLiteralLikeFlags"] = 2048] = "TemplateLiteralLikeFlags";
4223     })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
4224     // NOTE: Ensure this is up-to-date with src/debug/debug.ts
4225     var FlowFlags;
4226     (function (FlowFlags) {
4227         FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
4228         FlowFlags[FlowFlags["Start"] = 2] = "Start";
4229         FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
4230         FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
4231         FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
4232         FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
4233         FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
4234         FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
4235         FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
4236         FlowFlags[FlowFlags["Call"] = 512] = "Call";
4237         FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
4238         FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
4239         FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
4240         FlowFlags[FlowFlags["Label"] = 12] = "Label";
4241         FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
4242     })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
4243     /* @internal */
4244     var CommentDirectiveType;
4245     (function (CommentDirectiveType) {
4246         CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
4247         CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
4248     })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
4249     var OperationCanceledException = /** @class */ (function () {
4250         function OperationCanceledException() {
4251         }
4252         return OperationCanceledException;
4253     }());
4254     ts.OperationCanceledException = OperationCanceledException;
4255     /*@internal*/
4256     var RefFileKind;
4257     (function (RefFileKind) {
4258         RefFileKind[RefFileKind["Import"] = 0] = "Import";
4259         RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
4260         RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
4261     })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
4262     /* @internal */
4263     var StructureIsReused;
4264     (function (StructureIsReused) {
4265         StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
4266         StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
4267         StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
4268     })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
4269     /** Return code used by getEmitOutput function to indicate status of the function */
4270     var ExitStatus;
4271     (function (ExitStatus) {
4272         // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
4273         // when -version or -help was provided, or this was a normal compilation, no diagnostics
4274         // were produced, and all outputs were generated successfully.
4275         ExitStatus[ExitStatus["Success"] = 0] = "Success";
4276         // Diagnostics were produced and because of them no code was generated.
4277         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
4278         // Diagnostics were produced and outputs were generated in spite of them.
4279         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
4280         // When build skipped because passed in project is invalid
4281         ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
4282         // When build is skipped because project references form cycle
4283         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
4284         /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
4285         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
4286     })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
4287     /* @internal */
4288     var UnionReduction;
4289     (function (UnionReduction) {
4290         UnionReduction[UnionReduction["None"] = 0] = "None";
4291         UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
4292         UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
4293     })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
4294     /* @internal */
4295     var ContextFlags;
4296     (function (ContextFlags) {
4297         ContextFlags[ContextFlags["None"] = 0] = "None";
4298         ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
4299         ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
4300         ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
4301         ContextFlags[ContextFlags["SkipBindingPatterns"] = 8] = "SkipBindingPatterns";
4302     })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
4303     // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
4304     var NodeBuilderFlags;
4305     (function (NodeBuilderFlags) {
4306         NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
4307         // Options
4308         NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
4309         NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
4310         NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
4311         NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
4312         NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
4313         NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
4314         NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
4315         NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
4316         NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
4317         NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
4318         NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
4319         NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
4320         NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
4321         NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
4322         NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
4323         NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
4324         NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
4325         NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType";
4326         // Error handling
4327         NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
4328         NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
4329         NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
4330         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
4331         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
4332         NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
4333         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
4334         // Errors (cont.)
4335         NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
4336         /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
4337         NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
4338         // State
4339         NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
4340         NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
4341         NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
4342         NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
4343     })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
4344     // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
4345     var TypeFormatFlags;
4346     (function (TypeFormatFlags) {
4347         TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
4348         TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
4349         TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
4350         // hole because there's a hole in node builder flags
4351         TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
4352         // hole because there's a hole in node builder flags
4353         TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
4354         TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
4355         // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
4356         TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
4357         // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
4358         TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
4359         TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
4360         TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
4361         TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
4362         TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
4363         TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
4364         TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
4365         // Error Handling
4366         TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
4367         // TypeFormatFlags exclusive
4368         TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
4369         TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
4370         // State
4371         TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
4372         TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
4373         TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
4374         TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
4375         /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
4376         TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
4377     })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
4378     var SymbolFormatFlags;
4379     (function (SymbolFormatFlags) {
4380         SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
4381         // Write symbols's type argument if it is instantiated symbol
4382         // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
4383         //     var a: C<number>;
4384         //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
4385         SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
4386         // Use only external alias information to get the symbol name in the given context
4387         // eg.  module m { export class c { } } import x = m.c;
4388         // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
4389         SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
4390         // Build symbol name using any nodes needed, instead of just components of an entity name
4391         SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
4392         // Prefer aliases which are not directly visible
4393         SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
4394         // Skip building an accessible symbol chain
4395         /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
4396     })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
4397     /* @internal */
4398     var SymbolAccessibility;
4399     (function (SymbolAccessibility) {
4400         SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
4401         SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
4402         SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
4403     })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
4404     /* @internal */
4405     var SyntheticSymbolKind;
4406     (function (SyntheticSymbolKind) {
4407         SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
4408         SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
4409     })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
4410     var TypePredicateKind;
4411     (function (TypePredicateKind) {
4412         TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
4413         TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
4414         TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
4415         TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
4416     })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
4417     /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
4418     /* @internal */
4419     var TypeReferenceSerializationKind;
4420     (function (TypeReferenceSerializationKind) {
4421         // The TypeReferenceNode could not be resolved.
4422         // The type name should be emitted using a safe fallback.
4423         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
4424         // The TypeReferenceNode resolves to a type with a constructor
4425         // function that can be reached at runtime (e.g. a `class`
4426         // declaration or a `var` declaration for the static side
4427         // of a type, such as the global `Promise` type in lib.d.ts).
4428         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
4429         // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
4430         TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
4431         // The TypeReferenceNode resolves to a Number-like type.
4432         TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
4433         // The TypeReferenceNode resolves to a BigInt-like type.
4434         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
4435         // The TypeReferenceNode resolves to a String-like type.
4436         TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
4437         // The TypeReferenceNode resolves to a Boolean-like type.
4438         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
4439         // The TypeReferenceNode resolves to an Array-like type.
4440         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
4441         // The TypeReferenceNode resolves to the ESSymbol type.
4442         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
4443         // The TypeReferenceNode resolved to the global Promise constructor symbol.
4444         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
4445         // The TypeReferenceNode resolves to a Function type or a type with call signatures.
4446         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
4447         // The TypeReferenceNode resolves to any other type.
4448         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
4449     })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
4450     var SymbolFlags;
4451     (function (SymbolFlags) {
4452         SymbolFlags[SymbolFlags["None"] = 0] = "None";
4453         SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
4454         SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
4455         SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
4456         SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
4457         SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
4458         SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
4459         SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
4460         SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
4461         SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
4462         SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
4463         SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
4464         SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
4465         SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
4466         SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
4467         SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
4468         SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
4469         SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
4470         SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
4471         SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
4472         SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
4473         SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
4474         SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
4475         SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
4476         SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
4477         SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
4478         SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
4479         SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
4480         SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
4481         /* @internal */
4482         SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
4483         SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
4484         SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
4485         SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
4486         SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
4487         SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
4488         SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
4489         SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
4490         // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
4491         // same name, or any other value that is not a variable, e.g. ValueModule or Class
4492         SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
4493         // Block-scoped declarations are not allowed to be re-declared
4494         // they can not merge with anything in the value space
4495         SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
4496         SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
4497         SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
4498         SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
4499         SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
4500         SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
4501         SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
4502         SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
4503         SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
4504         SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
4505         SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
4506         SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
4507         SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
4508         SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
4509         SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
4510         SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
4511         SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
4512         SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
4513         SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
4514         SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
4515         SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
4516         SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
4517         /* @internal */
4518         SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
4519         /* @internal */
4520         SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
4521         /* @internal */
4522         // The set of things we consider semantically classifiable.  Used to speed up the LS during
4523         // classification.
4524         SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
4525         /* @internal */
4526         SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
4527     })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
4528     /* @internal */
4529     var EnumKind;
4530     (function (EnumKind) {
4531         EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
4532         EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
4533     })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
4534     /* @internal */
4535     var CheckFlags;
4536     (function (CheckFlags) {
4537         CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
4538         CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
4539         CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
4540         CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
4541         CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
4542         CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
4543         CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
4544         CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
4545         CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
4546         CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
4547         CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
4548         CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
4549         CheckFlags[CheckFlags["Late"] = 4096] = "Late";
4550         CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
4551         CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
4552         CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
4553         CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
4554         CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
4555         CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
4556         CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
4557         CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
4558         CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
4559         CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
4560     })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
4561     var InternalSymbolName;
4562     (function (InternalSymbolName) {
4563         InternalSymbolName["Call"] = "__call";
4564         InternalSymbolName["Constructor"] = "__constructor";
4565         InternalSymbolName["New"] = "__new";
4566         InternalSymbolName["Index"] = "__index";
4567         InternalSymbolName["ExportStar"] = "__export";
4568         InternalSymbolName["Global"] = "__global";
4569         InternalSymbolName["Missing"] = "__missing";
4570         InternalSymbolName["Type"] = "__type";
4571         InternalSymbolName["Object"] = "__object";
4572         InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
4573         InternalSymbolName["Class"] = "__class";
4574         InternalSymbolName["Function"] = "__function";
4575         InternalSymbolName["Computed"] = "__computed";
4576         InternalSymbolName["Resolving"] = "__resolving__";
4577         InternalSymbolName["ExportEquals"] = "export=";
4578         InternalSymbolName["Default"] = "default";
4579         InternalSymbolName["This"] = "this";
4580     })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
4581     /* @internal */
4582     var NodeCheckFlags;
4583     (function (NodeCheckFlags) {
4584         NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
4585         NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
4586         NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
4587         NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
4588         NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
4589         NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
4590         NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
4591         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
4592         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
4593         NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
4594         NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
4595         NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
4596         NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
4597         NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
4598         NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
4599         NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
4600         NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
4601         NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
4602         NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
4603         NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
4604         NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
4605         NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
4606         NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
4607     })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
4608     var TypeFlags;
4609     (function (TypeFlags) {
4610         TypeFlags[TypeFlags["Any"] = 1] = "Any";
4611         TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
4612         TypeFlags[TypeFlags["String"] = 4] = "String";
4613         TypeFlags[TypeFlags["Number"] = 8] = "Number";
4614         TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
4615         TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
4616         TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
4617         TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
4618         TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
4619         TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
4620         TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
4621         TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
4622         TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
4623         TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
4624         TypeFlags[TypeFlags["Void"] = 16384] = "Void";
4625         TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
4626         TypeFlags[TypeFlags["Null"] = 65536] = "Null";
4627         TypeFlags[TypeFlags["Never"] = 131072] = "Never";
4628         TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
4629         TypeFlags[TypeFlags["Object"] = 524288] = "Object";
4630         TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
4631         TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
4632         TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
4633         TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
4634         TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
4635         TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
4636         TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
4637         TypeFlags[TypeFlags["TemplateLiteral"] = 134217728] = "TemplateLiteral";
4638         TypeFlags[TypeFlags["StringMapping"] = 268435456] = "StringMapping";
4639         /* @internal */
4640         TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
4641         /* @internal */
4642         TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
4643         TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
4644         TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
4645         TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
4646         /* @internal */
4647         TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
4648         /* @internal */
4649         TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
4650         TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
4651         /* @internal */
4652         TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
4653         /* @internal */
4654         TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
4655         TypeFlags[TypeFlags["StringLike"] = 402653316] = "StringLike";
4656         TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
4657         TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
4658         TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
4659         TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
4660         TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
4661         TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
4662         /* @internal */
4663         TypeFlags[TypeFlags["DisjointDomains"] = 469892092] = "DisjointDomains";
4664         TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
4665         TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
4666         TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
4667         TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
4668         TypeFlags[TypeFlags["InstantiablePrimitive"] = 406847488] = "InstantiablePrimitive";
4669         TypeFlags[TypeFlags["Instantiable"] = 465829888] = "Instantiable";
4670         TypeFlags[TypeFlags["StructuredOrInstantiable"] = 469499904] = "StructuredOrInstantiable";
4671         /* @internal */
4672         TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
4673         /* @internal */
4674         TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
4675         /* @internal */
4676         TypeFlags[TypeFlags["Substructure"] = 469237760] = "Substructure";
4677         // 'Narrowable' types are types where narrowing actually narrows.
4678         // This *should* be every type other than null, undefined, void, and never
4679         TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable";
4680         /* @internal */
4681         TypeFlags[TypeFlags["NotPrimitiveUnion"] = 469647395] = "NotPrimitiveUnion";
4682         // The following flags are aggregated during union and intersection type construction
4683         /* @internal */
4684         TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask";
4685         // The following flags are used for different purposes during union and intersection type construction
4686         /* @internal */
4687         TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
4688         /* @internal */
4689         TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
4690         /* @internal */
4691         TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
4692         /* @internal */
4693         TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
4694     })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
4695     var ObjectFlags;
4696     (function (ObjectFlags) {
4697         ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
4698         ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
4699         ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
4700         ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
4701         ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
4702         ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
4703         ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
4704         ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
4705         ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
4706         ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
4707         ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
4708         ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
4709         ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
4710         ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
4711         ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
4712         ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
4713         ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
4714         ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
4715         /* @internal */
4716         ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
4717         /* @internal */
4718         ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
4719         /* @internal */
4720         ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
4721         /* @internal */
4722         ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
4723         /* @internal */
4724         ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
4725         /* @internal */
4726         ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
4727         /* @internal */
4728         ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
4729         /* @internal */
4730         ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
4731         /* @internal */
4732         ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
4733         /* @internal */
4734         ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
4735         /* @internal */
4736         ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
4737         /* @internal */
4738         ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
4739         /* @internal */
4740         ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
4741         /* @internal */
4742         ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone";
4743         ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
4744         /* @internal */
4745         ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
4746         /* @internal */
4747         ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
4748         // Object flags that uniquely identify the kind of ObjectType
4749         /* @internal */
4750         ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask";
4751     })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
4752     /* @internal */
4753     var VarianceFlags;
4754     (function (VarianceFlags) {
4755         VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
4756         VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
4757         VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
4758         VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
4759         VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
4760         VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
4761         VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
4762         VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
4763         VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
4764     })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
4765     var ElementFlags;
4766     (function (ElementFlags) {
4767         ElementFlags[ElementFlags["Required"] = 1] = "Required";
4768         ElementFlags[ElementFlags["Optional"] = 2] = "Optional";
4769         ElementFlags[ElementFlags["Rest"] = 4] = "Rest";
4770         ElementFlags[ElementFlags["Variadic"] = 8] = "Variadic";
4771         ElementFlags[ElementFlags["Variable"] = 12] = "Variable";
4772     })(ElementFlags = ts.ElementFlags || (ts.ElementFlags = {}));
4773     /* @internal */
4774     var JsxReferenceKind;
4775     (function (JsxReferenceKind) {
4776         JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
4777         JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
4778         JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
4779     })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
4780     var SignatureKind;
4781     (function (SignatureKind) {
4782         SignatureKind[SignatureKind["Call"] = 0] = "Call";
4783         SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
4784     })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
4785     /* @internal */
4786     var SignatureFlags;
4787     (function (SignatureFlags) {
4788         SignatureFlags[SignatureFlags["None"] = 0] = "None";
4789         SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
4790         SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
4791         SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
4792         SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
4793         SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
4794         // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
4795         // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
4796         // instantiating the return type.
4797         SignatureFlags[SignatureFlags["PropagatingFlags"] = 19] = "PropagatingFlags";
4798         SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
4799     })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
4800     var IndexKind;
4801     (function (IndexKind) {
4802         IndexKind[IndexKind["String"] = 0] = "String";
4803         IndexKind[IndexKind["Number"] = 1] = "Number";
4804     })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
4805     /* @internal */
4806     var TypeMapKind;
4807     (function (TypeMapKind) {
4808         TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
4809         TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
4810         TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
4811         TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
4812         TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
4813     })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
4814     var InferencePriority;
4815     (function (InferencePriority) {
4816         InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
4817         InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple";
4818         InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType";
4819         InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType";
4820         InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint";
4821         InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional";
4822         InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType";
4823         InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof";
4824         InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints";
4825         InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict";
4826         InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue";
4827         InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination";
4828         InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
4829     })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
4830     /* @internal */
4831     var InferenceFlags;
4832     (function (InferenceFlags) {
4833         InferenceFlags[InferenceFlags["None"] = 0] = "None";
4834         InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
4835         InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
4836         InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
4837     })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
4838     /**
4839      * Ternary values are defined such that
4840      * x & y picks the lesser in the order False < Unknown < Maybe < True, and
4841      * x | y picks the greater in the order False < Unknown < Maybe < True.
4842      * Generally, Ternary.Maybe is used as the result of a relation that depends on itself, and
4843      * Ternary.Unknown is used as the result of a variance check that depends on itself. We make
4844      * a distinction because we don't want to cache circular variance check results.
4845      */
4846     /* @internal */
4847     var Ternary;
4848     (function (Ternary) {
4849         Ternary[Ternary["False"] = 0] = "False";
4850         Ternary[Ternary["Unknown"] = 1] = "Unknown";
4851         Ternary[Ternary["Maybe"] = 3] = "Maybe";
4852         Ternary[Ternary["True"] = -1] = "True";
4853     })(Ternary = ts.Ternary || (ts.Ternary = {}));
4854     /* @internal */
4855     var AssignmentDeclarationKind;
4856     (function (AssignmentDeclarationKind) {
4857         AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
4858         /// exports.name = expr
4859         /// module.exports.name = expr
4860         AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
4861         /// module.exports = expr
4862         AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
4863         /// className.prototype.name = expr
4864         AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
4865         /// this.name = expr
4866         AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
4867         // F.name = expr
4868         AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
4869         // F.prototype = { ... }
4870         AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
4871         // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
4872         // Object.defineProperty(x, 'name', { get: Function, set: Function });
4873         // Object.defineProperty(x, 'name', { get: Function });
4874         // Object.defineProperty(x, 'name', { set: Function });
4875         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
4876         // Object.defineProperty(exports || module.exports, 'name', ...);
4877         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
4878         // Object.defineProperty(Foo.prototype, 'name', ...);
4879         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
4880     })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
4881     var DiagnosticCategory;
4882     (function (DiagnosticCategory) {
4883         DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
4884         DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
4885         DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
4886         DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
4887     })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
4888     /* @internal */
4889     function diagnosticCategoryName(d, lowerCase) {
4890         if (lowerCase === void 0) { lowerCase = true; }
4891         var name = DiagnosticCategory[d.category];
4892         return lowerCase ? name.toLowerCase() : name;
4893     }
4894     ts.diagnosticCategoryName = diagnosticCategoryName;
4895     var ModuleResolutionKind;
4896     (function (ModuleResolutionKind) {
4897         ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
4898         ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
4899     })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
4900     var WatchFileKind;
4901     (function (WatchFileKind) {
4902         WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
4903         WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
4904         WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4905         WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
4906         WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
4907     })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
4908     var WatchDirectoryKind;
4909     (function (WatchDirectoryKind) {
4910         WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
4911         WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
4912         WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4913     })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
4914     var PollingWatchKind;
4915     (function (PollingWatchKind) {
4916         PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
4917         PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
4918         PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
4919     })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
4920     var ModuleKind;
4921     (function (ModuleKind) {
4922         ModuleKind[ModuleKind["None"] = 0] = "None";
4923         ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
4924         ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
4925         ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
4926         ModuleKind[ModuleKind["System"] = 4] = "System";
4927         // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
4928         //       Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
4929         //       module kind).
4930         ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
4931         ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
4932         ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
4933     })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
4934     var JsxEmit;
4935     (function (JsxEmit) {
4936         JsxEmit[JsxEmit["None"] = 0] = "None";
4937         JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
4938         JsxEmit[JsxEmit["React"] = 2] = "React";
4939         JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
4940         JsxEmit[JsxEmit["ReactJSX"] = 4] = "ReactJSX";
4941         JsxEmit[JsxEmit["ReactJSXDev"] = 5] = "ReactJSXDev";
4942     })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
4943     var ImportsNotUsedAsValues;
4944     (function (ImportsNotUsedAsValues) {
4945         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
4946         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
4947         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
4948     })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
4949     var NewLineKind;
4950     (function (NewLineKind) {
4951         NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
4952         NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
4953     })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
4954     var ScriptKind;
4955     (function (ScriptKind) {
4956         ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
4957         ScriptKind[ScriptKind["JS"] = 1] = "JS";
4958         ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
4959         ScriptKind[ScriptKind["TS"] = 3] = "TS";
4960         ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
4961         ScriptKind[ScriptKind["External"] = 5] = "External";
4962         ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
4963         /**
4964          * Used on extensions that doesn't define the ScriptKind but the content defines it.
4965          * Deferred extensions are going to be included in all project contexts.
4966          */
4967         ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
4968     })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
4969     var ScriptTarget;
4970     (function (ScriptTarget) {
4971         ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
4972         ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
4973         ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
4974         ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
4975         ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
4976         ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
4977         ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
4978         ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
4979         ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
4980         ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
4981         ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
4982     })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
4983     var LanguageVariant;
4984     (function (LanguageVariant) {
4985         LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
4986         LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
4987     })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
4988     var WatchDirectoryFlags;
4989     (function (WatchDirectoryFlags) {
4990         WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
4991         WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
4992     })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
4993     /* @internal */
4994     var CharacterCodes;
4995     (function (CharacterCodes) {
4996         CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
4997         CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
4998         CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
4999         CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
5000         CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
5001         CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
5002         CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
5003         // Unicode 3.0 space characters
5004         CharacterCodes[CharacterCodes["space"] = 32] = "space";
5005         CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
5006         CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
5007         CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
5008         CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
5009         CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
5010         CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
5011         CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
5012         CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
5013         CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
5014         CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
5015         CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
5016         CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
5017         CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
5018         CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
5019         CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
5020         CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
5021         CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
5022         CharacterCodes[CharacterCodes["_"] = 95] = "_";
5023         CharacterCodes[CharacterCodes["$"] = 36] = "$";
5024         CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
5025         CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
5026         CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
5027         CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
5028         CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
5029         CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
5030         CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
5031         CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
5032         CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
5033         CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
5034         CharacterCodes[CharacterCodes["a"] = 97] = "a";
5035         CharacterCodes[CharacterCodes["b"] = 98] = "b";
5036         CharacterCodes[CharacterCodes["c"] = 99] = "c";
5037         CharacterCodes[CharacterCodes["d"] = 100] = "d";
5038         CharacterCodes[CharacterCodes["e"] = 101] = "e";
5039         CharacterCodes[CharacterCodes["f"] = 102] = "f";
5040         CharacterCodes[CharacterCodes["g"] = 103] = "g";
5041         CharacterCodes[CharacterCodes["h"] = 104] = "h";
5042         CharacterCodes[CharacterCodes["i"] = 105] = "i";
5043         CharacterCodes[CharacterCodes["j"] = 106] = "j";
5044         CharacterCodes[CharacterCodes["k"] = 107] = "k";
5045         CharacterCodes[CharacterCodes["l"] = 108] = "l";
5046         CharacterCodes[CharacterCodes["m"] = 109] = "m";
5047         CharacterCodes[CharacterCodes["n"] = 110] = "n";
5048         CharacterCodes[CharacterCodes["o"] = 111] = "o";
5049         CharacterCodes[CharacterCodes["p"] = 112] = "p";
5050         CharacterCodes[CharacterCodes["q"] = 113] = "q";
5051         CharacterCodes[CharacterCodes["r"] = 114] = "r";
5052         CharacterCodes[CharacterCodes["s"] = 115] = "s";
5053         CharacterCodes[CharacterCodes["t"] = 116] = "t";
5054         CharacterCodes[CharacterCodes["u"] = 117] = "u";
5055         CharacterCodes[CharacterCodes["v"] = 118] = "v";
5056         CharacterCodes[CharacterCodes["w"] = 119] = "w";
5057         CharacterCodes[CharacterCodes["x"] = 120] = "x";
5058         CharacterCodes[CharacterCodes["y"] = 121] = "y";
5059         CharacterCodes[CharacterCodes["z"] = 122] = "z";
5060         CharacterCodes[CharacterCodes["A"] = 65] = "A";
5061         CharacterCodes[CharacterCodes["B"] = 66] = "B";
5062         CharacterCodes[CharacterCodes["C"] = 67] = "C";
5063         CharacterCodes[CharacterCodes["D"] = 68] = "D";
5064         CharacterCodes[CharacterCodes["E"] = 69] = "E";
5065         CharacterCodes[CharacterCodes["F"] = 70] = "F";
5066         CharacterCodes[CharacterCodes["G"] = 71] = "G";
5067         CharacterCodes[CharacterCodes["H"] = 72] = "H";
5068         CharacterCodes[CharacterCodes["I"] = 73] = "I";
5069         CharacterCodes[CharacterCodes["J"] = 74] = "J";
5070         CharacterCodes[CharacterCodes["K"] = 75] = "K";
5071         CharacterCodes[CharacterCodes["L"] = 76] = "L";
5072         CharacterCodes[CharacterCodes["M"] = 77] = "M";
5073         CharacterCodes[CharacterCodes["N"] = 78] = "N";
5074         CharacterCodes[CharacterCodes["O"] = 79] = "O";
5075         CharacterCodes[CharacterCodes["P"] = 80] = "P";
5076         CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
5077         CharacterCodes[CharacterCodes["R"] = 82] = "R";
5078         CharacterCodes[CharacterCodes["S"] = 83] = "S";
5079         CharacterCodes[CharacterCodes["T"] = 84] = "T";
5080         CharacterCodes[CharacterCodes["U"] = 85] = "U";
5081         CharacterCodes[CharacterCodes["V"] = 86] = "V";
5082         CharacterCodes[CharacterCodes["W"] = 87] = "W";
5083         CharacterCodes[CharacterCodes["X"] = 88] = "X";
5084         CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
5085         CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
5086         CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
5087         CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
5088         CharacterCodes[CharacterCodes["at"] = 64] = "at";
5089         CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
5090         CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
5091         CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
5092         CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
5093         CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
5094         CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
5095         CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
5096         CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
5097         CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
5098         CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
5099         CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
5100         CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
5101         CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
5102         CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
5103         CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
5104         CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
5105         CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
5106         CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
5107         CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
5108         CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
5109         CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
5110         CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
5111         CharacterCodes[CharacterCodes["question"] = 63] = "question";
5112         CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
5113         CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
5114         CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
5115         CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
5116         CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
5117         CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
5118         CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
5119         CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
5120         CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
5121     })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
5122     var Extension;
5123     (function (Extension) {
5124         Extension["Ts"] = ".ts";
5125         Extension["Tsx"] = ".tsx";
5126         Extension["Dts"] = ".d.ts";
5127         Extension["Js"] = ".js";
5128         Extension["Jsx"] = ".jsx";
5129         Extension["Json"] = ".json";
5130         Extension["TsBuildInfo"] = ".tsbuildinfo";
5131     })(Extension = ts.Extension || (ts.Extension = {}));
5132     /* @internal */
5133     var TransformFlags;
5134     (function (TransformFlags) {
5135         TransformFlags[TransformFlags["None"] = 0] = "None";
5136         // Facts
5137         // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
5138         TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
5139         TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
5140         TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
5141         TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
5142         TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
5143         TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
5144         TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
5145         TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
5146         TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
5147         TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
5148         TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
5149         // Markers
5150         // - Flags used to indicate that a subtree contains a specific transformation.
5151         TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
5152         TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
5153         TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
5154         TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
5155         TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
5156         TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
5157         TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
5158         TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
5159         TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
5160         TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
5161         TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
5162         TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
5163         TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 8388608] = "ContainsPossibleTopLevelAwait";
5164         // Please leave this as 1 << 29.
5165         // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
5166         // It is a good reminder of how much room we have left
5167         TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
5168         // Assertions
5169         // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
5170         TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
5171         TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
5172         TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
5173         TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
5174         TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
5175         TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
5176         TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
5177         TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
5178         TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
5179         TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
5180         TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
5181         // Scope Exclusions
5182         // - Bitmasks that exclude flags from propagating out of a specific context
5183         //   into the subtree flags of their container.
5184         TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
5185         TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
5186         TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
5187         TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 547309568] = "ArrowFunctionExcludes";
5188         TransformFlags[TransformFlags["FunctionExcludes"] = 547313664] = "FunctionExcludes";
5189         TransformFlags[TransformFlags["ConstructorExcludes"] = 547311616] = "ConstructorExcludes";
5190         TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
5191         TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
5192         TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
5193         TransformFlags[TransformFlags["ModuleExcludes"] = 546379776] = "ModuleExcludes";
5194         TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
5195         TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
5196         TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
5197         TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
5198         TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
5199         TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
5200         TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
5201         // Propagating flags
5202         // - Bitmasks for flags that should propagate from a child
5203         TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
5204         // Masks
5205         // - Additional bitmasks
5206     })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
5207     var EmitFlags;
5208     (function (EmitFlags) {
5209         EmitFlags[EmitFlags["None"] = 0] = "None";
5210         EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
5211         EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
5212         EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
5213         EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
5214         EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
5215         EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
5216         EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
5217         EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
5218         EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
5219         EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
5220         EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
5221         EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
5222         EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
5223         EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
5224         EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
5225         EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
5226         EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
5227         EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
5228         EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
5229         EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
5230         EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
5231         EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
5232         EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
5233         EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
5234         EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
5235         EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
5236         EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
5237         EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
5238         /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
5239         /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
5240         /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
5241     })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
5242     /**
5243      * Used by the checker, this enum keeps track of external emit helpers that should be type
5244      * checked.
5245      */
5246     /* @internal */
5247     var ExternalEmitHelpers;
5248     (function (ExternalEmitHelpers) {
5249         ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
5250         ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
5251         ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
5252         ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
5253         ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
5254         ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
5255         ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
5256         ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
5257         ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
5258         ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
5259         ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
5260         ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
5261         ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
5262         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
5263         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
5264         ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
5265         ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
5266         ExternalEmitHelpers[ExternalEmitHelpers["ImportStar"] = 131072] = "ImportStar";
5267         ExternalEmitHelpers[ExternalEmitHelpers["ImportDefault"] = 262144] = "ImportDefault";
5268         ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 524288] = "MakeTemplateObject";
5269         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 1048576] = "ClassPrivateFieldGet";
5270         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 2097152] = "ClassPrivateFieldSet";
5271         ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 4194304] = "CreateBinding";
5272         ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
5273         ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 4194304] = "LastEmitHelper";
5274         // Helpers included by ES2015 for..of
5275         ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
5276         // Helpers included by ES2017 for..await..of
5277         ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
5278         // Helpers included by ES2017 async generators
5279         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
5280         // Helpers included by yield* in ES2017 async generators
5281         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
5282         // Helpers included by ES2015 spread
5283         ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
5284     })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
5285     var EmitHint;
5286     (function (EmitHint) {
5287         EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
5288         EmitHint[EmitHint["Expression"] = 1] = "Expression";
5289         EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
5290         EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
5291         EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
5292         EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
5293         EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
5294     })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
5295     var OuterExpressionKinds;
5296     (function (OuterExpressionKinds) {
5297         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
5298         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
5299         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
5300         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
5301         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
5302         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
5303     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
5304     /* @internal */
5305     var LexicalEnvironmentFlags;
5306     (function (LexicalEnvironmentFlags) {
5307         LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
5308         LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
5309         LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
5310     })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
5311     /*@internal*/
5312     var BundleFileSectionKind;
5313     (function (BundleFileSectionKind) {
5314         BundleFileSectionKind["Prologue"] = "prologue";
5315         BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
5316         BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
5317         BundleFileSectionKind["Reference"] = "reference";
5318         BundleFileSectionKind["Type"] = "type";
5319         BundleFileSectionKind["Lib"] = "lib";
5320         BundleFileSectionKind["Prepend"] = "prepend";
5321         BundleFileSectionKind["Text"] = "text";
5322         BundleFileSectionKind["Internal"] = "internal";
5323         // comments?
5324     })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
5325     var ListFormat;
5326     (function (ListFormat) {
5327         ListFormat[ListFormat["None"] = 0] = "None";
5328         // Line separators
5329         ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
5330         ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
5331         ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
5332         ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
5333         // Delimiters
5334         ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
5335         ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
5336         ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
5337         ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
5338         ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
5339         ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
5340         ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
5341         // Whitespace
5342         ListFormat[ListFormat["Indented"] = 128] = "Indented";
5343         ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
5344         ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
5345         // Brackets/Braces
5346         ListFormat[ListFormat["Braces"] = 1024] = "Braces";
5347         ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
5348         ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
5349         ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
5350         ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
5351         ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
5352         ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
5353         ListFormat[ListFormat["Optional"] = 49152] = "Optional";
5354         // Other
5355         ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
5356         ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
5357         ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
5358         ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
5359         ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
5360         ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
5361         // Precomputed Formats
5362         ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
5363         ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
5364         ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
5365         ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
5366         ListFormat[ListFormat["SingleLineTupleTypeElements"] = 528] = "SingleLineTupleTypeElements";
5367         ListFormat[ListFormat["MultiLineTupleTypeElements"] = 657] = "MultiLineTupleTypeElements";
5368         ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
5369         ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
5370         ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
5371         ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
5372         ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
5373         ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
5374         ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
5375         ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
5376         ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
5377         ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
5378         ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
5379         ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
5380         ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
5381         ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
5382         ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
5383         ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
5384         ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
5385         ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
5386         ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
5387         ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
5388         ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
5389         ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
5390         ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
5391         ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
5392         ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
5393         ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
5394         ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
5395         ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
5396         ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
5397         ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
5398         ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
5399         ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
5400     })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
5401     /* @internal */
5402     var PragmaKindFlags;
5403     (function (PragmaKindFlags) {
5404         PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
5405         /**
5406          * Triple slash comment of the form
5407          * /// <pragma-name argname="value" />
5408          */
5409         PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
5410         /**
5411          * Single line comment of the form
5412          * // @pragma-name argval1 argval2
5413          * or
5414          * /// @pragma-name argval1 argval2
5415          */
5416         PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
5417         /**
5418          * Multiline non-jsdoc pragma of the form
5419          * /* @pragma-name argval1 argval2 * /
5420          */
5421         PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
5422         PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
5423         PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
5424     })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
5425     // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
5426     //  fancy effectively defining it twice, once in value-space and once in type-space
5427     /* @internal */
5428     ts.commentPragmas = {
5429         "reference": {
5430             args: [
5431                 { name: "types", optional: true, captureSpan: true },
5432                 { name: "lib", optional: true, captureSpan: true },
5433                 { name: "path", optional: true, captureSpan: true },
5434                 { name: "no-default-lib", optional: true }
5435             ],
5436             kind: 1 /* TripleSlashXML */
5437         },
5438         "amd-dependency": {
5439             args: [{ name: "path" }, { name: "name", optional: true }],
5440             kind: 1 /* TripleSlashXML */
5441         },
5442         "amd-module": {
5443             args: [{ name: "name" }],
5444             kind: 1 /* TripleSlashXML */
5445         },
5446         "ts-check": {
5447             kind: 2 /* SingleLine */
5448         },
5449         "ts-nocheck": {
5450             kind: 2 /* SingleLine */
5451         },
5452         "jsx": {
5453             args: [{ name: "factory" }],
5454             kind: 4 /* MultiLine */
5455         },
5456         "jsxfrag": {
5457             args: [{ name: "factory" }],
5458             kind: 4 /* MultiLine */
5459         },
5460         "jsximportsource": {
5461             args: [{ name: "factory" }],
5462             kind: 4 /* MultiLine */
5463         },
5464         "jsxruntime": {
5465             args: [{ name: "factory" }],
5466             kind: 4 /* MultiLine */
5467         },
5468     };
5469 })(ts || (ts = {}));
5470 /* @internal */
5471 var ts;
5472 (function (ts) {
5473     /**
5474      * Internally, we represent paths as strings with '/' as the directory separator.
5475      * When we make system calls (eg: LanguageServiceHost.getDirectory()),
5476      * we expect the host to correctly handle paths in our specified format.
5477      */
5478     ts.directorySeparator = "/";
5479     var altDirectorySeparator = "\\";
5480     var urlSchemeSeparator = "://";
5481     var backslashRegExp = /\\/g;
5482     //// Path Tests
5483     /**
5484      * Determines whether a charCode corresponds to `/` or `\`.
5485      */
5486     function isAnyDirectorySeparator(charCode) {
5487         return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
5488     }
5489     ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
5490     /**
5491      * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
5492      */
5493     function isUrl(path) {
5494         return getEncodedRootLength(path) < 0;
5495     }
5496     ts.isUrl = isUrl;
5497     /**
5498      * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
5499      * like `c:`, `c:\` or `c:/`).
5500      */
5501     function isRootedDiskPath(path) {
5502         return getEncodedRootLength(path) > 0;
5503     }
5504     ts.isRootedDiskPath = isRootedDiskPath;
5505     /**
5506      * Determines whether a path consists only of a path root.
5507      */
5508     function isDiskPathRoot(path) {
5509         var rootLength = getEncodedRootLength(path);
5510         return rootLength > 0 && rootLength === path.length;
5511     }
5512     ts.isDiskPathRoot = isDiskPathRoot;
5513     /**
5514      * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
5515      *
5516      * ```ts
5517      * // POSIX
5518      * pathIsAbsolute("/path/to/file.ext") === true
5519      * // DOS
5520      * pathIsAbsolute("c:/path/to/file.ext") === true
5521      * // URL
5522      * pathIsAbsolute("file:///path/to/file.ext") === true
5523      * // Non-absolute
5524      * pathIsAbsolute("path/to/file.ext") === false
5525      * pathIsAbsolute("./path/to/file.ext") === false
5526      * ```
5527      */
5528     function pathIsAbsolute(path) {
5529         return getEncodedRootLength(path) !== 0;
5530     }
5531     ts.pathIsAbsolute = pathIsAbsolute;
5532     /**
5533      * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
5534      */
5535     function pathIsRelative(path) {
5536         return /^\.\.?($|[\\/])/.test(path);
5537     }
5538     ts.pathIsRelative = pathIsRelative;
5539     /**
5540      * Determines whether a path is neither relative nor absolute, e.g. "path/to/file".
5541      * Also known misleadingly as "non-relative".
5542      */
5543     function pathIsBareSpecifier(path) {
5544         return !pathIsAbsolute(path) && !pathIsRelative(path);
5545     }
5546     ts.pathIsBareSpecifier = pathIsBareSpecifier;
5547     function hasExtension(fileName) {
5548         return ts.stringContains(getBaseFileName(fileName), ".");
5549     }
5550     ts.hasExtension = hasExtension;
5551     function fileExtensionIs(path, extension) {
5552         return path.length > extension.length && ts.endsWith(path, extension);
5553     }
5554     ts.fileExtensionIs = fileExtensionIs;
5555     function fileExtensionIsOneOf(path, extensions) {
5556         for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
5557             var extension = extensions_1[_i];
5558             if (fileExtensionIs(path, extension)) {
5559                 return true;
5560             }
5561         }
5562         return false;
5563     }
5564     ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
5565     /**
5566      * Determines whether a path has a trailing separator (`/` or `\\`).
5567      */
5568     function hasTrailingDirectorySeparator(path) {
5569         return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
5570     }
5571     ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
5572     //// Path Parsing
5573     function isVolumeCharacter(charCode) {
5574         return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
5575             (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
5576     }
5577     function getFileUrlVolumeSeparatorEnd(url, start) {
5578         var ch0 = url.charCodeAt(start);
5579         if (ch0 === 58 /* colon */)
5580             return start + 1;
5581         if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
5582             var ch2 = url.charCodeAt(start + 2);
5583             if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
5584                 return start + 3;
5585         }
5586         return -1;
5587     }
5588     /**
5589      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
5590      * If the root is part of a URL, the twos-complement of the root length is returned.
5591      */
5592     function getEncodedRootLength(path) {
5593         if (!path)
5594             return 0;
5595         var ch0 = path.charCodeAt(0);
5596         // POSIX or UNC
5597         if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
5598             if (path.charCodeAt(1) !== ch0)
5599                 return 1; // POSIX: "/" (or non-normalized "\")
5600             var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
5601             if (p1 < 0)
5602                 return path.length; // UNC: "//server" or "\\server"
5603             return p1 + 1; // UNC: "//server/" or "\\server\"
5604         }
5605         // DOS
5606         if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
5607             var ch2 = path.charCodeAt(2);
5608             if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
5609                 return 3; // DOS: "c:/" or "c:\"
5610             if (path.length === 2)
5611                 return 2; // DOS: "c:" (but not "c:d")
5612         }
5613         // URL
5614         var schemeEnd = path.indexOf(urlSchemeSeparator);
5615         if (schemeEnd !== -1) {
5616             var authorityStart = schemeEnd + urlSchemeSeparator.length;
5617             var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
5618             if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
5619                 // For local "file" URLs, include the leading DOS volume (if present).
5620                 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
5621                 // special case interpreted as "the machine from which the URL is being interpreted".
5622                 var scheme = path.slice(0, schemeEnd);
5623                 var authority = path.slice(authorityStart, authorityEnd);
5624                 if (scheme === "file" && (authority === "" || authority === "localhost") &&
5625                     isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
5626                     var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
5627                     if (volumeSeparatorEnd !== -1) {
5628                         if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
5629                             // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
5630                             return ~(volumeSeparatorEnd + 1);
5631                         }
5632                         if (volumeSeparatorEnd === path.length) {
5633                             // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
5634                             // but not "file:///c:d" or "file:///c%3ad"
5635                             return ~volumeSeparatorEnd;
5636                         }
5637                     }
5638                 }
5639                 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
5640             }
5641             return ~path.length; // URL: "file://server", "http://server"
5642         }
5643         // relative
5644         return 0;
5645     }
5646     /**
5647      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
5648      *
5649      * For example:
5650      * ```ts
5651      * getRootLength("a") === 0                   // ""
5652      * getRootLength("/") === 1                   // "/"
5653      * getRootLength("c:") === 2                  // "c:"
5654      * getRootLength("c:d") === 0                 // ""
5655      * getRootLength("c:/") === 3                 // "c:/"
5656      * getRootLength("c:\\") === 3                // "c:\\"
5657      * getRootLength("//server") === 7            // "//server"
5658      * getRootLength("//server/share") === 8      // "//server/"
5659      * getRootLength("\\\\server") === 7          // "\\\\server"
5660      * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
5661      * getRootLength("file:///path") === 8        // "file:///"
5662      * getRootLength("file:///c:") === 10         // "file:///c:"
5663      * getRootLength("file:///c:d") === 8         // "file:///"
5664      * getRootLength("file:///c:/path") === 11    // "file:///c:/"
5665      * getRootLength("file://server") === 13      // "file://server"
5666      * getRootLength("file://server/path") === 14 // "file://server/"
5667      * getRootLength("http://server") === 13      // "http://server"
5668      * getRootLength("http://server/path") === 14 // "http://server/"
5669      * ```
5670      */
5671     function getRootLength(path) {
5672         var rootLength = getEncodedRootLength(path);
5673         return rootLength < 0 ? ~rootLength : rootLength;
5674     }
5675     ts.getRootLength = getRootLength;
5676     function getDirectoryPath(path) {
5677         path = normalizeSlashes(path);
5678         // If the path provided is itself the root, then return it.
5679         var rootLength = getRootLength(path);
5680         if (rootLength === path.length)
5681             return path;
5682         // return the leading portion of the path up to the last (non-terminal) directory separator
5683         // but not including any trailing directory separator.
5684         path = removeTrailingDirectorySeparator(path);
5685         return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
5686     }
5687     ts.getDirectoryPath = getDirectoryPath;
5688     function getBaseFileName(path, extensions, ignoreCase) {
5689         path = normalizeSlashes(path);
5690         // if the path provided is itself the root, then it has not file name.
5691         var rootLength = getRootLength(path);
5692         if (rootLength === path.length)
5693             return "";
5694         // return the trailing portion of the path starting after the last (non-terminal) directory
5695         // separator but not including any trailing directory separator.
5696         path = removeTrailingDirectorySeparator(path);
5697         var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
5698         var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
5699         return extension ? name.slice(0, name.length - extension.length) : name;
5700     }
5701     ts.getBaseFileName = getBaseFileName;
5702     function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
5703         if (!ts.startsWith(extension, "."))
5704             extension = "." + extension;
5705         if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
5706             var pathExtension = path.slice(path.length - extension.length);
5707             if (stringEqualityComparer(pathExtension, extension)) {
5708                 return pathExtension;
5709             }
5710         }
5711     }
5712     function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
5713         if (typeof extensions === "string") {
5714             return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
5715         }
5716         for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
5717             var extension = extensions_2[_i];
5718             var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
5719             if (result)
5720                 return result;
5721         }
5722         return "";
5723     }
5724     function getAnyExtensionFromPath(path, extensions, ignoreCase) {
5725         // Retrieves any string from the final "." onwards from a base file name.
5726         // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
5727         if (extensions) {
5728             return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
5729         }
5730         var baseFileName = getBaseFileName(path);
5731         var extensionIndex = baseFileName.lastIndexOf(".");
5732         if (extensionIndex >= 0) {
5733             return baseFileName.substring(extensionIndex);
5734         }
5735         return "";
5736     }
5737     ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
5738     function pathComponents(path, rootLength) {
5739         var root = path.substring(0, rootLength);
5740         var rest = path.substring(rootLength).split(ts.directorySeparator);
5741         if (rest.length && !ts.lastOrUndefined(rest))
5742             rest.pop();
5743         return __spreadArrays([root], rest);
5744     }
5745     /**
5746      * Parse a path into an array containing a root component (at index 0) and zero or more path
5747      * components (at indices > 0). The result is not normalized.
5748      * If the path is relative, the root component is `""`.
5749      * If the path is absolute, the root component includes the first path separator (`/`).
5750      *
5751      * ```ts
5752      * // POSIX
5753      * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
5754      * getPathComponents("/path/to/") === ["/", "path", "to"]
5755      * getPathComponents("/") === ["/"]
5756      * // DOS
5757      * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
5758      * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
5759      * getPathComponents("c:/") === ["c:/"]
5760      * getPathComponents("c:") === ["c:"]
5761      * // URL
5762      * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
5763      * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
5764      * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
5765      * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
5766      * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
5767      * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
5768      * getPathComponents("file://server/") === ["file://server/"]
5769      * getPathComponents("file://server") === ["file://server"]
5770      * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
5771      * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
5772      * getPathComponents("file:///") === ["file:///"]
5773      * getPathComponents("file://") === ["file://"]
5774      */
5775     function getPathComponents(path, currentDirectory) {
5776         if (currentDirectory === void 0) { currentDirectory = ""; }
5777         path = combinePaths(currentDirectory, path);
5778         return pathComponents(path, getRootLength(path));
5779     }
5780     ts.getPathComponents = getPathComponents;
5781     //// Path Formatting
5782     /**
5783      * Formats a parsed path consisting of a root component (at index 0) and zero or more path
5784      * segments (at indices > 0).
5785      *
5786      * ```ts
5787      * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
5788      * ```
5789      */
5790     function getPathFromPathComponents(pathComponents) {
5791         if (pathComponents.length === 0)
5792             return "";
5793         var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
5794         return root + pathComponents.slice(1).join(ts.directorySeparator);
5795     }
5796     ts.getPathFromPathComponents = getPathFromPathComponents;
5797     //// Path Normalization
5798     /**
5799      * Normalize path separators, converting `\` into `/`.
5800      */
5801     function normalizeSlashes(path) {
5802         return path.replace(backslashRegExp, ts.directorySeparator);
5803     }
5804     ts.normalizeSlashes = normalizeSlashes;
5805     /**
5806      * Reduce an array of path components to a more simplified path by navigating any
5807      * `"."` or `".."` entries in the path.
5808      */
5809     function reducePathComponents(components) {
5810         if (!ts.some(components))
5811             return [];
5812         var reduced = [components[0]];
5813         for (var i = 1; i < components.length; i++) {
5814             var component = components[i];
5815             if (!component)
5816                 continue;
5817             if (component === ".")
5818                 continue;
5819             if (component === "..") {
5820                 if (reduced.length > 1) {
5821                     if (reduced[reduced.length - 1] !== "..") {
5822                         reduced.pop();
5823                         continue;
5824                     }
5825                 }
5826                 else if (reduced[0])
5827                     continue;
5828             }
5829             reduced.push(component);
5830         }
5831         return reduced;
5832     }
5833     ts.reducePathComponents = reducePathComponents;
5834     /**
5835      * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
5836      *
5837      * ```ts
5838      * // Non-rooted
5839      * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
5840      * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
5841      * // POSIX
5842      * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
5843      * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
5844      * // DOS
5845      * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
5846      * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
5847      * // URL
5848      * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
5849      * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
5850      * ```
5851      */
5852     function combinePaths(path) {
5853         var paths = [];
5854         for (var _i = 1; _i < arguments.length; _i++) {
5855             paths[_i - 1] = arguments[_i];
5856         }
5857         if (path)
5858             path = normalizeSlashes(path);
5859         for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
5860             var relativePath = paths_1[_a];
5861             if (!relativePath)
5862                 continue;
5863             relativePath = normalizeSlashes(relativePath);
5864             if (!path || getRootLength(relativePath) !== 0) {
5865                 path = relativePath;
5866             }
5867             else {
5868                 path = ensureTrailingDirectorySeparator(path) + relativePath;
5869             }
5870         }
5871         return path;
5872     }
5873     ts.combinePaths = combinePaths;
5874     /**
5875      * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
5876      * `.` and `..` path components are resolved. Trailing directory separators are preserved.
5877      *
5878      * ```ts
5879      * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
5880      * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
5881      * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
5882      * ```
5883      */
5884     function resolvePath(path) {
5885         var paths = [];
5886         for (var _i = 1; _i < arguments.length; _i++) {
5887             paths[_i - 1] = arguments[_i];
5888         }
5889         return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
5890     }
5891     ts.resolvePath = resolvePath;
5892     /**
5893      * Parse a path into an array containing a root component (at index 0) and zero or more path
5894      * components (at indices > 0). The result is normalized.
5895      * If the path is relative, the root component is `""`.
5896      * If the path is absolute, the root component includes the first path separator (`/`).
5897      *
5898      * ```ts
5899      * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
5900      * ```
5901      */
5902     function getNormalizedPathComponents(path, currentDirectory) {
5903         return reducePathComponents(getPathComponents(path, currentDirectory));
5904     }
5905     ts.getNormalizedPathComponents = getNormalizedPathComponents;
5906     function getNormalizedAbsolutePath(fileName, currentDirectory) {
5907         return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
5908     }
5909     ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
5910     function normalizePath(path) {
5911         path = normalizeSlashes(path);
5912         var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
5913         return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
5914     }
5915     ts.normalizePath = normalizePath;
5916     function getPathWithoutRoot(pathComponents) {
5917         if (pathComponents.length === 0)
5918             return "";
5919         return pathComponents.slice(1).join(ts.directorySeparator);
5920     }
5921     function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
5922         return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
5923     }
5924     ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
5925     function toPath(fileName, basePath, getCanonicalFileName) {
5926         var nonCanonicalizedPath = isRootedDiskPath(fileName)
5927             ? normalizePath(fileName)
5928             : getNormalizedAbsolutePath(fileName, basePath);
5929         return getCanonicalFileName(nonCanonicalizedPath);
5930     }
5931     ts.toPath = toPath;
5932     function normalizePathAndParts(path) {
5933         path = normalizeSlashes(path);
5934         var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
5935         if (parts.length) {
5936             var joinedParts = root + parts.join(ts.directorySeparator);
5937             return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
5938         }
5939         else {
5940             return { path: root, parts: parts };
5941         }
5942     }
5943     ts.normalizePathAndParts = normalizePathAndParts;
5944     function removeTrailingDirectorySeparator(path) {
5945         if (hasTrailingDirectorySeparator(path)) {
5946             return path.substr(0, path.length - 1);
5947         }
5948         return path;
5949     }
5950     ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
5951     function ensureTrailingDirectorySeparator(path) {
5952         if (!hasTrailingDirectorySeparator(path)) {
5953             return path + ts.directorySeparator;
5954         }
5955         return path;
5956     }
5957     ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
5958     /**
5959      * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
5960      * with `./` or `../`) so as not to be confused with an unprefixed module name.
5961      *
5962      * ```ts
5963      * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
5964      * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
5965      * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
5966      * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
5967      * ```
5968      */
5969     function ensurePathIsNonModuleName(path) {
5970         return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
5971     }
5972     ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
5973     function changeAnyExtension(path, ext, extensions, ignoreCase) {
5974         var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
5975         return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
5976     }
5977     ts.changeAnyExtension = changeAnyExtension;
5978     //// Path Comparisons
5979     // check path for these segments: '', '.'. '..'
5980     var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
5981     function comparePathsWorker(a, b, componentComparer) {
5982         if (a === b)
5983             return 0 /* EqualTo */;
5984         if (a === undefined)
5985             return -1 /* LessThan */;
5986         if (b === undefined)
5987             return 1 /* GreaterThan */;
5988         // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
5989         //       need to perform path reduction.
5990         var aRoot = a.substring(0, getRootLength(a));
5991         var bRoot = b.substring(0, getRootLength(b));
5992         var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
5993         if (result !== 0 /* EqualTo */) {
5994             return result;
5995         }
5996         // NOTE: Performance optimization - shortcut if there are no relative path segments in
5997         //       the non-root portion of the path
5998         var aRest = a.substring(aRoot.length);
5999         var bRest = b.substring(bRoot.length);
6000         if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6001             return componentComparer(aRest, bRest);
6002         }
6003         // The path contains a relative path segment. Normalize the paths and perform a slower component
6004         // by component comparison.
6005         var aComponents = reducePathComponents(getPathComponents(a));
6006         var bComponents = reducePathComponents(getPathComponents(b));
6007         var sharedLength = Math.min(aComponents.length, bComponents.length);
6008         for (var i = 1; i < sharedLength; i++) {
6009             var result_2 = componentComparer(aComponents[i], bComponents[i]);
6010             if (result_2 !== 0 /* EqualTo */) {
6011                 return result_2;
6012             }
6013         }
6014         return ts.compareValues(aComponents.length, bComponents.length);
6015     }
6016     /**
6017      * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6018      */
6019     function comparePathsCaseSensitive(a, b) {
6020         return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6021     }
6022     ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6023     /**
6024      * Performs a case-insensitive comparison of two paths.
6025      */
6026     function comparePathsCaseInsensitive(a, b) {
6027         return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6028     }
6029     ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6030     function comparePaths(a, b, currentDirectory, ignoreCase) {
6031         if (typeof currentDirectory === "string") {
6032             a = combinePaths(currentDirectory, a);
6033             b = combinePaths(currentDirectory, b);
6034         }
6035         else if (typeof currentDirectory === "boolean") {
6036             ignoreCase = currentDirectory;
6037         }
6038         return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6039     }
6040     ts.comparePaths = comparePaths;
6041     function containsPath(parent, child, currentDirectory, ignoreCase) {
6042         if (typeof currentDirectory === "string") {
6043             parent = combinePaths(currentDirectory, parent);
6044             child = combinePaths(currentDirectory, child);
6045         }
6046         else if (typeof currentDirectory === "boolean") {
6047             ignoreCase = currentDirectory;
6048         }
6049         if (parent === undefined || child === undefined)
6050             return false;
6051         if (parent === child)
6052             return true;
6053         var parentComponents = reducePathComponents(getPathComponents(parent));
6054         var childComponents = reducePathComponents(getPathComponents(child));
6055         if (childComponents.length < parentComponents.length) {
6056             return false;
6057         }
6058         var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6059         for (var i = 0; i < parentComponents.length; i++) {
6060             var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6061             if (!equalityComparer(parentComponents[i], childComponents[i])) {
6062                 return false;
6063             }
6064         }
6065         return true;
6066     }
6067     ts.containsPath = containsPath;
6068     /**
6069      * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6070      * Comparison is case-sensitive between the canonical paths.
6071      *
6072      * @deprecated Use `containsPath` if possible.
6073      */
6074     function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6075         var canonicalFileName = getCanonicalFileName(fileName);
6076         var canonicalDirectoryName = getCanonicalFileName(directoryName);
6077         return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6078     }
6079     ts.startsWithDirectory = startsWithDirectory;
6080     //// Relative Paths
6081     function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6082         var fromComponents = reducePathComponents(getPathComponents(from));
6083         var toComponents = reducePathComponents(getPathComponents(to));
6084         var start;
6085         for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6086             var fromComponent = getCanonicalFileName(fromComponents[start]);
6087             var toComponent = getCanonicalFileName(toComponents[start]);
6088             var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6089             if (!comparer(fromComponent, toComponent))
6090                 break;
6091         }
6092         if (start === 0) {
6093             return toComponents;
6094         }
6095         var components = toComponents.slice(start);
6096         var relative = [];
6097         for (; start < fromComponents.length; start++) {
6098             relative.push("..");
6099         }
6100         return __spreadArrays([""], relative, components);
6101     }
6102     ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6103     function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6104         ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6105         var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6106         var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6107         var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6108         return getPathFromPathComponents(pathComponents);
6109     }
6110     ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6111     function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6112         return !isRootedDiskPath(absoluteOrRelativePath)
6113             ? absoluteOrRelativePath
6114             : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6115     }
6116     ts.convertToRelativePath = convertToRelativePath;
6117     function getRelativePathFromFile(from, to, getCanonicalFileName) {
6118         return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6119     }
6120     ts.getRelativePathFromFile = getRelativePathFromFile;
6121     function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6122         var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6123         var firstComponent = pathComponents[0];
6124         if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6125             var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6126             pathComponents[0] = prefix + firstComponent;
6127         }
6128         return getPathFromPathComponents(pathComponents);
6129     }
6130     ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6131     function forEachAncestorDirectory(directory, callback) {
6132         while (true) {
6133             var result = callback(directory);
6134             if (result !== undefined) {
6135                 return result;
6136             }
6137             var parentPath = getDirectoryPath(directory);
6138             if (parentPath === directory) {
6139                 return undefined;
6140             }
6141             directory = parentPath;
6142         }
6143     }
6144     ts.forEachAncestorDirectory = forEachAncestorDirectory;
6145     function isNodeModulesDirectory(dirPath) {
6146         return ts.endsWith(dirPath, "/node_modules");
6147     }
6148     ts.isNodeModulesDirectory = isNodeModulesDirectory;
6149 })(ts || (ts = {}));
6150 var ts;
6151 (function (ts) {
6152     /**
6153      * djb2 hashing algorithm
6154      * http://www.cse.yorku.ca/~oz/hash.html
6155      */
6156     /* @internal */
6157     function generateDjb2Hash(data) {
6158         var acc = 5381;
6159         for (var i = 0; i < data.length; i++) {
6160             acc = ((acc << 5) + acc) + data.charCodeAt(i);
6161         }
6162         return acc.toString();
6163     }
6164     ts.generateDjb2Hash = generateDjb2Hash;
6165     /**
6166      * Set a high stack trace limit to provide more information in case of an error.
6167      * Called for command-line and server use cases.
6168      * Not called if TypeScript is used as a library.
6169      */
6170     /* @internal */
6171     function setStackTraceLimit() {
6172         if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
6173             Error.stackTraceLimit = 100;
6174         }
6175     }
6176     ts.setStackTraceLimit = setStackTraceLimit;
6177     var FileWatcherEventKind;
6178     (function (FileWatcherEventKind) {
6179         FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
6180         FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
6181         FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
6182     })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
6183     /* @internal */
6184     var PollingInterval;
6185     (function (PollingInterval) {
6186         PollingInterval[PollingInterval["High"] = 2000] = "High";
6187         PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
6188         PollingInterval[PollingInterval["Low"] = 250] = "Low";
6189     })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
6190     /* @internal */
6191     ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
6192     function createPollingIntervalBasedLevels(levels) {
6193         var _a;
6194         return _a = {},
6195             _a[PollingInterval.Low] = levels.Low,
6196             _a[PollingInterval.Medium] = levels.Medium,
6197             _a[PollingInterval.High] = levels.High,
6198             _a;
6199     }
6200     var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
6201     var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
6202     /* @internal */
6203     ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
6204     /* @internal */
6205     function setCustomPollingValues(system) {
6206         if (!system.getEnvironmentVariable) {
6207             return;
6208         }
6209         var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
6210         pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
6211         ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
6212         function getLevel(envVar, level) {
6213             return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
6214         }
6215         function getCustomLevels(baseVariable) {
6216             var customLevels;
6217             setCustomLevel("Low");
6218             setCustomLevel("Medium");
6219             setCustomLevel("High");
6220             return customLevels;
6221             function setCustomLevel(level) {
6222                 var customLevel = getLevel(baseVariable, level);
6223                 if (customLevel) {
6224                     (customLevels || (customLevels = {}))[level] = Number(customLevel);
6225                 }
6226             }
6227         }
6228         function setCustomLevels(baseVariable, levels) {
6229             var customLevels = getCustomLevels(baseVariable);
6230             if (customLevels) {
6231                 setLevel("Low");
6232                 setLevel("Medium");
6233                 setLevel("High");
6234                 return true;
6235             }
6236             return false;
6237             function setLevel(level) {
6238                 levels[level] = customLevels[level] || levels[level];
6239             }
6240         }
6241         function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
6242             var customLevels = getCustomLevels(baseVariable);
6243             return (pollingIntervalChanged || customLevels) &&
6244                 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
6245         }
6246     }
6247     ts.setCustomPollingValues = setCustomPollingValues;
6248     /* @internal */
6249     function createDynamicPriorityPollingWatchFile(host) {
6250         var watchedFiles = [];
6251         var changedFilesInLastPoll = [];
6252         var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
6253         var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
6254         var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
6255         return watchFile;
6256         function watchFile(fileName, callback, defaultPollingInterval) {
6257             var file = {
6258                 fileName: fileName,
6259                 callback: callback,
6260                 unchangedPolls: 0,
6261                 mtime: getModifiedTime(fileName)
6262             };
6263             watchedFiles.push(file);
6264             addToPollingIntervalQueue(file, defaultPollingInterval);
6265             return {
6266                 close: function () {
6267                     file.isClosed = true;
6268                     // Remove from watchedFiles
6269                     ts.unorderedRemoveItem(watchedFiles, file);
6270                     // Do not update polling interval queue since that will happen as part of polling
6271                 }
6272             };
6273         }
6274         function createPollingIntervalQueue(pollingInterval) {
6275             var queue = [];
6276             queue.pollingInterval = pollingInterval;
6277             queue.pollIndex = 0;
6278             queue.pollScheduled = false;
6279             return queue;
6280         }
6281         function pollPollingIntervalQueue(queue) {
6282             queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
6283             // Set the next polling index and timeout
6284             if (queue.length) {
6285                 scheduleNextPoll(queue.pollingInterval);
6286             }
6287             else {
6288                 ts.Debug.assert(queue.pollIndex === 0);
6289                 queue.pollScheduled = false;
6290             }
6291         }
6292         function pollLowPollingIntervalQueue(queue) {
6293             // Always poll complete list of changedFilesInLastPoll
6294             pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
6295             // Finally do the actual polling of the queue
6296             pollPollingIntervalQueue(queue);
6297             // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
6298             // as pollPollingIntervalQueue wont schedule for next poll
6299             if (!queue.pollScheduled && changedFilesInLastPoll.length) {
6300                 scheduleNextPoll(PollingInterval.Low);
6301             }
6302         }
6303         function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
6304             // Max visit would be all elements of the queue
6305             var needsVisit = queue.length;
6306             var definedValueCopyToIndex = pollIndex;
6307             for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
6308                 var watchedFile = queue[pollIndex];
6309                 if (!watchedFile) {
6310                     continue;
6311                 }
6312                 else if (watchedFile.isClosed) {
6313                     queue[pollIndex] = undefined;
6314                     continue;
6315                 }
6316                 polled++;
6317                 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
6318                 if (watchedFile.isClosed) {
6319                     // Closed watcher as part of callback
6320                     queue[pollIndex] = undefined;
6321                 }
6322                 else if (fileChanged) {
6323                     watchedFile.unchangedPolls = 0;
6324                     // Changed files go to changedFilesInLastPoll queue
6325                     if (queue !== changedFilesInLastPoll) {
6326                         queue[pollIndex] = undefined;
6327                         addChangedFileToLowPollingIntervalQueue(watchedFile);
6328                     }
6329                 }
6330                 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
6331                     watchedFile.unchangedPolls++;
6332                 }
6333                 else if (queue === changedFilesInLastPoll) {
6334                     // Restart unchangedPollCount for unchanged file and move to low polling interval queue
6335                     watchedFile.unchangedPolls = 1;
6336                     queue[pollIndex] = undefined;
6337                     addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
6338                 }
6339                 else if (pollingInterval !== PollingInterval.High) {
6340                     watchedFile.unchangedPolls++;
6341                     queue[pollIndex] = undefined;
6342                     addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
6343                 }
6344                 if (queue[pollIndex]) {
6345                     // Copy this file to the non hole location
6346                     if (definedValueCopyToIndex < pollIndex) {
6347                         queue[definedValueCopyToIndex] = watchedFile;
6348                         queue[pollIndex] = undefined;
6349                     }
6350                     definedValueCopyToIndex++;
6351                 }
6352             }
6353             // Return next poll index
6354             return pollIndex;
6355             function nextPollIndex() {
6356                 pollIndex++;
6357                 if (pollIndex === queue.length) {
6358                     if (definedValueCopyToIndex < pollIndex) {
6359                         // There are holes from nextDefinedValueIndex to end of queue, change queue size
6360                         queue.length = definedValueCopyToIndex;
6361                     }
6362                     pollIndex = 0;
6363                     definedValueCopyToIndex = 0;
6364                 }
6365             }
6366         }
6367         function pollingIntervalQueue(pollingInterval) {
6368             switch (pollingInterval) {
6369                 case PollingInterval.Low:
6370                     return lowPollingIntervalQueue;
6371                 case PollingInterval.Medium:
6372                     return mediumPollingIntervalQueue;
6373                 case PollingInterval.High:
6374                     return highPollingIntervalQueue;
6375             }
6376         }
6377         function addToPollingIntervalQueue(file, pollingInterval) {
6378             pollingIntervalQueue(pollingInterval).push(file);
6379             scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
6380         }
6381         function addChangedFileToLowPollingIntervalQueue(file) {
6382             changedFilesInLastPoll.push(file);
6383             scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
6384         }
6385         function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
6386             if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
6387                 scheduleNextPoll(pollingInterval);
6388             }
6389         }
6390         function scheduleNextPoll(pollingInterval) {
6391             pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
6392         }
6393         function getModifiedTime(fileName) {
6394             return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
6395         }
6396     }
6397     ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
6398     function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
6399         // One file can have multiple watchers
6400         var fileWatcherCallbacks = ts.createMultiMap();
6401         var dirWatchers = new ts.Map();
6402         var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6403         return nonPollingWatchFile;
6404         function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
6405             var filePath = toCanonicalName(fileName);
6406             fileWatcherCallbacks.add(filePath, callback);
6407             var dirPath = ts.getDirectoryPath(filePath) || ".";
6408             var watcher = dirWatchers.get(dirPath) ||
6409                 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
6410             watcher.referenceCount++;
6411             return {
6412                 close: function () {
6413                     if (watcher.referenceCount === 1) {
6414                         watcher.close();
6415                         dirWatchers.delete(dirPath);
6416                     }
6417                     else {
6418                         watcher.referenceCount--;
6419                     }
6420                     fileWatcherCallbacks.remove(filePath, callback);
6421                 }
6422             };
6423         }
6424         function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
6425             var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
6426                 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
6427                 if (!ts.isString(relativeFileName)) {
6428                     return;
6429                 }
6430                 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
6431                 // Some applications save a working file via rename operations
6432                 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
6433                 if (callbacks) {
6434                     for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
6435                         var fileCallback = callbacks_1[_i];
6436                         fileCallback(fileName, FileWatcherEventKind.Changed);
6437                     }
6438                 }
6439             }, 
6440             /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
6441             watcher.referenceCount = 0;
6442             dirWatchers.set(dirPath, watcher);
6443             return watcher;
6444         }
6445     }
6446     /* @internal */
6447     function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
6448         var cache = new ts.Map();
6449         var callbacksCache = ts.createMultiMap();
6450         var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6451         return function (fileName, callback, pollingInterval, options) {
6452             var path = toCanonicalFileName(fileName);
6453             var existing = cache.get(path);
6454             if (existing) {
6455                 existing.refCount++;
6456             }
6457             else {
6458                 cache.set(path, {
6459                     watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
6460                     refCount: 1
6461                 });
6462             }
6463             callbacksCache.add(path, callback);
6464             return {
6465                 close: function () {
6466                     var watcher = ts.Debug.checkDefined(cache.get(path));
6467                     callbacksCache.remove(path, callback);
6468                     watcher.refCount--;
6469                     if (watcher.refCount)
6470                         return;
6471                     cache.delete(path);
6472                     ts.closeFileWatcherOf(watcher);
6473                 }
6474             };
6475         };
6476     }
6477     ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
6478     /**
6479      * Returns true if file status changed
6480      */
6481     /*@internal*/
6482     function onWatchedFileStat(watchedFile, modifiedTime) {
6483         var oldTime = watchedFile.mtime.getTime();
6484         var newTime = modifiedTime.getTime();
6485         if (oldTime !== newTime) {
6486             watchedFile.mtime = modifiedTime;
6487             watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
6488             return true;
6489         }
6490         return false;
6491     }
6492     ts.onWatchedFileStat = onWatchedFileStat;
6493     /*@internal*/
6494     function getFileWatcherEventKind(oldTime, newTime) {
6495         return oldTime === 0
6496             ? FileWatcherEventKind.Created
6497             : newTime === 0
6498                 ? FileWatcherEventKind.Deleted
6499                 : FileWatcherEventKind.Changed;
6500     }
6501     ts.getFileWatcherEventKind = getFileWatcherEventKind;
6502     /*@internal*/
6503     ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
6504     /*@internal*/
6505     ts.sysLog = ts.noop; // eslint-disable-line prefer-const
6506     /*@internal*/
6507     function setSysLog(logger) {
6508         ts.sysLog = logger;
6509     }
6510     ts.setSysLog = setSysLog;
6511     /**
6512      * Watch the directory recursively using host provided method to watch child directories
6513      * that means if this is recursive watcher, watch the children directories as well
6514      * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
6515      */
6516     /*@internal*/
6517     function createDirectoryWatcherSupportingRecursive(host) {
6518         var cache = new ts.Map();
6519         var callbackCache = ts.createMultiMap();
6520         var cacheToUpdateChildWatches = new ts.Map();
6521         var timerToUpdateChildWatches;
6522         var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
6523         var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
6524         return function (dirName, callback, recursive, options) { return recursive ?
6525             createDirectoryWatcher(dirName, options, callback) :
6526             host.watchDirectory(dirName, callback, recursive, options); };
6527         /**
6528          * Create the directory watcher for the dirPath.
6529          */
6530         function createDirectoryWatcher(dirName, options, callback) {
6531             var dirPath = toCanonicalFilePath(dirName);
6532             var directoryWatcher = cache.get(dirPath);
6533             if (directoryWatcher) {
6534                 directoryWatcher.refCount++;
6535             }
6536             else {
6537                 directoryWatcher = {
6538                     watcher: host.watchDirectory(dirName, function (fileName) {
6539                         if (isIgnoredPath(fileName))
6540                             return;
6541                         if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
6542                             // Call the actual callback
6543                             invokeCallbacks(dirPath, fileName);
6544                             // Iterate through existing children and update the watches if needed
6545                             updateChildWatches(dirName, dirPath, options);
6546                         }
6547                         else {
6548                             nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
6549                         }
6550                     }, /*recursive*/ false, options),
6551                     refCount: 1,
6552                     childWatches: ts.emptyArray
6553                 };
6554                 cache.set(dirPath, directoryWatcher);
6555                 updateChildWatches(dirName, dirPath, options);
6556             }
6557             var callbackToAdd = callback && { dirName: dirName, callback: callback };
6558             if (callbackToAdd) {
6559                 callbackCache.add(dirPath, callbackToAdd);
6560             }
6561             return {
6562                 dirName: dirName,
6563                 close: function () {
6564                     var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
6565                     if (callbackToAdd)
6566                         callbackCache.remove(dirPath, callbackToAdd);
6567                     directoryWatcher.refCount--;
6568                     if (directoryWatcher.refCount)
6569                         return;
6570                     cache.delete(dirPath);
6571                     ts.closeFileWatcherOf(directoryWatcher);
6572                     directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
6573                 }
6574             };
6575         }
6576         function invokeCallbacks(dirPath, fileNameOrInvokeMap, fileNames) {
6577             var fileName;
6578             var invokeMap;
6579             if (ts.isString(fileNameOrInvokeMap)) {
6580                 fileName = fileNameOrInvokeMap;
6581             }
6582             else {
6583                 invokeMap = fileNameOrInvokeMap;
6584             }
6585             // Call the actual callback
6586             callbackCache.forEach(function (callbacks, rootDirName) {
6587                 var _a;
6588                 if (invokeMap && invokeMap.get(rootDirName) === true)
6589                     return;
6590                 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
6591                     if (invokeMap) {
6592                         if (fileNames) {
6593                             var existing = invokeMap.get(rootDirName);
6594                             if (existing) {
6595                                 (_a = existing).push.apply(_a, fileNames);
6596                             }
6597                             else {
6598                                 invokeMap.set(rootDirName, fileNames.slice());
6599                             }
6600                         }
6601                         else {
6602                             invokeMap.set(rootDirName, true);
6603                         }
6604                     }
6605                     else {
6606                         callbacks.forEach(function (_a) {
6607                             var callback = _a.callback;
6608                             return callback(fileName);
6609                         });
6610                     }
6611                 }
6612             });
6613         }
6614         function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
6615             // Iterate through existing children and update the watches if needed
6616             var parentWatcher = cache.get(dirPath);
6617             if (parentWatcher && host.directoryExists(dirName)) {
6618                 // Schedule the update and postpone invoke for callbacks
6619                 scheduleUpdateChildWatches(dirName, dirPath, fileName, options);
6620                 return;
6621             }
6622             // Call the actual callbacks and remove child watches
6623             invokeCallbacks(dirPath, fileName);
6624             removeChildWatches(parentWatcher);
6625         }
6626         function scheduleUpdateChildWatches(dirName, dirPath, fileName, options) {
6627             var existing = cacheToUpdateChildWatches.get(dirPath);
6628             if (existing) {
6629                 existing.fileNames.push(fileName);
6630             }
6631             else {
6632                 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options, fileNames: [fileName] });
6633             }
6634             if (timerToUpdateChildWatches) {
6635                 host.clearTimeout(timerToUpdateChildWatches);
6636                 timerToUpdateChildWatches = undefined;
6637             }
6638             timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
6639         }
6640         function onTimerToUpdateChildWatches() {
6641             timerToUpdateChildWatches = undefined;
6642             ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
6643             var start = ts.timestamp();
6644             var invokeMap = new ts.Map();
6645             while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
6646                 var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, fileNames = _c.fileNames, done = _a.done;
6647                 ts.Debug.assert(!done);
6648                 cacheToUpdateChildWatches.delete(dirPath);
6649                 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
6650                 // to ensure that all the changes are reflected at this time
6651                 var hasChanges = updateChildWatches(dirName, dirPath, options);
6652                 invokeCallbacks(dirPath, invokeMap, hasChanges ? undefined : fileNames);
6653             }
6654             ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
6655             callbackCache.forEach(function (callbacks, rootDirName) {
6656                 var existing = invokeMap.get(rootDirName);
6657                 if (existing) {
6658                     callbacks.forEach(function (_a) {
6659                         var callback = _a.callback, dirName = _a.dirName;
6660                         if (ts.isArray(existing)) {
6661                             existing.forEach(callback);
6662                         }
6663                         else {
6664                             callback(dirName);
6665                         }
6666                     });
6667                 }
6668             });
6669             var elapsed = ts.timestamp() - start;
6670             ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
6671         }
6672         function removeChildWatches(parentWatcher) {
6673             if (!parentWatcher)
6674                 return;
6675             var existingChildWatches = parentWatcher.childWatches;
6676             parentWatcher.childWatches = ts.emptyArray;
6677             for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
6678                 var childWatcher = existingChildWatches_1[_i];
6679                 childWatcher.close();
6680                 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
6681             }
6682         }
6683         function updateChildWatches(parentDir, parentDirPath, options) {
6684             // Iterate through existing children and update the watches if needed
6685             var parentWatcher = cache.get(parentDirPath);
6686             if (!parentWatcher)
6687                 return false;
6688             var newChildWatches;
6689             var hasChanges = ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
6690                 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
6691                 // Filter our the symbolic link directories since those arent included in recursive watch
6692                 // which is same behaviour when recursive: true is passed to fs.watch
6693                 return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
6694             }) : ts.emptyArray, parentWatcher.childWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
6695             parentWatcher.childWatches = newChildWatches || ts.emptyArray;
6696             return hasChanges;
6697             /**
6698              * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
6699              */
6700             function createAndAddChildDirectoryWatcher(childName) {
6701                 var result = createDirectoryWatcher(childName, options);
6702                 addChildDirectoryWatcher(result);
6703             }
6704             /**
6705              * Add child directory watcher to the new ChildDirectoryWatcher list
6706              */
6707             function addChildDirectoryWatcher(childWatcher) {
6708                 (newChildWatches || (newChildWatches = [])).push(childWatcher);
6709             }
6710         }
6711         function isIgnoredPath(path) {
6712             return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
6713         }
6714         function isInPath(path, searchPath) {
6715             if (ts.stringContains(path, searchPath))
6716                 return true;
6717             if (host.useCaseSensitiveFileNames)
6718                 return false;
6719             return ts.stringContains(toCanonicalFilePath(path), searchPath);
6720         }
6721     }
6722     ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
6723     /*@internal*/
6724     var FileSystemEntryKind;
6725     (function (FileSystemEntryKind) {
6726         FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
6727         FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
6728     })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
6729     /*@internal*/
6730     function createFileWatcherCallback(callback) {
6731         return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
6732     }
6733     ts.createFileWatcherCallback = createFileWatcherCallback;
6734     function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
6735         return function (eventName) {
6736             if (eventName === "rename") {
6737                 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
6738             }
6739             else {
6740                 // Change
6741                 callback(fileName, FileWatcherEventKind.Changed);
6742             }
6743         };
6744     }
6745     function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
6746         return function (eventName, relativeFileName) {
6747             // In watchDirectory we only care about adding and removing files (when event name is
6748             // "rename"); changes made within files are handled by corresponding fileWatchers (when
6749             // event name is "change")
6750             if (eventName === "rename") {
6751                 // When deleting a file, the passed baseFileName is null
6752                 callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
6753             }
6754         };
6755     }
6756     /*@internal*/
6757     function createSystemWatchFunctions(_a) {
6758         var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory;
6759         var dynamicPollingWatchFile;
6760         var nonPollingWatchFile;
6761         var hostRecursiveDirectoryWatcher;
6762         return {
6763             watchFile: watchFile,
6764             watchDirectory: watchDirectory
6765         };
6766         function watchFile(fileName, callback, pollingInterval, options) {
6767             options = updateOptionsForWatchFile(options, useNonPollingWatchers);
6768             var watchFileKind = ts.Debug.checkDefined(options.watchFile);
6769             switch (watchFileKind) {
6770                 case ts.WatchFileKind.FixedPollingInterval:
6771                     return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
6772                 case ts.WatchFileKind.PriorityPollingInterval:
6773                     return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
6774                 case ts.WatchFileKind.DynamicPriorityPolling:
6775                     return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
6776                 case ts.WatchFileKind.UseFsEvents:
6777                     return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), 
6778                     /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
6779                 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
6780                     if (!nonPollingWatchFile) {
6781                         nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
6782                     }
6783                     return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
6784                 default:
6785                     ts.Debug.assertNever(watchFileKind);
6786             }
6787         }
6788         function ensureDynamicPollingWatchFile() {
6789             return dynamicPollingWatchFile ||
6790                 (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
6791         }
6792         function updateOptionsForWatchFile(options, useNonPollingWatchers) {
6793             if (options && options.watchFile !== undefined)
6794                 return options;
6795             switch (tscWatchFile) {
6796                 case "PriorityPollingInterval":
6797                     // Use polling interval based on priority when create watch using host.watchFile
6798                     return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
6799                 case "DynamicPriorityPolling":
6800                     // Use polling interval but change the interval depending on file changes and their default polling interval
6801                     return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
6802                 case "UseFsEvents":
6803                     // Use notifications from FS to watch with falling back to fs.watchFile
6804                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
6805                 case "UseFsEventsWithFallbackDynamicPolling":
6806                     // Use notifications from FS to watch with falling back to dynamic watch file
6807                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
6808                 case "UseFsEventsOnParentDirectory":
6809                     useNonPollingWatchers = true;
6810                 // fall through
6811                 default:
6812                     return useNonPollingWatchers ?
6813                         // Use notifications from FS to watch with falling back to fs.watchFile
6814                         generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
6815                         // Default to do not use fixed polling interval
6816                         { watchFile: ts.WatchFileKind.FixedPollingInterval };
6817             }
6818         }
6819         function generateWatchFileOptions(watchFile, fallbackPolling, options) {
6820             var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
6821             return {
6822                 watchFile: watchFile,
6823                 fallbackPolling: defaultFallbackPolling === undefined ?
6824                     fallbackPolling :
6825                     defaultFallbackPolling
6826             };
6827         }
6828         function watchDirectory(directoryName, callback, recursive, options) {
6829             if (fsSupportsRecursiveFsWatch) {
6830                 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
6831             }
6832             if (!hostRecursiveDirectoryWatcher) {
6833                 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
6834                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
6835                     directoryExists: directoryExists,
6836                     getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
6837                     watchDirectory: nonRecursiveWatchDirectory,
6838                     realpath: realpath,
6839                     setTimeout: setTimeout,
6840                     clearTimeout: clearTimeout
6841                 });
6842             }
6843             return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
6844         }
6845         function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
6846             ts.Debug.assert(!recursive);
6847             options = updateOptionsForWatchDirectory(options);
6848             var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
6849             switch (watchDirectoryKind) {
6850                 case ts.WatchDirectoryKind.FixedPollingInterval:
6851                     return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
6852                     /*options*/ undefined);
6853                 case ts.WatchDirectoryKind.DynamicPriorityPolling:
6854                     return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
6855                     /*options*/ undefined);
6856                 case ts.WatchDirectoryKind.UseFsEvents:
6857                     return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
6858                 default:
6859                     ts.Debug.assertNever(watchDirectoryKind);
6860             }
6861         }
6862         function updateOptionsForWatchDirectory(options) {
6863             if (options && options.watchDirectory !== undefined)
6864                 return options;
6865             switch (tscWatchDirectory) {
6866                 case "RecursiveDirectoryUsingFsWatchFile":
6867                     // Use polling interval based on priority when create watch using host.watchFile
6868                     return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
6869                 case "RecursiveDirectoryUsingDynamicPriorityPolling":
6870                     // Use polling interval but change the interval depending on file changes and their default polling interval
6871                     return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
6872                 default:
6873                     var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
6874                     return {
6875                         watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
6876                         fallbackPolling: defaultFallbackPolling !== undefined ?
6877                             defaultFallbackPolling :
6878                             undefined
6879                     };
6880             }
6881         }
6882     }
6883     ts.createSystemWatchFunctions = createSystemWatchFunctions;
6884     /**
6885      * patch writefile to create folder before writing the file
6886      */
6887     /*@internal*/
6888     function patchWriteFileEnsuringDirectory(sys) {
6889         // patch writefile to create folder before writing the file
6890         var originalWriteFile = sys.writeFile;
6891         sys.writeFile = function (path, data, writeBom) {
6892             return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); });
6893         };
6894     }
6895     ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
6896     function getNodeMajorVersion() {
6897         if (typeof process === "undefined") {
6898             return undefined;
6899         }
6900         var version = process.version;
6901         if (!version) {
6902             return undefined;
6903         }
6904         var dot = version.indexOf(".");
6905         if (dot === -1) {
6906             return undefined;
6907         }
6908         return parseInt(version.substring(1, dot));
6909     }
6910     ts.getNodeMajorVersion = getNodeMajorVersion;
6911     // TODO: GH#18217 this is used as if it's certainly defined in many places.
6912     // eslint-disable-next-line prefer-const
6913     ts.sys = (function () {
6914         // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
6915         // byte order mark from the specified encoding. Using any other byte order mark does
6916         // not actually work.
6917         var byteOrderMarkIndicator = "\uFEFF";
6918         function getNodeSystem() {
6919             var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
6920             var _fs = require("fs");
6921             var _path = require("path");
6922             var _os = require("os");
6923             // crypto can be absent on reduced node installations
6924             var _crypto;
6925             try {
6926                 _crypto = require("crypto");
6927             }
6928             catch (_a) {
6929                 _crypto = undefined;
6930             }
6931             var activeSession;
6932             var profilePath = "./profile.cpuprofile";
6933             var Buffer = require("buffer").Buffer;
6934             var nodeVersion = getNodeMajorVersion();
6935             var isNode4OrLater = nodeVersion >= 4;
6936             var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
6937             var platform = _os.platform();
6938             var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
6939             var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
6940             var _b = createSystemWatchFunctions({
6941                 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
6942                 getModifiedTime: getModifiedTime,
6943                 setTimeout: setTimeout,
6944                 clearTimeout: clearTimeout,
6945                 fsWatch: fsWatch,
6946                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
6947                 fileExists: fileExists,
6948                 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
6949                 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
6950                 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
6951                 directoryExists: directoryExists,
6952                 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
6953                 realpath: realpath,
6954                 tscWatchFile: process.env.TSC_WATCHFILE,
6955                 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
6956                 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
6957             }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
6958             var nodeSystem = {
6959                 args: process.argv.slice(2),
6960                 newLine: _os.EOL,
6961                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
6962                 write: function (s) {
6963                     process.stdout.write(s);
6964                 },
6965                 writeOutputIsTTY: function () {
6966                     return process.stdout.isTTY;
6967                 },
6968                 readFile: readFile,
6969                 writeFile: writeFile,
6970                 watchFile: watchFile,
6971                 watchDirectory: watchDirectory,
6972                 resolvePath: function (path) { return _path.resolve(path); },
6973                 fileExists: fileExists,
6974                 directoryExists: directoryExists,
6975                 createDirectory: function (directoryName) {
6976                     if (!nodeSystem.directoryExists(directoryName)) {
6977                         // Wrapped in a try-catch to prevent crashing if we are in a race
6978                         // with another copy of ourselves to create the same directory
6979                         try {
6980                             _fs.mkdirSync(directoryName);
6981                         }
6982                         catch (e) {
6983                             if (e.code !== "EEXIST") {
6984                                 // Failed for some other reason (access denied?); still throw
6985                                 throw e;
6986                             }
6987                         }
6988                     }
6989                 },
6990                 getExecutingFilePath: function () {
6991                     return __filename;
6992                 },
6993                 getCurrentDirectory: function () {
6994                     return process.cwd();
6995                 },
6996                 getDirectories: getDirectories,
6997                 getEnvironmentVariable: function (name) {
6998                     return process.env[name] || "";
6999                 },
7000                 readDirectory: readDirectory,
7001                 getModifiedTime: getModifiedTime,
7002                 setModifiedTime: setModifiedTime,
7003                 deleteFile: deleteFile,
7004                 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
7005                 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
7006                 getMemoryUsage: function () {
7007                     if (global.gc) {
7008                         global.gc();
7009                     }
7010                     return process.memoryUsage().heapUsed;
7011                 },
7012                 getFileSize: function (path) {
7013                     try {
7014                         var stat = _fs.statSync(path);
7015                         if (stat.isFile()) {
7016                             return stat.size;
7017                         }
7018                     }
7019                     catch ( /*ignore*/_a) { /*ignore*/ }
7020                     return 0;
7021                 },
7022                 exit: function (exitCode) {
7023                     disableCPUProfiler(function () { return process.exit(exitCode); });
7024                 },
7025                 enableCPUProfiler: enableCPUProfiler,
7026                 disableCPUProfiler: disableCPUProfiler,
7027                 realpath: realpath,
7028                 debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
7029                 tryEnableSourceMapsForHost: function () {
7030                     try {
7031                         require("source-map-support").install();
7032                     }
7033                     catch (_a) {
7034                         // Could not enable source maps.
7035                     }
7036                 },
7037                 setTimeout: setTimeout,
7038                 clearTimeout: clearTimeout,
7039                 clearScreen: function () {
7040                     process.stdout.write("\x1Bc");
7041                 },
7042                 setBlocking: function () {
7043                     if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
7044                         process.stdout._handle.setBlocking(true);
7045                     }
7046                 },
7047                 bufferFrom: bufferFrom,
7048                 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
7049                 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
7050                 require: function (baseDir, moduleName) {
7051                     try {
7052                         var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
7053                         return { module: require(modulePath), modulePath: modulePath, error: undefined };
7054                     }
7055                     catch (error) {
7056                         return { module: undefined, modulePath: undefined, error: error };
7057                     }
7058                 }
7059             };
7060             return nodeSystem;
7061             /**
7062              * Uses the builtin inspector APIs to capture a CPU profile
7063              * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
7064              */
7065             function enableCPUProfiler(path, cb) {
7066                 if (activeSession) {
7067                     cb();
7068                     return false;
7069                 }
7070                 var inspector = require("inspector");
7071                 if (!inspector || !inspector.Session) {
7072                     cb();
7073                     return false;
7074                 }
7075                 var session = new inspector.Session();
7076                 session.connect();
7077                 session.post("Profiler.enable", function () {
7078                     session.post("Profiler.start", function () {
7079                         activeSession = session;
7080                         profilePath = path;
7081                         cb();
7082                     });
7083                 });
7084                 return true;
7085             }
7086             /**
7087              * Strips non-TS paths from the profile, so users with private projects shouldn't
7088              * need to worry about leaking paths by submitting a cpu profile to us
7089              */
7090             function cleanupPaths(profile) {
7091                 var externalFileCounter = 0;
7092                 var remappedPaths = new ts.Map();
7093                 var normalizedDir = ts.normalizeSlashes(__dirname);
7094                 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
7095                 var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
7096                 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
7097                     var node = _a[_i];
7098                     if (node.callFrame.url) {
7099                         var url = ts.normalizeSlashes(node.callFrame.url);
7100                         if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
7101                             node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
7102                         }
7103                         else if (!nativePattern.test(url)) {
7104                             node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
7105                             externalFileCounter++;
7106                         }
7107                     }
7108                 }
7109                 return profile;
7110             }
7111             function disableCPUProfiler(cb) {
7112                 if (activeSession && activeSession !== "stopping") {
7113                     var s_1 = activeSession;
7114                     activeSession.post("Profiler.stop", function (err, _a) {
7115                         var profile = _a.profile;
7116                         if (!err) {
7117                             try {
7118                                 if (_fs.statSync(profilePath).isDirectory()) {
7119                                     profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
7120                                 }
7121                             }
7122                             catch (_b) {
7123                                 // do nothing and ignore fallible fs operation
7124                             }
7125                             try {
7126                                 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
7127                             }
7128                             catch (_c) {
7129                                 // do nothing and ignore fallible fs operation
7130                             }
7131                             _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
7132                         }
7133                         activeSession = undefined;
7134                         s_1.disconnect();
7135                         cb();
7136                     });
7137                     activeSession = "stopping";
7138                     return true;
7139                 }
7140                 else {
7141                     cb();
7142                     return false;
7143                 }
7144             }
7145             function bufferFrom(input, encoding) {
7146                 // See https://github.com/Microsoft/TypeScript/issues/25652
7147                 return Buffer.from && Buffer.from !== Int8Array.from
7148                     ? Buffer.from(input, encoding)
7149                     : new Buffer(input, encoding);
7150             }
7151             function isFileSystemCaseSensitive() {
7152                 // win32\win64 are case insensitive platforms
7153                 if (platform === "win32" || platform === "win64") {
7154                     return false;
7155                 }
7156                 // If this file exists under a different case, we must be case-insensitve.
7157                 return !fileExists(swapCase(__filename));
7158             }
7159             /** Convert all lowercase chars to uppercase, and vice-versa */
7160             function swapCase(s) {
7161                 return s.replace(/\w/g, function (ch) {
7162                     var up = ch.toUpperCase();
7163                     return ch === up ? ch.toLowerCase() : up;
7164                 });
7165             }
7166             function fsWatchFileWorker(fileName, callback, pollingInterval) {
7167                 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
7168                 var eventKind;
7169                 return {
7170                     close: function () { return _fs.unwatchFile(fileName, fileChanged); }
7171                 };
7172                 function fileChanged(curr, prev) {
7173                     // 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)
7174                     // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
7175                     var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
7176                     if (+curr.mtime === 0) {
7177                         if (isPreviouslyDeleted) {
7178                             // Already deleted file, no need to callback again
7179                             return;
7180                         }
7181                         eventKind = FileWatcherEventKind.Deleted;
7182                     }
7183                     else if (isPreviouslyDeleted) {
7184                         eventKind = FileWatcherEventKind.Created;
7185                     }
7186                     // If there is no change in modified time, ignore the event
7187                     else if (+curr.mtime === +prev.mtime) {
7188                         return;
7189                     }
7190                     else {
7191                         // File changed
7192                         eventKind = FileWatcherEventKind.Changed;
7193                     }
7194                     callback(fileName, eventKind);
7195                 }
7196             }
7197             function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
7198                 var options;
7199                 var lastDirectoryPartWithDirectorySeparator;
7200                 var lastDirectoryPart;
7201                 if (isLinuxOrMacOs) {
7202                     lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
7203                     lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
7204                 }
7205                 /** Watcher for the file system entry depending on whether it is missing or present */
7206                 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
7207                     watchMissingFileSystemEntry() :
7208                     watchPresentFileSystemEntry();
7209                 return {
7210                     close: function () {
7211                         // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
7212                         watcher.close();
7213                         watcher = undefined;
7214                     }
7215                 };
7216                 /**
7217                  * Invoke the callback with rename and update the watcher if not closed
7218                  * @param createWatcher
7219                  */
7220                 function invokeCallbackAndUpdateWatcher(createWatcher) {
7221                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
7222                     // Call the callback for current directory
7223                     callback("rename", "");
7224                     // If watcher is not closed, update it
7225                     if (watcher) {
7226                         watcher.close();
7227                         watcher = createWatcher();
7228                     }
7229                 }
7230                 /**
7231                  * Watch the file or directory that is currently present
7232                  * and when the watched file or directory is deleted, switch to missing file system entry watcher
7233                  */
7234                 function watchPresentFileSystemEntry() {
7235                     // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
7236                     // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
7237                     if (options === undefined) {
7238                         if (fsSupportsRecursiveFsWatch) {
7239                             options = { persistent: true, recursive: !!recursive };
7240                         }
7241                         else {
7242                             options = { persistent: true };
7243                         }
7244                     }
7245                     try {
7246                         var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
7247                             callbackChangingToMissingFileSystemEntry :
7248                             callback);
7249                         // Watch the missing file or directory or error
7250                         presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
7251                         return presentWatcher;
7252                     }
7253                     catch (e) {
7254                         // Catch the exception and use polling instead
7255                         // 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
7256                         // so instead of throwing error, use fs.watchFile
7257                         return watchPresentFileSystemEntryWithFsWatchFile();
7258                     }
7259                 }
7260                 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
7261                     // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
7262                     // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
7263                     return event === "rename" &&
7264                         (!relativeName ||
7265                             relativeName === lastDirectoryPart ||
7266                             relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
7267                         !fileSystemEntryExists(fileOrDirectory, entryKind) ?
7268                         invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
7269                         callback(event, relativeName);
7270                 }
7271                 /**
7272                  * Watch the file or directory using fs.watchFile since fs.watch threw exception
7273                  * 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
7274                  */
7275                 function watchPresentFileSystemEntryWithFsWatchFile() {
7276                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
7277                     return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
7278                 }
7279                 /**
7280                  * Watch the file or directory that is missing
7281                  * and switch to existing file or directory when the missing filesystem entry is created
7282                  */
7283                 function watchMissingFileSystemEntry() {
7284                     return watchFile(fileOrDirectory, function (_fileName, eventKind) {
7285                         if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
7286                             // Call the callback for current file or directory
7287                             // For now it could be callback for the inner directory creation,
7288                             // but just return current directory, better than current no-op
7289                             invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
7290                         }
7291                     }, fallbackPollingInterval, fallbackOptions);
7292                 }
7293             }
7294             function readFileWorker(fileName, _encoding) {
7295                 var buffer;
7296                 try {
7297                     buffer = _fs.readFileSync(fileName);
7298                 }
7299                 catch (e) {
7300                     return undefined;
7301                 }
7302                 var len = buffer.length;
7303                 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
7304                     // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
7305                     // flip all byte pairs and treat as little endian.
7306                     len &= ~1; // Round down to a multiple of 2
7307                     for (var i = 0; i < len; i += 2) {
7308                         var temp = buffer[i];
7309                         buffer[i] = buffer[i + 1];
7310                         buffer[i + 1] = temp;
7311                     }
7312                     return buffer.toString("utf16le", 2);
7313                 }
7314                 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
7315                     // Little endian UTF-16 byte order mark detected
7316                     return buffer.toString("utf16le", 2);
7317                 }
7318                 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
7319                     // UTF-8 byte order mark detected
7320                     return buffer.toString("utf8", 3);
7321                 }
7322                 // Default is UTF-8 with no byte order mark
7323                 return buffer.toString("utf8");
7324             }
7325             function readFile(fileName, _encoding) {
7326                 ts.perfLogger.logStartReadFile(fileName);
7327                 var file = readFileWorker(fileName, _encoding);
7328                 ts.perfLogger.logStopReadFile();
7329                 return file;
7330             }
7331             function writeFile(fileName, data, writeByteOrderMark) {
7332                 ts.perfLogger.logEvent("WriteFile: " + fileName);
7333                 // If a BOM is required, emit one
7334                 if (writeByteOrderMark) {
7335                     data = byteOrderMarkIndicator + data;
7336                 }
7337                 var fd;
7338                 try {
7339                     fd = _fs.openSync(fileName, "w");
7340                     _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
7341                 }
7342                 finally {
7343                     if (fd !== undefined) {
7344                         _fs.closeSync(fd);
7345                     }
7346                 }
7347             }
7348             function getAccessibleFileSystemEntries(path) {
7349                 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
7350                 try {
7351                     var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
7352                     var files = [];
7353                     var directories = [];
7354                     for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
7355                         var dirent = entries_1[_i];
7356                         // withFileTypes is not supported before Node 10.10.
7357                         var entry = typeof dirent === "string" ? dirent : dirent.name;
7358                         // This is necessary because on some file system node fails to exclude
7359                         // "." and "..". See https://github.com/nodejs/node/issues/4002
7360                         if (entry === "." || entry === "..") {
7361                             continue;
7362                         }
7363                         var stat = void 0;
7364                         if (typeof dirent === "string" || dirent.isSymbolicLink()) {
7365                             var name = ts.combinePaths(path, entry);
7366                             try {
7367                                 stat = _fs.statSync(name);
7368                             }
7369                             catch (e) {
7370                                 continue;
7371                             }
7372                         }
7373                         else {
7374                             stat = dirent;
7375                         }
7376                         if (stat.isFile()) {
7377                             files.push(entry);
7378                         }
7379                         else if (stat.isDirectory()) {
7380                             directories.push(entry);
7381                         }
7382                     }
7383                     files.sort();
7384                     directories.sort();
7385                     return { files: files, directories: directories };
7386                 }
7387                 catch (e) {
7388                     return ts.emptyFileSystemEntries;
7389                 }
7390             }
7391             function readDirectory(path, extensions, excludes, includes, depth) {
7392                 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
7393             }
7394             function fileSystemEntryExists(path, entryKind) {
7395                 // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve
7396                 // the CPU time performance.
7397                 var originalStackTraceLimit = Error.stackTraceLimit;
7398                 Error.stackTraceLimit = 0;
7399                 try {
7400                     var stat = _fs.statSync(path);
7401                     switch (entryKind) {
7402                         case 0 /* File */: return stat.isFile();
7403                         case 1 /* Directory */: return stat.isDirectory();
7404                         default: return false;
7405                     }
7406                 }
7407                 catch (e) {
7408                     return false;
7409                 }
7410                 finally {
7411                     Error.stackTraceLimit = originalStackTraceLimit;
7412                 }
7413             }
7414             function fileExists(path) {
7415                 return fileSystemEntryExists(path, 0 /* File */);
7416             }
7417             function directoryExists(path) {
7418                 return fileSystemEntryExists(path, 1 /* Directory */);
7419             }
7420             function getDirectories(path) {
7421                 return getAccessibleFileSystemEntries(path).directories.slice();
7422             }
7423             function realpath(path) {
7424                 try {
7425                     return _fs.realpathSync(path);
7426                 }
7427                 catch (_a) {
7428                     return path;
7429                 }
7430             }
7431             function getModifiedTime(path) {
7432                 try {
7433                     return _fs.statSync(path).mtime;
7434                 }
7435                 catch (e) {
7436                     return undefined;
7437                 }
7438             }
7439             function setModifiedTime(path, time) {
7440                 try {
7441                     _fs.utimesSync(path, time, time);
7442                 }
7443                 catch (e) {
7444                     return;
7445                 }
7446             }
7447             function deleteFile(path) {
7448                 try {
7449                     return _fs.unlinkSync(path);
7450                 }
7451                 catch (e) {
7452                     return;
7453                 }
7454             }
7455             function createSHA256Hash(data) {
7456                 var hash = _crypto.createHash("sha256");
7457                 hash.update(data);
7458                 return hash.digest("hex");
7459             }
7460         }
7461         var sys;
7462         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
7463             // process and process.nextTick checks if current environment is node-like
7464             // process.browser check excludes webpack and browserify
7465             sys = getNodeSystem();
7466         }
7467         if (sys) {
7468             // patch writefile to create folder before writing the file
7469             patchWriteFileEnsuringDirectory(sys);
7470         }
7471         return sys;
7472     })();
7473     if (ts.sys && ts.sys.getEnvironmentVariable) {
7474         setCustomPollingValues(ts.sys);
7475         ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
7476             ? 1 /* Normal */
7477             : 0 /* None */);
7478     }
7479     if (ts.sys && ts.sys.debugMode) {
7480         ts.Debug.isDebugging = true;
7481     }
7482 })(ts || (ts = {}));
7483 // <auto-generated />
7484 // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
7485 /* @internal */
7486 var ts;
7487 (function (ts) {
7488     function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated) {
7489         return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid, reportsDeprecated: reportsDeprecated };
7490     }
7491     ts.Diagnostics = {
7492         Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
7493         Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
7494         _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
7495         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."),
7496         The_parser_expected_to_find_a_to_match_the_token_here: diag(1007, ts.DiagnosticCategory.Error, "The_parser_expected_to_find_a_to_match_the_token_here_1007", "The parser expected to find a '}' to match the '{' token here."),
7497         Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
7498         Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
7499         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."),
7500         Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
7501         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."),
7502         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."),
7503         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."),
7504         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."),
7505         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."),
7506         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."),
7507         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."),
7508         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."),
7509         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."),
7510         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."),
7511         An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."),
7512         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."),
7513         An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."),
7514         Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
7515         _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
7516         _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
7517         _0_modifier_cannot_appear_on_class_elements_of_this_kind: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031", "'{0}' modifier cannot appear on class elements of this kind."),
7518         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."),
7519         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."),
7520         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."),
7521         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."),
7522         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."),
7523         _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."),
7524         _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."),
7525         _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
7526         _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."),
7527         _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."),
7528         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."),
7529         Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier: diag(1046, ts.DiagnosticCategory.Error, "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046", "Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier."),
7530         A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
7531         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."),
7532         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."),
7533         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."),
7534         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."),
7535         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."),
7536         A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
7537         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."),
7538         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."),
7539         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."),
7540         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."),
7541         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."),
7542         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."),
7543         Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
7544         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."),
7545         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."),
7546         The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<{0}>'?"),
7547         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."),
7548         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."),
7549         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."),
7550         _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."),
7551         _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."),
7552         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."),
7553         Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
7554         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}'."),
7555         _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."),
7556         _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."),
7557         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."),
7558         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."),
7559         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."),
7560         An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
7561         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."),
7562         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."),
7563         _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
7564         Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
7565         Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
7566         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."),
7567         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."),
7568         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."),
7569         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."),
7570         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."),
7571         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."),
7572         Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
7573         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."),
7574         Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
7575         Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
7576         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."),
7577         Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
7578         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."),
7579         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."),
7580         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."),
7581         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."),
7582         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."),
7583         An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
7584         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."),
7585         Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
7586         Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
7587         Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
7588         Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
7589         Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
7590         Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
7591         Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
7592         case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
7593         Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
7594         Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
7595         Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
7596         Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
7597         Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
7598         Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
7599         Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
7600         Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
7601         Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
7602         String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
7603         Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
7604         or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
7605         Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
7606         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."),
7607         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'."),
7608         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."),
7609         const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
7610         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."),
7611         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."),
7612         Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
7613         Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
7614         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."),
7615         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."),
7616         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."),
7617         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."),
7618         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."),
7619         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."),
7620         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."),
7621         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."),
7622         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."),
7623         extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
7624         extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
7625         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."),
7626         implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
7627         Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
7628         Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
7629         Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
7630         Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
7631         Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
7632         Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
7633         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."),
7634         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."),
7635         Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
7636         Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
7637         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."),
7638         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."),
7639         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."),
7640         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."),
7641         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."),
7642         An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
7643         Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
7644         An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
7645         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."),
7646         export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."),
7647         Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196", "Catch clause variable type annotation must be 'any' or 'unknown' if specified."),
7648         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."),
7649         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."),
7650         Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
7651         Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
7652         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."),
7653         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."),
7654         Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type: diag(1205, ts.DiagnosticCategory.Error, "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205", "Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'."),
7655         Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
7656         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."),
7657         _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."),
7658         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."),
7659         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."),
7660         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."),
7661         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."),
7662         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."),
7663         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."),
7664         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."),
7665         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'."),
7666         Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_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 in your 'tsconfig' or 'jsconfig' to remove this warning."),
7667         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."),
7668         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."),
7669         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."),
7670         _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
7671         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."),
7672         Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
7673         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}'."),
7674         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}'."),
7675         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."),
7676         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."),
7677         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."),
7678         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."),
7679         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."),
7680         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."),
7681         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."),
7682         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."),
7683         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'."),
7684         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'."),
7685         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."),
7686         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."),
7687         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."),
7688         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."),
7689         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."),
7690         _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."),
7691         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."),
7692         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."),
7693         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."),
7694         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."),
7695         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."),
7696         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."),
7697         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'."),
7698         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."),
7699         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."),
7700         _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."),
7701         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."),
7702         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."),
7703         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."),
7704         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."),
7705         Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"),
7706         Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
7707         Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."),
7708         Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module: diag(1262, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262", "Identifier expected. '{0}' is a reserved word at the top-level of a module."),
7709         Declarations_with_initializers_cannot_also_have_definite_assignment_assertions: diag(1263, ts.DiagnosticCategory.Error, "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263", "Declarations with initializers cannot also have definite assignment assertions."),
7710         Declarations_with_definite_assignment_assertions_must_also_have_type_annotations: diag(1264, ts.DiagnosticCategory.Error, "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264", "Declarations with definite assignment assertions must also have type annotations."),
7711         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."),
7712         await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."),
7713         Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern: diag(1312, ts.DiagnosticCategory.Error, "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312", "Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern."),
7714         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."),
7715         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."),
7716         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."),
7717         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."),
7718         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."),
7719         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."),
7720         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."),
7721         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."),
7722         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."),
7723         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."),
7724         Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'."),
7725         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."),
7726         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."),
7727         Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments."),
7728         String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
7729         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."),
7730         _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}()'?"),
7731         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'."),
7732         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'."),
7733         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'."),
7734         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."),
7735         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."),
7736         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."),
7737         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."),
7738         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."),
7739         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."),
7740         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."),
7741         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}')'?"),
7742         Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
7743         The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'."),
7744         A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
7745         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."),
7746         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."),
7747         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."),
7748         Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
7749         use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
7750         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."),
7751         An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
7752         A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
7753         A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
7754         readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
7755         A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355", "A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals."),
7756         Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"),
7757         An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."),
7758         Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."),
7759         Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."),
7760         Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"),
7761         _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."),
7762         _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."),
7763         A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."),
7764         Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
7765         Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"),
7766         Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
7767         Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
7768         Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"),
7769         Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
7770         Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."),
7771         This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error: diag(1371, ts.DiagnosticCategory.Error, "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371", "This import is never used as a value and must use 'import type' because the 'importsNotUsedAsValues' is set to 'error'."),
7772         Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
7773         Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"),
7774         await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."),
7775         _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
7776         _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
7777         Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1378, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1378", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."),
7778         An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type: diag(1379, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379", "An import alias cannot reference a declaration that was exported using 'export type'."),
7779         An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type: diag(1380, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380", "An import alias cannot reference a declaration that was imported using 'import type'."),
7780         Unexpected_token_Did_you_mean_or_rbrace: diag(1381, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_rbrace_1381", "Unexpected token. Did you mean `{'}'}` or `&rbrace;`?"),
7781         Unexpected_token_Did_you_mean_or_gt: diag(1382, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_gt_1382", "Unexpected token. Did you mean `{'>'}` or `&gt;`?"),
7782         Only_named_exports_may_use_export_type: diag(1383, ts.DiagnosticCategory.Error, "Only_named_exports_may_use_export_type_1383", "Only named exports may use 'export type'."),
7783         A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list: diag(1384, ts.DiagnosticCategory.Error, "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384", "A 'new' expression with type arguments must always be followed by a parenthesized argument list."),
7784         Function_type_notation_must_be_parenthesized_when_used_in_a_union_type: diag(1385, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385", "Function type notation must be parenthesized when used in a union type."),
7785         Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type: diag(1386, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386", "Constructor type notation must be parenthesized when used in a union type."),
7786         Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."),
7787         Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."),
7788         _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."),
7789         The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."),
7790         The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."),
7791         Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
7792         Construct_signature_return_types_0_and_1_are_incompatible: diag(2203, ts.DiagnosticCategory.Error, "Construct_signature_return_types_0_and_1_are_incompatible_2203", "Construct signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
7793         Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2204, ts.DiagnosticCategory.Error, "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204", "Call signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
7794         Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
7795         Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
7796         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."),
7797         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."),
7798         Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
7799         Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
7800         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}'."),
7801         File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
7802         Cannot_find_module_0_or_its_corresponding_type_declarations: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_or_its_corresponding_type_declarations_2307", "Cannot find module '{0}' or its corresponding type declarations."),
7803         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."),
7804         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."),
7805         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."),
7806         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."),
7807         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."),
7808         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."),
7809         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)."),
7810         Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
7811         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."),
7812         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)."),
7813         Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
7814         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."),
7815         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}'."),
7816         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}'."),
7817         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}'."),
7818         Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
7819         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}'."),
7820         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}'."),
7821         Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
7822         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}'."),
7823         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."),
7824         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}'."),
7825         Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
7826         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."),
7827         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."),
7828         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."),
7829         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."),
7830         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."),
7831         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."),
7832         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."),
7833         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."),
7834         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}'."),
7835         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."),
7836         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}'."),
7837         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'."),
7838         This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343", "This syntax requires an imported helper named '{1}' which does not exist in '{0}'. Consider upgrading your version of '{0}'."),
7839         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}'."),
7840         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}'."),
7841         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."),
7842         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."),
7843         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'?"),
7844         This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
7845         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."),
7846         This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
7847         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."),
7848         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}'."),
7849         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."),
7850         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."),
7851         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."),
7852         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."),
7853         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."),
7854         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."),
7855         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'."),
7856         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."),
7857         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."),
7858         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."),
7859         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."),
7860         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}'."),
7861         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'."),
7862         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."),
7863         Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
7864         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."),
7865         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."),
7866         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."),
7867         Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
7868         Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."),
7869         Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
7870         Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
7871         A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: 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, parameter properties, or private identifiers."),
7872         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."),
7873         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."),
7874         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."),
7875         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."),
7876         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."),
7877         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."),
7878         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."),
7879         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."),
7880         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."),
7881         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."),
7882         Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
7883         Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
7884         Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
7885         Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
7886         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."),
7887         Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
7888         Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
7889         This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
7890         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."),
7891         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."),
7892         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}'."),
7893         constructor_cannot_be_used_as_a_parameter_property_name: diag(2398, ts.DiagnosticCategory.Error, "constructor_cannot_be_used_as_a_parameter_property_name_2398", "'constructor' cannot be used as a parameter property name."),
7894         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."),
7895         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."),
7896         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."),
7897         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."),
7898         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}'."),
7899         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."),
7900         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'."),
7901         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."),
7902         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}'."),
7903         Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
7904         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."),
7905         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'."),
7906         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}'."),
7907         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}'."),
7908         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}'."),
7909         Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
7910         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}'."),
7911         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}'."),
7912         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}'."),
7913         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}'."),
7914         Types_of_construct_signatures_are_incompatible: diag(2419, ts.DiagnosticCategory.Error, "Types_of_construct_signatures_are_incompatible_2419", "Types of construct signatures are incompatible."),
7915         Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
7916         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."),
7917         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."),
7918         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."),
7919         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."),
7920         Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
7921         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."),
7922         Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
7923         Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
7924         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."),
7925         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."),
7926         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."),
7927         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."),
7928         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."),
7929         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."),
7930         Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
7931         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."),
7932         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}'."),
7933         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."),
7934         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}'."),
7935         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}'."),
7936         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}'."),
7937         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."),
7938         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}'."),
7939         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."),
7940         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."),
7941         Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
7942         Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
7943         Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
7944         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."),
7945         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."),
7946         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."),
7947         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}'."),
7948         Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
7949         Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
7950         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."),
7951         Module_0_declares_1_locally_but_it_is_not_exported: diag(2459, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_not_exported_2459", "Module '{0}' declares '{1}' locally, but it is not exported."),
7952         Module_0_declares_1_locally_but_it_is_exported_as_2: diag(2460, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_exported_as_2_2460", "Module '{0}' declares '{1}' locally, but it is exported as '{2}'."),
7953         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."),
7954         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."),
7955         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."),
7956         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'."),
7957         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."),
7958         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."),
7959         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."),
7960         Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
7961         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'."),
7962         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."),
7963         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'."),
7964         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."),
7965         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."),
7966         const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."),
7967         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."),
7968         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."),
7969         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."),
7970         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'."),
7971         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}'."),
7972         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."),
7973         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}'."),
7974         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."),
7975         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}'."),
7976         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."),
7977         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."),
7978         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."),
7979         The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the '{0}()' method of an iterator must have a 'value' property."),
7980         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."),
7981         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."),
7982         Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."),
7983         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."),
7984         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."),
7985         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."),
7986         This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."),
7987         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 *'."),
7988         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."),
7989         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."),
7990         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."),
7991         _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."),
7992         Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
7993         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."),
7994         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."),
7995         _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."),
7996         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."),
7997         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."),
7998         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."),
7999         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."),
8000         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."),
8001         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."),
8002         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."),
8003         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."),
8004         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}'."),
8005         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."),
8006         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."),
8007         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."),
8008         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."),
8009         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."),
8010         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."),
8011         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."),
8012         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."),
8013         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."),
8014         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."),
8015         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."),
8016         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."),
8017         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."),
8018         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."),
8019         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."),
8020         Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
8021         Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
8022         Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
8023         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."),
8024         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."),
8025         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}'."),
8026         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}'."),
8027         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."),
8028         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."),
8029         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."),
8030         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."),
8031         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."),
8032         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."),
8033         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."),
8034         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[]'."),
8035         The_type_returned_by_the_0_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_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."),
8036         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."),
8037         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."),
8038         Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."),
8039         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}'?"),
8040         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}'?"),
8041         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."),
8042         Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
8043         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}."),
8044         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."),
8045         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."),
8046         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}."),
8047         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}'."),
8048         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?"),
8049         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}'?"),
8050         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."),
8051         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."),
8052         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."),
8053         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."),
8054         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."),
8055         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."),
8056         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."),
8057         Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
8058         Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
8059         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."),
8060         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."),
8061         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."),
8062         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}'."),
8063         Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
8064         Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
8065         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."),
8066         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."),
8067         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."),
8068         Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_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 '{1}' or later."),
8069         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'."),
8070         _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."),
8071         Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
8072         JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
8073         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."),
8074         Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
8075         Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
8076         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."),
8077         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."),
8078         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
8079         This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."),
8080         _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."),
8081         _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."),
8082         _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."),
8083         _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."),
8084         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."),
8085         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."),
8086         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."),
8087         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}'."),
8088         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."),
8089         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."),
8090         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."),
8091         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."),
8092         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."),
8093         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."),
8094         _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."),
8095         _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."),
8096         Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."),
8097         Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"),
8098         Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"),
8099         Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."),
8100         _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."),
8101         _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."),
8102         Source_has_0_element_s_but_target_requires_1: diag(2618, ts.DiagnosticCategory.Error, "Source_has_0_element_s_but_target_requires_1_2618", "Source has {0} element(s) but target requires {1}."),
8103         Source_has_0_element_s_but_target_allows_only_1: diag(2619, ts.DiagnosticCategory.Error, "Source_has_0_element_s_but_target_allows_only_1_2619", "Source has {0} element(s) but target allows only {1}."),
8104         Target_requires_0_element_s_but_source_may_have_fewer: diag(2620, ts.DiagnosticCategory.Error, "Target_requires_0_element_s_but_source_may_have_fewer_2620", "Target requires {0} element(s) but source may have fewer."),
8105         Target_allows_only_0_element_s_but_source_may_have_more: diag(2621, ts.DiagnosticCategory.Error, "Target_allows_only_0_element_s_but_source_may_have_more_2621", "Target allows only {0} element(s) but source may have more."),
8106         Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other: diag(2622, ts.DiagnosticCategory.Error, "Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other_2622", "Element at index {0} is variadic in one type but not in the other."),
8107         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."),
8108         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."),
8109         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."),
8110         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}'."),
8111         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."),
8112         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."),
8113         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."),
8114         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}'."),
8115         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."),
8116         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."),
8117         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."),
8118         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}'?"),
8119         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}'?"),
8120         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."),
8121         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."),
8122         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."),
8123         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."),
8124         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."),
8125         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."),
8126         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."),
8127         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."),
8128         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."),
8129         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."),
8130         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."),
8131         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."),
8132         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."),
8133         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."),
8134         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}'."),
8135         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'."),
8136         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."),
8137         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."),
8138         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."),
8139         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."),
8140         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}'."),
8141         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."),
8142         _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."),
8143         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."),
8144         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}'."),
8145         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'?"),
8146         _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0: diag(2690, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690", "'{0}' only refers to a type, but is being used as a value here. Did you mean to use '{1} in {0}'?"),
8147         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."),
8148         _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."),
8149         _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."),
8150         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}'."),
8151         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),
8152         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?"),
8153         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."),
8154         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."),
8155         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}'."),
8156         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."),
8157         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."),
8158         _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."),
8159         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."),
8160         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."),
8161         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."),
8162         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."),
8163         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."),
8164         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."),
8165         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."),
8166         _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."),
8167         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."),
8168         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."),
8169         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}\"]'?"),
8170         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."),
8171         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."),
8172         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."),
8173         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}'."),
8174         Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
8175         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."),
8176         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?"),
8177         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'."),
8178         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'."),
8179         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'."),
8180         _0_has_no_exported_member_named_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "_0_has_no_exported_member_named_1_Did_you_mean_2_2724", "'{0}' has no exported member named '{1}'. Did you mean '{2}'?"),
8181         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}."),
8182         Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
8183         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}'?"),
8184         _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
8185         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."),
8186         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."),
8187         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(...)'."),
8188         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."),
8189         Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
8190         Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
8191         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}'?"),
8192         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}'."),
8193         BigInt_literals_are_not_available_when_targeting_lower_than_ES2020: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737", "BigInt literals are not available when targeting lower than ES2020."),
8194         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."),
8195         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}"),
8196         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."),
8197         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}'."),
8198         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."),
8199         No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."),
8200         Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."),
8201         This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
8202         This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
8203         _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
8204         Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
8205         _0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749", "'{0}' refers to a value, but is being used as a type here. Did you mean 'typeof {0}'?"),
8206         The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
8207         Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
8208         The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
8209         Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
8210         super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
8211         No_constituent_of_type_0_is_callable: diag(2755, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_callable_2755", "No constituent of type '{0}' is callable."),
8212         Not_all_constituents_of_type_0_are_callable: diag(2756, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_callable_2756", "Not all constituents of type '{0}' are callable."),
8213         Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
8214         Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2758, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758", "Each member of the union type '{0}' has signatures, but none of those signatures are compatible with each other."),
8215         No_constituent_of_type_0_is_constructable: diag(2759, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_constructable_2759", "No constituent of type '{0}' is constructable."),
8216         Not_all_constituents_of_type_0_are_constructable: diag(2760, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_constructable_2760", "Not all constituents of type '{0}' are constructable."),
8217         Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
8218         Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2762, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762", "Each member of the union type '{0}' has construct signatures, but none of those signatures are compatible with each other."),
8219         Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0: diag(2763, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but for-of will always send '{0}'."),
8220         Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0: diag(2764, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array spread will always send '{0}'."),
8221         Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0: diag(2765, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array destructuring will always send '{0}'."),
8222         Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0: diag(2766, ts.DiagnosticCategory.Error, "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766", "Cannot delegate iteration to value because the 'next' method of its iterator expects type '{1}', but the containing generator will always send '{0}'."),
8223         The_0_property_of_an_iterator_must_be_a_method: diag(2767, ts.DiagnosticCategory.Error, "The_0_property_of_an_iterator_must_be_a_method_2767", "The '{0}' property of an iterator must be a method."),
8224         The_0_property_of_an_async_iterator_must_be_a_method: diag(2768, ts.DiagnosticCategory.Error, "The_0_property_of_an_async_iterator_must_be_a_method_2768", "The '{0}' property of an async iterator must be a method."),
8225         No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
8226         The_last_overload_gave_the_following_error: diag(2770, ts.DiagnosticCategory.Error, "The_last_overload_gave_the_following_error_2770", "The last overload gave the following error."),
8227         The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
8228         Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."),
8229         Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
8230         This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"),
8231         Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."),
8232         Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."),
8233         The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."),
8234         The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access: diag(2778, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778", "The target of an object rest assignment may not be an optional property access."),
8235         The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access: diag(2779, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779", "The left-hand side of an assignment expression may not be an optional property access."),
8236         The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access: diag(2780, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780", "The left-hand side of a 'for...in' statement may not be an optional property access."),
8237         The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access: diag(2781, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781", "The left-hand side of a 'for...of' statement may not be an optional property access."),
8238         _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
8239         _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."),
8240         get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."),
8241         This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
8242         _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."),
8243         Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."),
8244         Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."),
8245         Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."),
8246         The_operand_of_a_delete_operator_must_be_optional: diag(2790, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."),
8247         Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, ts.DiagnosticCategory.Error, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."),
8248         Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option: diag(2792, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_th_2792", "Cannot find module '{0}'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?"),
8249         The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_are_not_externally_visible: diag(2793, ts.DiagnosticCategory.Error, "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793", "The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible."),
8250         Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise: diag(2794, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794", "Expected {0} arguments, but got {1}. Did you forget to include 'void' in your type argument to 'Promise'?"),
8251         The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."),
8252         It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."),
8253         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}'."),
8254         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}'."),
8255         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}'."),
8256         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}'."),
8257         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}'."),
8258         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}'."),
8259         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}'."),
8260         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}'."),
8261         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}'."),
8262         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}'."),
8263         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}'."),
8264         extends_clause_of_exported_class_has_or_is_using_private_name_0: diag(4021, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021", "'extends' clause of exported class has or is using private name '{0}'."),
8265         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}'."),
8266         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."),
8267         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}'."),
8268         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}'."),
8269         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."),
8270         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}'."),
8271         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}'."),
8272         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."),
8273         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}'."),
8274         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}'."),
8275         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}'."),
8276         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}'."),
8277         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}'."),
8278         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}'."),
8279         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}'."),
8280         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}'."),
8281         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."),
8282         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}'."),
8283         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}'."),
8284         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."),
8285         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}'."),
8286         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}'."),
8287         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}'."),
8288         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}'."),
8289         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}'."),
8290         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}'."),
8291         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}'."),
8292         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}'."),
8293         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."),
8294         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}'."),
8295         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}'."),
8296         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."),
8297         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}'."),
8298         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}'."),
8299         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}'."),
8300         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}'."),
8301         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."),
8302         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}'."),
8303         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}'."),
8304         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."),
8305         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}'."),
8306         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}'."),
8307         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}'."),
8308         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}'."),
8309         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}'."),
8310         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}'."),
8311         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."),
8312         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}'."),
8313         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}'."),
8314         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."),
8315         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}'."),
8316         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}'."),
8317         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}'."),
8318         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}'."),
8319         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."),
8320         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}'."),
8321         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}'."),
8322         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}'."),
8323         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}'."),
8324         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}'."),
8325         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."),
8326         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}'."),
8327         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}'."),
8328         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."),
8329         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."),
8330         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}'."),
8331         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}'."),
8332         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."),
8333         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}'."),
8334         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}'."),
8335         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}'."),
8336         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}'."),
8337         Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
8338         The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1: diag(4104, ts.DiagnosticCategory.Error, "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104", "The type '{0}' is 'readonly' and cannot be assigned to the mutable type '{1}'."),
8339         Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter: diag(4105, ts.DiagnosticCategory.Error, "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105", "Private or protected member '{0}' cannot be accessed on a type parameter."),
8340         Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."),
8341         Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."),
8342         Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."),
8343         Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."),
8344         Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
8345         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."),
8346         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."),
8347         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}'."),
8348         Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
8349         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}."),
8350         Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
8351         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}."),
8352         Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"),
8353         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}."),
8354         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."),
8355         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."),
8356         Option_0_cannot_be_specified_when_option_target_is_ES3: diag(5048, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_target_is_ES3_5048", "Option '{0}' cannot be specified when option 'target' is 'ES3'."),
8357         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."),
8358         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}'."),
8359         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}'."),
8360         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}'."),
8361         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."),
8362         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."),
8363         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}'."),
8364         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}'."),
8365         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."),
8366         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."),
8367         Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' can have at most one '*' character."),
8368         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."),
8369         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}'."),
8370         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}'."),
8371         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."),
8372         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."),
8373         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."),
8374         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}'."),
8375         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."),
8376         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'."),
8377         Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
8378         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}."),
8379         Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."),
8380         _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."),
8381         _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."),
8382         Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"),
8383         Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
8384         Unknown_watch_option_0_Did_you_mean_1: diag(5079, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_Did_you_mean_1_5079", "Unknown watch option '{0}'. Did you mean '{1}'?"),
8385         Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."),
8386         Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."),
8387         _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."),
8388         Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
8389         Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."),
8390         A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."),
8391         A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."),
8392         A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."),
8393         The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."),
8394         Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."),
8395         Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"),
8396         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."),
8397         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."),
8398         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
8399         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."),
8400         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."),
8401         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
8402         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
8403         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."),
8404         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."),
8405         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
8406         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
8407         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."),
8408         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
8409         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."),
8410         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
8411         Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."),
8412         Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."),
8413         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
8414         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
8415         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'."),
8416         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
8417         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
8418         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
8419         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
8420         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
8421         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
8422         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."),
8423         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
8424         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
8425         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
8426         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
8427         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
8428         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
8429         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
8430         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
8431         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
8432         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
8433         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
8434         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}'."),
8435         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}."),
8436         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 <language> or <language>-<territory>. For example '{0}' or '{1}'."),
8437         Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
8438         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
8439         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
8440         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."),
8441         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
8442         File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."),
8443         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."),
8444         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."),
8445         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."),
8446         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."),
8447         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)."),
8448         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
8449         Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'null' on command line."),
8450         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
8451         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."),
8452         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."),
8453         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)."),
8454         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."),
8455         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
8456         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."),
8457         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)."),
8458         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."),
8459         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."),
8460         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."),
8461         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."),
8462         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."),
8463         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."),
8464         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'."),
8465         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."),
8466         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}."),
8467         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."),
8468         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"),
8469         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."),
8470         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
8471         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}'."),
8472         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}'."),
8473         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}'. ========"),
8474         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
8475         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}'."),
8476         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
8477         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}'."),
8478         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}'."),
8479         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}'."),
8480         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
8481         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."),
8482         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}'."),
8483         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
8484         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."),
8485         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}'."),
8486         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
8487         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."),
8488         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}'."),
8489         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}'."),
8490         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}'."),
8491         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}'."),
8492         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}'."),
8493         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}'."),
8494         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
8495         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
8496         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."),
8497         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
8498         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'?"),
8499         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."),
8500         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}'. ========"),
8501         Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
8502         Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
8503         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}. ========"),
8504         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. ========"),
8505         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
8506         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."),
8507         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. ========"),
8508         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."),
8509         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}'."),
8510         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."),
8511         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}'. ========"),
8512         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. ========"),
8513         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}'."),
8514         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'."),
8515         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."),
8516         _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),
8517         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
8518         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
8519         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."),
8520         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}'."),
8521         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),
8522         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
8523         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}'."),
8524         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."),
8525         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."),
8526         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}'."),
8527         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."),
8528         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'."),
8529         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}'."),
8530         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."),
8531         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
8532         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
8533         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."),
8534         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."),
8535         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')."),
8536         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."),
8537         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."),
8538         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')"),
8539         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."),
8540         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)."),
8541         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."),
8542         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."),
8543         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."),
8544         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
8545         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."),
8546         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."),
8547         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
8548         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
8549         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'."),
8550         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."),
8551         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
8552         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"),
8553         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
8554         Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
8555         Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
8556         Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
8557         Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
8558         Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
8559         Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
8560         Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
8561         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'."),
8562         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
8563         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
8564         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
8565         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."),
8566         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."),
8567         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."),
8568         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
8569         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."),
8570         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
8571         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."),
8572         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."),
8573         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),
8574         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."),
8575         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."),
8576         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)."),
8577         _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),
8578         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
8579         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
8580         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
8581         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}"),
8582         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
8583         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}"),
8584         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
8585         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
8586         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused."),
8587         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."),
8588         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}'."),
8589         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}'."),
8590         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."),
8591         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."),
8592         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."),
8593         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?"),
8594         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?"),
8595         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."),
8596         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}'."),
8597         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
8598         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
8599         Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2: diag(6218, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218", "======== Module name '{0}' was successfully resolved to '{1}' with Package ID '{2}'. ========"),
8600         Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3: diag(6219, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219", "======== Type reference directive '{0}' was successfully resolved to '{1}' with Package ID '{2}', primary: {3}. ========"),
8601         package_json_had_a_falsy_0_field: diag(6220, ts.DiagnosticCategory.Message, "package_json_had_a_falsy_0_field_6220", "'package.json' had a falsy '{0}' field."),
8602         Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects: diag(6221, ts.DiagnosticCategory.Message, "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221", "Disable use of source files instead of declaration files from referenced projects."),
8603         Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."),
8604         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
8605         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
8606         Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."),
8607         Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."),
8608         Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."),
8609         Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."),
8610         Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."),
8611         Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."),
8612         Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."),
8613         Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."),
8614         This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."),
8615         This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without: diag(6234, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234", "This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'?"),
8616         Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."),
8617         Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."),
8618         Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."),
8619         Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"),
8620         Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
8621         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
8622         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."),
8623         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}'."),
8624         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."),
8625         File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307", "File '{0}' is not listed within the file list of project '{1}'. Projects must list all files or use an 'include' pattern."),
8626         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"),
8627         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"),
8628         Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."),
8629         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}'"),
8630         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}'"),
8631         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"),
8632         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"),
8633         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"),
8634         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
8635         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}"),
8636         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}'"),
8637         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
8638         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
8639         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"),
8640         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
8641         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"),
8642         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"),
8643         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"),
8644         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
8645         Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
8646         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')"),
8647         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"),
8648         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."),
8649         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."),
8650         Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
8651         Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
8652         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
8653         A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
8654         A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
8655         Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
8656         Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
8657         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
8658         Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
8659         Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
8660         Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
8661         Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"),
8662         Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"),
8663         Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."),
8664         _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
8665         Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."),
8666         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}'"),
8667         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."),
8668         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."),
8669         Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."),
8670         File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"),
8671         Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"),
8672         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."),
8673         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."),
8674         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."),
8675         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."),
8676         _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."),
8677         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."),
8678         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."),
8679         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."),
8680         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'."),
8681         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."),
8682         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."),
8683         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."),
8684         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."),
8685         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."),
8686         _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."),
8687         _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."),
8688         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."),
8689         Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_retu_7025", "Generator implicitly has yield type '{0}' because it does not yield any values. Consider supplying a return type annotation."),
8690         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."),
8691         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
8692         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
8693         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
8694         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."),
8695         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."),
8696         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."),
8697         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."),
8698         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."),
8699         Try_npm_i_save_dev_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_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035", "Try `npm i --save-dev @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),
8700         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}'."),
8701         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'."),
8702         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."),
8703         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."),
8704         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}`"),
8705         The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
8706         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."),
8707         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."),
8708         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."),
8709         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."),
8710         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."),
8711         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."),
8712         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."),
8713         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."),
8714         _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."),
8715         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}'?"),
8716         Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1: diag(7052, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052", "Element implicitly has an 'any' type because type '{0}' has no index signature. Did you mean to call '{1}'?"),
8717         Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1: diag(7053, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053", "Element implicitly has an 'any' type because expression of type '{0}' can't be used to index type '{1}'."),
8718         No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1: diag(7054, ts.DiagnosticCategory.Error, "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054", "No index signature with a parameter of type '{0}' was found on type '{1}'."),
8719         _0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type: diag(7055, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055", "'{0}', which lacks return-type annotation, implicitly has an '{1}' yield type."),
8720         The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed: diag(7056, ts.DiagnosticCategory.Error, "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056", "The inferred type of this node exceeds the maximum length the compiler will serialize. An explicit type annotation is needed."),
8721         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
8722         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."),
8723         import_can_only_be_used_in_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."),
8724         export_can_only_be_used_in_TypeScript_files: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_TypeScript_files_8003", "'export =' can only be used in TypeScript files."),
8725         Type_parameter_declarations_can_only_be_used_in_TypeScript_files: diag(8004, ts.DiagnosticCategory.Error, "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004", "Type parameter declarations can only be used in TypeScript files."),
8726         implements_clauses_can_only_be_used_in_TypeScript_files: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_TypeScript_files_8005", "'implements' clauses can only be used in TypeScript files."),
8727         _0_declarations_can_only_be_used_in_TypeScript_files: diag(8006, ts.DiagnosticCategory.Error, "_0_declarations_can_only_be_used_in_TypeScript_files_8006", "'{0}' declarations can only be used in TypeScript files."),
8728         Type_aliases_can_only_be_used_in_TypeScript_files: diag(8008, ts.DiagnosticCategory.Error, "Type_aliases_can_only_be_used_in_TypeScript_files_8008", "Type aliases can only be used in TypeScript files."),
8729         The_0_modifier_can_only_be_used_in_TypeScript_files: diag(8009, ts.DiagnosticCategory.Error, "The_0_modifier_can_only_be_used_in_TypeScript_files_8009", "The '{0}' modifier can only be used in TypeScript files."),
8730         Type_annotations_can_only_be_used_in_TypeScript_files: diag(8010, ts.DiagnosticCategory.Error, "Type_annotations_can_only_be_used_in_TypeScript_files_8010", "Type annotations can only be used in TypeScript files."),
8731         Type_arguments_can_only_be_used_in_TypeScript_files: diag(8011, ts.DiagnosticCategory.Error, "Type_arguments_can_only_be_used_in_TypeScript_files_8011", "Type arguments can only be used in TypeScript files."),
8732         Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, ts.DiagnosticCategory.Error, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."),
8733         Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, ts.DiagnosticCategory.Error, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."),
8734         Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, ts.DiagnosticCategory.Error, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."),
8735         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}'."),
8736         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}'."),
8737         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
8738         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."),
8739         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."),
8740         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."),
8741         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."),
8742         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."),
8743         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."),
8744         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."),
8745         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."),
8746         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."),
8747         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."),
8748         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."),
8749         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."),
8750         Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."),
8751         A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."),
8752         The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."),
8753         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."),
8754         class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
8755         Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
8756         Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."),
8757         Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."),
8758         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'."),
8759         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."),
8760         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}'."),
8761         JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
8762         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."),
8763         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'."),
8764         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."),
8765         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."),
8766         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."),
8767         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."),
8768         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
8769         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."),
8770         _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}'?"),
8771         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."),
8772         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."),
8773         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."),
8774         The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option: diag(17016, ts.DiagnosticCategory.Error, "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016", "The 'jsxFragmentFactory' compiler option must be provided to use JSX fragments with the 'jsxFactory' compiler option."),
8775         An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments: diag(17017, ts.DiagnosticCategory.Error, "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017", "An @jsxFrag pragma is required when using an @jsx pragma with JSX fragments."),
8776         Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"),
8777         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}"),
8778         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."),
8779         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."),
8780         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}'."),
8781         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."),
8782         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."),
8783         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."),
8784         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."),
8785         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."),
8786         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."),
8787         await_has_no_effect_on_the_type_of_this_expression: diag(80007, ts.DiagnosticCategory.Suggestion, "await_has_no_effect_on_the_type_of_this_expression_80007", "'await' has no effect on the type of this expression."),
8788         Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers: diag(80008, ts.DiagnosticCategory.Suggestion, "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008", "Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers."),
8789         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
8790         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"),
8791         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
8792         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
8793         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
8794         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
8795         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
8796         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
8797         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
8798         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
8799         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
8800         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
8801         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
8802         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}\""),
8803         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
8804         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
8805         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
8806         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
8807         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
8808         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
8809         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
8810         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
8811         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
8812         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
8813         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}'"),
8814         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
8815         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
8816         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
8817         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
8818         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
8819         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
8820         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}\""),
8821         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
8822         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
8823         Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"),
8824         Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, ts.DiagnosticCategory.Message, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"),
8825         Declare_private_method_0: diag(90038, ts.DiagnosticCategory.Message, "Declare_private_method_0_90038", "Declare private method '{0}'"),
8826         Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"),
8827         Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"),
8828         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
8829         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
8830         Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
8831         Convert_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"),
8832         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
8833         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
8834         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
8835         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
8836         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
8837         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
8838         Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
8839         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
8840         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
8841         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
8842         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
8843         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
8844         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
8845         Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
8846         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
8847         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
8848         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}'"),
8849         Convert_all_type_literals_to_mapped_type: diag(95021, ts.DiagnosticCategory.Message, "Convert_all_type_literals_to_mapped_type_95021", "Convert all type literals to mapped type"),
8850         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
8851         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
8852         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
8853         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"),
8854         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
8855         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
8856         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"),
8857         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"),
8858         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"),
8859         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)"),
8860         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
8861         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
8862         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
8863         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
8864         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"),
8865         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"),
8866         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
8867         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
8868         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
8869         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
8870         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"),
8871         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
8872         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
8873         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
8874         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
8875         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
8876         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
8877         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
8878         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
8879         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
8880         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
8881         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
8882         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
8883         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
8884         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
8885         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
8886         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"),
8887         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
8888         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
8889         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
8890         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
8891         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
8892         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
8893         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
8894         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
8895         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
8896         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
8897         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"),
8898         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"),
8899         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
8900         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"),
8901         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"),
8902         Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
8903         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
8904         Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
8905         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
8906         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
8907         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
8908         Infer_this_type_of_0_from_usage: diag(95080, ts.DiagnosticCategory.Message, "Infer_this_type_of_0_from_usage_95080", "Infer 'this' type of '{0}' from usage"),
8909         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
8910         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
8911         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
8912         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
8913         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
8914         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
8915         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
8916         Enable_the_jsx_flag_in_your_configuration_file: diag(95088, ts.DiagnosticCategory.Message, "Enable_the_jsx_flag_in_your_configuration_file_95088", "Enable the '--jsx' flag in your configuration file"),
8917         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
8918         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
8919         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
8920         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
8921         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
8922         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
8923         Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"),
8924         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
8925         Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"),
8926         Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"),
8927         Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"),
8928         Convert_invalid_character_to_its_html_entity_code: diag(95100, ts.DiagnosticCategory.Message, "Convert_invalid_character_to_its_html_entity_code_95100", "Convert invalid character to its html entity code"),
8929         Convert_all_invalid_characters_to_HTML_entity_code: diag(95101, ts.DiagnosticCategory.Message, "Convert_all_invalid_characters_to_HTML_entity_code_95101", "Convert all invalid characters to HTML entity code"),
8930         Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
8931         Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
8932         Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
8933         Convert_function_expression_0_to_arrow_function: diag(95105, ts.DiagnosticCategory.Message, "Convert_function_expression_0_to_arrow_function_95105", "Convert function expression '{0}' to arrow function"),
8934         Convert_function_declaration_0_to_arrow_function: diag(95106, ts.DiagnosticCategory.Message, "Convert_function_declaration_0_to_arrow_function_95106", "Convert function declaration '{0}' to arrow function"),
8935         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
8936         Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"),
8937         Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"),
8938         Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"),
8939         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
8940         Remove_braces_from_arrow_function_body: diag(95112, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_body_95112", "Remove braces from arrow function body"),
8941         Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"),
8942         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
8943         Remove_braces_from_all_arrow_function_bodies_with_relevant_issues: diag(95115, ts.DiagnosticCategory.Message, "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115", "Remove braces from all arrow function bodies with relevant issues"),
8944         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
8945         Move_labeled_tuple_element_modifiers_to_labels: diag(95117, ts.DiagnosticCategory.Message, "Move_labeled_tuple_element_modifiers_to_labels_95117", "Move labeled tuple element modifiers to labels"),
8946         Convert_overload_list_to_single_signature: diag(95118, ts.DiagnosticCategory.Message, "Convert_overload_list_to_single_signature_95118", "Convert overload list to single signature"),
8947         Generate_get_and_set_accessors_for_all_overriding_properties: diag(95119, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_for_all_overriding_properties_95119", "Generate 'get' and 'set' accessors for all overriding properties"),
8948         Wrap_in_JSX_fragment: diag(95120, ts.DiagnosticCategory.Message, "Wrap_in_JSX_fragment_95120", "Wrap in JSX fragment"),
8949         Wrap_all_unparented_JSX_in_JSX_fragment: diag(95121, ts.DiagnosticCategory.Message, "Wrap_all_unparented_JSX_in_JSX_fragment_95121", "Wrap all unparented JSX in JSX fragment"),
8950         Convert_arrow_function_or_function_expression: diag(95122, ts.DiagnosticCategory.Message, "Convert_arrow_function_or_function_expression_95122", "Convert arrow function or function expression"),
8951         Convert_to_anonymous_function: diag(95123, ts.DiagnosticCategory.Message, "Convert_to_anonymous_function_95123", "Convert to anonymous function"),
8952         Convert_to_named_function: diag(95124, ts.DiagnosticCategory.Message, "Convert_to_named_function_95124", "Convert to named function"),
8953         Convert_to_arrow_function: diag(95125, ts.DiagnosticCategory.Message, "Convert_to_arrow_function_95125", "Convert to arrow function"),
8954         Remove_parentheses: diag(95126, ts.DiagnosticCategory.Message, "Remove_parentheses_95126", "Remove parentheses"),
8955         Could_not_find_a_containing_arrow_function: diag(95127, ts.DiagnosticCategory.Message, "Could_not_find_a_containing_arrow_function_95127", "Could not find a containing arrow function"),
8956         Containing_function_is_not_an_arrow_function: diag(95128, ts.DiagnosticCategory.Message, "Containing_function_is_not_an_arrow_function_95128", "Containing function is not an arrow function"),
8957         Could_not_find_export_statement: diag(95129, ts.DiagnosticCategory.Message, "Could_not_find_export_statement_95129", "Could not find export statement"),
8958         This_file_already_has_a_default_export: diag(95130, ts.DiagnosticCategory.Message, "This_file_already_has_a_default_export_95130", "This file already has a default export"),
8959         Could_not_find_import_clause: diag(95131, ts.DiagnosticCategory.Message, "Could_not_find_import_clause_95131", "Could not find import clause"),
8960         Could_not_find_namespace_import_or_named_imports: diag(95132, ts.DiagnosticCategory.Message, "Could_not_find_namespace_import_or_named_imports_95132", "Could not find namespace import or named imports"),
8961         Selection_is_not_a_valid_type_node: diag(95133, ts.DiagnosticCategory.Message, "Selection_is_not_a_valid_type_node_95133", "Selection is not a valid type node"),
8962         No_type_could_be_extracted_from_this_type_node: diag(95134, ts.DiagnosticCategory.Message, "No_type_could_be_extracted_from_this_type_node_95134", "No type could be extracted from this type node"),
8963         Could_not_find_property_for_which_to_generate_accessor: diag(95135, ts.DiagnosticCategory.Message, "Could_not_find_property_for_which_to_generate_accessor_95135", "Could not find property for which to generate accessor"),
8964         Name_is_not_valid: diag(95136, ts.DiagnosticCategory.Message, "Name_is_not_valid_95136", "Name is not valid"),
8965         Can_only_convert_property_with_modifier: diag(95137, ts.DiagnosticCategory.Message, "Can_only_convert_property_with_modifier_95137", "Can only convert property with modifier"),
8966         Switch_each_misused_0_to_1: diag(95138, ts.DiagnosticCategory.Message, "Switch_each_misused_0_to_1_95138", "Switch each misused '{0}' to '{1}'"),
8967         Convert_to_optional_chain_expression: diag(95139, ts.DiagnosticCategory.Message, "Convert_to_optional_chain_expression_95139", "Convert to optional chain expression"),
8968         Could_not_find_convertible_access_expression: diag(95140, ts.DiagnosticCategory.Message, "Could_not_find_convertible_access_expression_95140", "Could not find convertible access expression"),
8969         Could_not_find_matching_access_expressions: diag(95141, ts.DiagnosticCategory.Message, "Could_not_find_matching_access_expressions_95141", "Could not find matching access expressions"),
8970         Can_only_convert_logical_AND_access_chains: diag(95142, ts.DiagnosticCategory.Message, "Can_only_convert_logical_AND_access_chains_95142", "Can only convert logical AND access chains"),
8971         Add_void_to_Promise_resolved_without_a_value: diag(95143, ts.DiagnosticCategory.Message, "Add_void_to_Promise_resolved_without_a_value_95143", "Add 'void' to Promise resolved without a value"),
8972         Add_void_to_all_Promises_resolved_without_a_value: diag(95144, ts.DiagnosticCategory.Message, "Add_void_to_all_Promises_resolved_without_a_value_95144", "Add 'void' to all Promises resolved without a value"),
8973         No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."),
8974         Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."),
8975         JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"),
8976         Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters."),
8977         An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."),
8978         The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."),
8979         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
8980         Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier: diag(18013, ts.DiagnosticCategory.Error, "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013", "Property '{0}' is not accessible outside class '{1}' because it has a private identifier."),
8981         The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling: diag(18014, ts.DiagnosticCategory.Error, "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014", "The property '{0}' cannot be accessed on type '{1}' within this class because it is shadowed by another private identifier with the same spelling."),
8982         Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2: diag(18015, ts.DiagnosticCategory.Error, "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015", "Property '{0}' in type '{1}' refers to a different member that cannot be accessed from within type '{2}'."),
8983         Private_identifiers_are_not_allowed_outside_class_bodies: diag(18016, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_outside_class_bodies_18016", "Private identifiers are not allowed outside class bodies."),
8984         The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"),
8985         The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"),
8986         _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier."),
8987         A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."),
8988         An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."),
8989         An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."),
8990         can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."),
8991         Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."),
8992         Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."),
8993         Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."),
8994         An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."),
8995         The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."),
8996         The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."),
8997         Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."),
8998         Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, ts.DiagnosticCategory.Message, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."),
8999         Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."),
9000     };
9001 })(ts || (ts = {}));
9002 var ts;
9003 (function (ts) {
9004     var _a;
9005     /* @internal */
9006     function tokenIsIdentifierOrKeyword(token) {
9007         return token >= 78 /* Identifier */;
9008     }
9009     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
9010     /* @internal */
9011     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
9012         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
9013     }
9014     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
9015     var textToKeywordObj = (_a = {
9016             abstract: 125 /* AbstractKeyword */,
9017             any: 128 /* AnyKeyword */,
9018             as: 126 /* AsKeyword */,
9019             asserts: 127 /* AssertsKeyword */,
9020             bigint: 155 /* BigIntKeyword */,
9021             boolean: 131 /* BooleanKeyword */,
9022             break: 80 /* BreakKeyword */,
9023             case: 81 /* CaseKeyword */,
9024             catch: 82 /* CatchKeyword */,
9025             class: 83 /* ClassKeyword */,
9026             continue: 85 /* ContinueKeyword */,
9027             const: 84 /* ConstKeyword */
9028         },
9029         _a["" + "constructor"] = 132 /* ConstructorKeyword */,
9030         _a.debugger = 86 /* DebuggerKeyword */,
9031         _a.declare = 133 /* DeclareKeyword */,
9032         _a.default = 87 /* DefaultKeyword */,
9033         _a.delete = 88 /* DeleteKeyword */,
9034         _a.do = 89 /* DoKeyword */,
9035         _a.else = 90 /* ElseKeyword */,
9036         _a.enum = 91 /* EnumKeyword */,
9037         _a.export = 92 /* ExportKeyword */,
9038         _a.extends = 93 /* ExtendsKeyword */,
9039         _a.false = 94 /* FalseKeyword */,
9040         _a.finally = 95 /* FinallyKeyword */,
9041         _a.for = 96 /* ForKeyword */,
9042         _a.from = 153 /* FromKeyword */,
9043         _a.function = 97 /* FunctionKeyword */,
9044         _a.get = 134 /* GetKeyword */,
9045         _a.if = 98 /* IfKeyword */,
9046         _a.implements = 116 /* ImplementsKeyword */,
9047         _a.import = 99 /* ImportKeyword */,
9048         _a.in = 100 /* InKeyword */,
9049         _a.infer = 135 /* InferKeyword */,
9050         _a.instanceof = 101 /* InstanceOfKeyword */,
9051         _a.interface = 117 /* InterfaceKeyword */,
9052         _a.intrinsic = 136 /* IntrinsicKeyword */,
9053         _a.is = 137 /* IsKeyword */,
9054         _a.keyof = 138 /* KeyOfKeyword */,
9055         _a.let = 118 /* LetKeyword */,
9056         _a.module = 139 /* ModuleKeyword */,
9057         _a.namespace = 140 /* NamespaceKeyword */,
9058         _a.never = 141 /* NeverKeyword */,
9059         _a.new = 102 /* NewKeyword */,
9060         _a.null = 103 /* NullKeyword */,
9061         _a.number = 144 /* NumberKeyword */,
9062         _a.object = 145 /* ObjectKeyword */,
9063         _a.package = 119 /* PackageKeyword */,
9064         _a.private = 120 /* PrivateKeyword */,
9065         _a.protected = 121 /* ProtectedKeyword */,
9066         _a.public = 122 /* PublicKeyword */,
9067         _a.readonly = 142 /* ReadonlyKeyword */,
9068         _a.require = 143 /* RequireKeyword */,
9069         _a.global = 154 /* GlobalKeyword */,
9070         _a.return = 104 /* ReturnKeyword */,
9071         _a.set = 146 /* SetKeyword */,
9072         _a.static = 123 /* StaticKeyword */,
9073         _a.string = 147 /* StringKeyword */,
9074         _a.super = 105 /* SuperKeyword */,
9075         _a.switch = 106 /* SwitchKeyword */,
9076         _a.symbol = 148 /* SymbolKeyword */,
9077         _a.this = 107 /* ThisKeyword */,
9078         _a.throw = 108 /* ThrowKeyword */,
9079         _a.true = 109 /* TrueKeyword */,
9080         _a.try = 110 /* TryKeyword */,
9081         _a.type = 149 /* TypeKeyword */,
9082         _a.typeof = 111 /* TypeOfKeyword */,
9083         _a.undefined = 150 /* UndefinedKeyword */,
9084         _a.unique = 151 /* UniqueKeyword */,
9085         _a.unknown = 152 /* UnknownKeyword */,
9086         _a.var = 112 /* VarKeyword */,
9087         _a.void = 113 /* VoidKeyword */,
9088         _a.while = 114 /* WhileKeyword */,
9089         _a.with = 115 /* WithKeyword */,
9090         _a.yield = 124 /* YieldKeyword */,
9091         _a.async = 129 /* AsyncKeyword */,
9092         _a.await = 130 /* AwaitKeyword */,
9093         _a.of = 156 /* OfKeyword */,
9094         _a);
9095     var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj));
9096     var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, "</": 30 /* LessThanSlashToken */, ">>": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 77 /* CaretEqualsToken */, "||=": 74 /* BarBarEqualsToken */, "&&=": 75 /* AmpersandAmpersandEqualsToken */, "??=": 76 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ })));
9097     /*
9098         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
9099         IdentifierStart ::
9100             Can contain Unicode 3.0.0 categories:
9101             Uppercase letter (Lu),
9102             Lowercase letter (Ll),
9103             Titlecase letter (Lt),
9104             Modifier letter (Lm),
9105             Other letter (Lo), or
9106             Letter number (Nl).
9107         IdentifierPart :: =
9108             Can contain IdentifierStart + Unicode 3.0.0 categories:
9109             Non-spacing mark (Mn),
9110             Combining spacing mark (Mc),
9111             Decimal number (Nd), or
9112             Connector punctuation (Pc).
9113
9114         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
9115         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
9116     */
9117     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,];
9118     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,];
9119     /*
9120         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
9121         IdentifierStart ::
9122             Can contain Unicode 6.2 categories:
9123             Uppercase letter (Lu),
9124             Lowercase letter (Ll),
9125             Titlecase letter (Lt),
9126             Modifier letter (Lm),
9127             Other letter (Lo), or
9128             Letter number (Nl).
9129         IdentifierPart ::
9130             Can contain IdentifierStart + Unicode 6.2 categories:
9131             Non-spacing mark (Mn),
9132             Combining spacing mark (Mc),
9133             Decimal number (Nd),
9134             Connector punctuation (Pc),
9135             <ZWNJ>, or
9136             <ZWJ>.
9137
9138         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
9139         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
9140     */
9141     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,];
9142     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,];
9143     /**
9144      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
9145      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
9146      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
9147      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
9148      */
9149     var unicodeESNextIdentifierStart = [65, 90, 97, 122, 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, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 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, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 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, 2809, 2809, 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, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 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, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 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, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 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, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 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, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 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, 43824, 43866, 43868, 43879, 43888, 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, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101];
9150     var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 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, 2556, 2556, 2558, 2558, 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, 2809, 2815, 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, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 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, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 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, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 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, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 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, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 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, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 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, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 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, 65071, 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, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999];
9151     /**
9152      * Test for whether a single line comment's text contains a directive.
9153      */
9154     var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
9155     /**
9156      * Test for whether a multi-line comment's last line contains a directive.
9157      */
9158     var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
9159     function lookupInUnicodeMap(code, map) {
9160         // Bail out quickly if it couldn't possibly be in the map.
9161         if (code < map[0]) {
9162             return false;
9163         }
9164         // Perform binary search in one of the Unicode range maps
9165         var lo = 0;
9166         var hi = map.length;
9167         var mid;
9168         while (lo + 1 < hi) {
9169             mid = lo + (hi - lo) / 2;
9170             // mid has to be even to catch a range's beginning
9171             mid -= mid % 2;
9172             if (map[mid] <= code && code <= map[mid + 1]) {
9173                 return true;
9174             }
9175             if (code < map[mid]) {
9176                 hi = mid;
9177             }
9178             else {
9179                 lo = mid + 2;
9180             }
9181         }
9182         return false;
9183     }
9184     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
9185         return languageVersion >= 2 /* ES2015 */ ?
9186             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
9187             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
9188                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
9189     }
9190     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
9191     function isUnicodeIdentifierPart(code, languageVersion) {
9192         return languageVersion >= 2 /* ES2015 */ ?
9193             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
9194             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
9195                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
9196     }
9197     function makeReverseMap(source) {
9198         var result = [];
9199         source.forEach(function (value, name) {
9200             result[value] = name;
9201         });
9202         return result;
9203     }
9204     var tokenStrings = makeReverseMap(textToToken);
9205     function tokenToString(t) {
9206         return tokenStrings[t];
9207     }
9208     ts.tokenToString = tokenToString;
9209     /* @internal */
9210     function stringToToken(s) {
9211         return textToToken.get(s);
9212     }
9213     ts.stringToToken = stringToToken;
9214     /* @internal */
9215     function computeLineStarts(text) {
9216         var result = new Array();
9217         var pos = 0;
9218         var lineStart = 0;
9219         while (pos < text.length) {
9220             var ch = text.charCodeAt(pos);
9221             pos++;
9222             switch (ch) {
9223                 case 13 /* carriageReturn */:
9224                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
9225                         pos++;
9226                     }
9227                 // falls through
9228                 case 10 /* lineFeed */:
9229                     result.push(lineStart);
9230                     lineStart = pos;
9231                     break;
9232                 default:
9233                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
9234                         result.push(lineStart);
9235                         lineStart = pos;
9236                     }
9237                     break;
9238             }
9239         }
9240         result.push(lineStart);
9241         return result;
9242     }
9243     ts.computeLineStarts = computeLineStarts;
9244     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
9245         return sourceFile.getPositionOfLineAndCharacter ?
9246             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
9247             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
9248     }
9249     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
9250     /* @internal */
9251     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
9252         if (line < 0 || line >= lineStarts.length) {
9253             if (allowEdits) {
9254                 // Clamp line to nearest allowable value
9255                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
9256             }
9257             else {
9258                 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
9259             }
9260         }
9261         var res = lineStarts[line] + character;
9262         if (allowEdits) {
9263             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
9264             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
9265             // apply them to the computed position to improve accuracy
9266             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
9267         }
9268         if (line < lineStarts.length - 1) {
9269             ts.Debug.assert(res < lineStarts[line + 1]);
9270         }
9271         else if (debugText !== undefined) {
9272             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
9273         }
9274         return res;
9275     }
9276     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
9277     /* @internal */
9278     function getLineStarts(sourceFile) {
9279         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
9280     }
9281     ts.getLineStarts = getLineStarts;
9282     /* @internal */
9283     function computeLineAndCharacterOfPosition(lineStarts, position) {
9284         var lineNumber = computeLineOfPosition(lineStarts, position);
9285         return {
9286             line: lineNumber,
9287             character: position - lineStarts[lineNumber]
9288         };
9289     }
9290     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
9291     /**
9292      * @internal
9293      * We assume the first line starts at position 0 and 'position' is non-negative.
9294      */
9295     function computeLineOfPosition(lineStarts, position, lowerBound) {
9296         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
9297         if (lineNumber < 0) {
9298             // If the actual position was not found,
9299             // the binary search returns the 2's-complement of the next line start
9300             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
9301             // then the search will return -2.
9302             //
9303             // We want the index of the previous line start, so we subtract 1.
9304             // Review 2's-complement if this is confusing.
9305             lineNumber = ~lineNumber - 1;
9306             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
9307         }
9308         return lineNumber;
9309     }
9310     ts.computeLineOfPosition = computeLineOfPosition;
9311     /** @internal */
9312     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
9313         if (pos1 === pos2)
9314             return 0;
9315         var lineStarts = getLineStarts(sourceFile);
9316         var lower = Math.min(pos1, pos2);
9317         var isNegative = lower === pos2;
9318         var upper = isNegative ? pos1 : pos2;
9319         var lowerLine = computeLineOfPosition(lineStarts, lower);
9320         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
9321         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
9322     }
9323     ts.getLinesBetweenPositions = getLinesBetweenPositions;
9324     function getLineAndCharacterOfPosition(sourceFile, position) {
9325         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
9326     }
9327     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
9328     function isWhiteSpaceLike(ch) {
9329         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
9330     }
9331     ts.isWhiteSpaceLike = isWhiteSpaceLike;
9332     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
9333     function isWhiteSpaceSingleLine(ch) {
9334         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
9335         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
9336         return ch === 32 /* space */ ||
9337             ch === 9 /* tab */ ||
9338             ch === 11 /* verticalTab */ ||
9339             ch === 12 /* formFeed */ ||
9340             ch === 160 /* nonBreakingSpace */ ||
9341             ch === 133 /* nextLine */ ||
9342             ch === 5760 /* ogham */ ||
9343             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
9344             ch === 8239 /* narrowNoBreakSpace */ ||
9345             ch === 8287 /* mathematicalSpace */ ||
9346             ch === 12288 /* ideographicSpace */ ||
9347             ch === 65279 /* byteOrderMark */;
9348     }
9349     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
9350     function isLineBreak(ch) {
9351         // ES5 7.3:
9352         // The ECMAScript line terminator characters are listed in Table 3.
9353         //     Table 3: Line Terminator Characters
9354         //     Code Unit Value     Name                    Formal Name
9355         //     \u000A              Line Feed               <LF>
9356         //     \u000D              Carriage Return         <CR>
9357         //     \u2028              Line separator          <LS>
9358         //     \u2029              Paragraph separator     <PS>
9359         // Only the characters in Table 3 are treated as line terminators. Other new line or line
9360         // breaking characters are treated as white space but not as line terminators.
9361         return ch === 10 /* lineFeed */ ||
9362             ch === 13 /* carriageReturn */ ||
9363             ch === 8232 /* lineSeparator */ ||
9364             ch === 8233 /* paragraphSeparator */;
9365     }
9366     ts.isLineBreak = isLineBreak;
9367     function isDigit(ch) {
9368         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
9369     }
9370     function isHexDigit(ch) {
9371         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
9372     }
9373     function isCodePoint(code) {
9374         return code <= 0x10FFFF;
9375     }
9376     /* @internal */
9377     function isOctalDigit(ch) {
9378         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
9379     }
9380     ts.isOctalDigit = isOctalDigit;
9381     function couldStartTrivia(text, pos) {
9382         // Keep in sync with skipTrivia
9383         var ch = text.charCodeAt(pos);
9384         switch (ch) {
9385             case 13 /* carriageReturn */:
9386             case 10 /* lineFeed */:
9387             case 9 /* tab */:
9388             case 11 /* verticalTab */:
9389             case 12 /* formFeed */:
9390             case 32 /* space */:
9391             case 47 /* slash */:
9392             // starts of normal trivia
9393             // falls through
9394             case 60 /* lessThan */:
9395             case 124 /* bar */:
9396             case 61 /* equals */:
9397             case 62 /* greaterThan */:
9398                 // Starts of conflict marker trivia
9399                 return true;
9400             case 35 /* hash */:
9401                 // Only if its the beginning can we have #! trivia
9402                 return pos === 0;
9403             default:
9404                 return ch > 127 /* maxAsciiCharacter */;
9405         }
9406     }
9407     ts.couldStartTrivia = couldStartTrivia;
9408     /* @internal */
9409     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
9410         if (stopAtComments === void 0) { stopAtComments = false; }
9411         if (ts.positionIsSynthesized(pos)) {
9412             return pos;
9413         }
9414         // Keep in sync with couldStartTrivia
9415         while (true) {
9416             var ch = text.charCodeAt(pos);
9417             switch (ch) {
9418                 case 13 /* carriageReturn */:
9419                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9420                         pos++;
9421                     }
9422                 // falls through
9423                 case 10 /* lineFeed */:
9424                     pos++;
9425                     if (stopAfterLineBreak) {
9426                         return pos;
9427                     }
9428                     continue;
9429                 case 9 /* tab */:
9430                 case 11 /* verticalTab */:
9431                 case 12 /* formFeed */:
9432                 case 32 /* space */:
9433                     pos++;
9434                     continue;
9435                 case 47 /* slash */:
9436                     if (stopAtComments) {
9437                         break;
9438                     }
9439                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9440                         pos += 2;
9441                         while (pos < text.length) {
9442                             if (isLineBreak(text.charCodeAt(pos))) {
9443                                 break;
9444                             }
9445                             pos++;
9446                         }
9447                         continue;
9448                     }
9449                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9450                         pos += 2;
9451                         while (pos < text.length) {
9452                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9453                                 pos += 2;
9454                                 break;
9455                             }
9456                             pos++;
9457                         }
9458                         continue;
9459                     }
9460                     break;
9461                 case 60 /* lessThan */:
9462                 case 124 /* bar */:
9463                 case 61 /* equals */:
9464                 case 62 /* greaterThan */:
9465                     if (isConflictMarkerTrivia(text, pos)) {
9466                         pos = scanConflictMarkerTrivia(text, pos);
9467                         continue;
9468                     }
9469                     break;
9470                 case 35 /* hash */:
9471                     if (pos === 0 && isShebangTrivia(text, pos)) {
9472                         pos = scanShebangTrivia(text, pos);
9473                         continue;
9474                     }
9475                     break;
9476                 default:
9477                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
9478                         pos++;
9479                         continue;
9480                     }
9481                     break;
9482             }
9483             return pos;
9484         }
9485     }
9486     ts.skipTrivia = skipTrivia;
9487     // All conflict markers consist of the same character repeated seven times.  If it is
9488     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
9489     var mergeConflictMarkerLength = "<<<<<<<".length;
9490     function isConflictMarkerTrivia(text, pos) {
9491         ts.Debug.assert(pos >= 0);
9492         // Conflict markers must be at the start of a line.
9493         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
9494             var ch = text.charCodeAt(pos);
9495             if ((pos + mergeConflictMarkerLength) < text.length) {
9496                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
9497                     if (text.charCodeAt(pos + i) !== ch) {
9498                         return false;
9499                     }
9500                 }
9501                 return ch === 61 /* equals */ ||
9502                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
9503             }
9504         }
9505         return false;
9506     }
9507     function scanConflictMarkerTrivia(text, pos, error) {
9508         if (error) {
9509             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
9510         }
9511         var ch = text.charCodeAt(pos);
9512         var len = text.length;
9513         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
9514             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
9515                 pos++;
9516             }
9517         }
9518         else {
9519             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
9520             // Consume everything from the start of a ||||||| or ======= marker to the start
9521             // of the next ======= or >>>>>>> marker.
9522             while (pos < len) {
9523                 var currentChar = text.charCodeAt(pos);
9524                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
9525                     break;
9526                 }
9527                 pos++;
9528             }
9529         }
9530         return pos;
9531     }
9532     var shebangTriviaRegex = /^#!.*/;
9533     /*@internal*/
9534     function isShebangTrivia(text, pos) {
9535         // Shebangs check must only be done at the start of the file
9536         ts.Debug.assert(pos === 0);
9537         return shebangTriviaRegex.test(text);
9538     }
9539     ts.isShebangTrivia = isShebangTrivia;
9540     /*@internal*/
9541     function scanShebangTrivia(text, pos) {
9542         var shebang = shebangTriviaRegex.exec(text)[0];
9543         pos = pos + shebang.length;
9544         return pos;
9545     }
9546     ts.scanShebangTrivia = scanShebangTrivia;
9547     /**
9548      * Invokes a callback for each comment range following the provided position.
9549      *
9550      * Single-line comment ranges include the leading double-slash characters but not the ending
9551      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
9552      * asterisk-slash characters.
9553      *
9554      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
9555      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
9556      * @param text The source text to scan.
9557      * @param pos The position at which to start scanning.
9558      * @param trailing If false, whitespace is skipped until the first line break and comments
9559      *      between that location and the next token are returned. If true, comments occurring
9560      *      between the given position and the next line break are returned.
9561      * @param cb The callback to execute as each comment range is encountered.
9562      * @param state A state value to pass to each iteration of the callback.
9563      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
9564      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
9565      *      return value of the callback.
9566      */
9567     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
9568         var pendingPos;
9569         var pendingEnd;
9570         var pendingKind;
9571         var pendingHasTrailingNewLine;
9572         var hasPendingCommentRange = false;
9573         var collecting = trailing;
9574         var accumulator = initial;
9575         if (pos === 0) {
9576             collecting = true;
9577             var shebang = getShebang(text);
9578             if (shebang) {
9579                 pos = shebang.length;
9580             }
9581         }
9582         scan: while (pos >= 0 && pos < text.length) {
9583             var ch = text.charCodeAt(pos);
9584             switch (ch) {
9585                 case 13 /* carriageReturn */:
9586                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9587                         pos++;
9588                     }
9589                 // falls through
9590                 case 10 /* lineFeed */:
9591                     pos++;
9592                     if (trailing) {
9593                         break scan;
9594                     }
9595                     collecting = true;
9596                     if (hasPendingCommentRange) {
9597                         pendingHasTrailingNewLine = true;
9598                     }
9599                     continue;
9600                 case 9 /* tab */:
9601                 case 11 /* verticalTab */:
9602                 case 12 /* formFeed */:
9603                 case 32 /* space */:
9604                     pos++;
9605                     continue;
9606                 case 47 /* slash */:
9607                     var nextChar = text.charCodeAt(pos + 1);
9608                     var hasTrailingNewLine = false;
9609                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
9610                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
9611                         var startPos = pos;
9612                         pos += 2;
9613                         if (nextChar === 47 /* slash */) {
9614                             while (pos < text.length) {
9615                                 if (isLineBreak(text.charCodeAt(pos))) {
9616                                     hasTrailingNewLine = true;
9617                                     break;
9618                                 }
9619                                 pos++;
9620                             }
9621                         }
9622                         else {
9623                             while (pos < text.length) {
9624                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9625                                     pos += 2;
9626                                     break;
9627                                 }
9628                                 pos++;
9629                             }
9630                         }
9631                         if (collecting) {
9632                             if (hasPendingCommentRange) {
9633                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
9634                                 if (!reduce && accumulator) {
9635                                     // If we are not reducing and we have a truthy result, return it.
9636                                     return accumulator;
9637                                 }
9638                             }
9639                             pendingPos = startPos;
9640                             pendingEnd = pos;
9641                             pendingKind = kind;
9642                             pendingHasTrailingNewLine = hasTrailingNewLine;
9643                             hasPendingCommentRange = true;
9644                         }
9645                         continue;
9646                     }
9647                     break scan;
9648                 default:
9649                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
9650                         if (hasPendingCommentRange && isLineBreak(ch)) {
9651                             pendingHasTrailingNewLine = true;
9652                         }
9653                         pos++;
9654                         continue;
9655                     }
9656                     break scan;
9657             }
9658         }
9659         if (hasPendingCommentRange) {
9660             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
9661         }
9662         return accumulator;
9663     }
9664     function forEachLeadingCommentRange(text, pos, cb, state) {
9665         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
9666     }
9667     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
9668     function forEachTrailingCommentRange(text, pos, cb, state) {
9669         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
9670     }
9671     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
9672     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
9673         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
9674     }
9675     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
9676     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
9677         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
9678     }
9679     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
9680     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
9681         if (!comments) {
9682             comments = [];
9683         }
9684         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
9685         return comments;
9686     }
9687     function getLeadingCommentRanges(text, pos) {
9688         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
9689     }
9690     ts.getLeadingCommentRanges = getLeadingCommentRanges;
9691     function getTrailingCommentRanges(text, pos) {
9692         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
9693     }
9694     ts.getTrailingCommentRanges = getTrailingCommentRanges;
9695     /** Optionally, get the shebang */
9696     function getShebang(text) {
9697         var match = shebangTriviaRegex.exec(text);
9698         if (match) {
9699             return match[0];
9700         }
9701     }
9702     ts.getShebang = getShebang;
9703     function isIdentifierStart(ch, languageVersion) {
9704         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
9705             ch === 36 /* $ */ || ch === 95 /* _ */ ||
9706             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
9707     }
9708     ts.isIdentifierStart = isIdentifierStart;
9709     function isIdentifierPart(ch, languageVersion, identifierVariant) {
9710         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
9711             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
9712             // "-" and ":" are valid in JSX Identifiers
9713             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
9714             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
9715     }
9716     ts.isIdentifierPart = isIdentifierPart;
9717     /* @internal */
9718     function isIdentifierText(name, languageVersion, identifierVariant) {
9719         var ch = codePointAt(name, 0);
9720         if (!isIdentifierStart(ch, languageVersion)) {
9721             return false;
9722         }
9723         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
9724             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
9725                 return false;
9726             }
9727         }
9728         return true;
9729     }
9730     ts.isIdentifierText = isIdentifierText;
9731     // Creates a scanner over a (possibly unspecified) range of a piece of text.
9732     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
9733         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
9734         var text = textInitial;
9735         // Current position (end position of text of current token)
9736         var pos;
9737         // end of text
9738         var end;
9739         // Start position of whitespace before current token
9740         var startPos;
9741         // Start position of text of current token
9742         var tokenPos;
9743         var token;
9744         var tokenValue;
9745         var tokenFlags;
9746         var commentDirectives;
9747         var inJSDocType = 0;
9748         setText(text, start, length);
9749         var scanner = {
9750             getStartPos: function () { return startPos; },
9751             getTextPos: function () { return pos; },
9752             getToken: function () { return token; },
9753             getTokenPos: function () { return tokenPos; },
9754             getTokenText: function () { return text.substring(tokenPos, pos); },
9755             getTokenValue: function () { return tokenValue; },
9756             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
9757             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
9758             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
9759             hasPrecedingJSDocComment: function () { return (tokenFlags & 2 /* PrecedingJSDocComment */) !== 0; },
9760             isIdentifier: function () { return token === 78 /* Identifier */ || token > 115 /* LastReservedWord */; },
9761             isReservedWord: function () { return token >= 80 /* FirstReservedWord */ && token <= 115 /* LastReservedWord */; },
9762             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
9763             getCommentDirectives: function () { return commentDirectives; },
9764             getNumericLiteralFlags: function () { return tokenFlags & 1008 /* NumericLiteralFlags */; },
9765             getTokenFlags: function () { return tokenFlags; },
9766             reScanGreaterToken: reScanGreaterToken,
9767             reScanAsteriskEqualsToken: reScanAsteriskEqualsToken,
9768             reScanSlashToken: reScanSlashToken,
9769             reScanTemplateToken: reScanTemplateToken,
9770             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
9771             scanJsxIdentifier: scanJsxIdentifier,
9772             scanJsxAttributeValue: scanJsxAttributeValue,
9773             reScanJsxAttributeValue: reScanJsxAttributeValue,
9774             reScanJsxToken: reScanJsxToken,
9775             reScanLessThanToken: reScanLessThanToken,
9776             reScanQuestionToken: reScanQuestionToken,
9777             scanJsxToken: scanJsxToken,
9778             scanJsDocToken: scanJsDocToken,
9779             scan: scan,
9780             getText: getText,
9781             clearCommentDirectives: clearCommentDirectives,
9782             setText: setText,
9783             setScriptTarget: setScriptTarget,
9784             setLanguageVariant: setLanguageVariant,
9785             setOnError: setOnError,
9786             setTextPos: setTextPos,
9787             setInJSDocType: setInJSDocType,
9788             tryScan: tryScan,
9789             lookAhead: lookAhead,
9790             scanRange: scanRange,
9791         };
9792         if (ts.Debug.isDebugging) {
9793             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
9794                 get: function () {
9795                     var text = scanner.getText();
9796                     return text.slice(0, scanner.getStartPos()) + "â•‘" + text.slice(scanner.getStartPos());
9797                 },
9798             });
9799         }
9800         return scanner;
9801         function error(message, errPos, length) {
9802             if (errPos === void 0) { errPos = pos; }
9803             if (onError) {
9804                 var oldPos = pos;
9805                 pos = errPos;
9806                 onError(message, length || 0);
9807                 pos = oldPos;
9808             }
9809         }
9810         function scanNumberFragment() {
9811             var start = pos;
9812             var allowSeparator = false;
9813             var isPreviousTokenSeparator = false;
9814             var result = "";
9815             while (true) {
9816                 var ch = text.charCodeAt(pos);
9817                 if (ch === 95 /* _ */) {
9818                     tokenFlags |= 512 /* ContainsSeparator */;
9819                     if (allowSeparator) {
9820                         allowSeparator = false;
9821                         isPreviousTokenSeparator = true;
9822                         result += text.substring(start, pos);
9823                     }
9824                     else if (isPreviousTokenSeparator) {
9825                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9826                     }
9827                     else {
9828                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9829                     }
9830                     pos++;
9831                     start = pos;
9832                     continue;
9833                 }
9834                 if (isDigit(ch)) {
9835                     allowSeparator = true;
9836                     isPreviousTokenSeparator = false;
9837                     pos++;
9838                     continue;
9839                 }
9840                 break;
9841             }
9842             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9843                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9844             }
9845             return result + text.substring(start, pos);
9846         }
9847         function scanNumber() {
9848             var start = pos;
9849             var mainFragment = scanNumberFragment();
9850             var decimalFragment;
9851             var scientificFragment;
9852             if (text.charCodeAt(pos) === 46 /* dot */) {
9853                 pos++;
9854                 decimalFragment = scanNumberFragment();
9855             }
9856             var end = pos;
9857             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
9858                 pos++;
9859                 tokenFlags |= 16 /* Scientific */;
9860                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
9861                     pos++;
9862                 var preNumericPart = pos;
9863                 var finalFragment = scanNumberFragment();
9864                 if (!finalFragment) {
9865                     error(ts.Diagnostics.Digit_expected);
9866                 }
9867                 else {
9868                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
9869                     end = pos;
9870                 }
9871             }
9872             var result;
9873             if (tokenFlags & 512 /* ContainsSeparator */) {
9874                 result = mainFragment;
9875                 if (decimalFragment) {
9876                     result += "." + decimalFragment;
9877                 }
9878                 if (scientificFragment) {
9879                     result += scientificFragment;
9880                 }
9881             }
9882             else {
9883                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
9884             }
9885             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
9886                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
9887                 return {
9888                     type: 8 /* NumericLiteral */,
9889                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
9890                 };
9891             }
9892             else {
9893                 tokenValue = result;
9894                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
9895                 checkForIdentifierStartAfterNumericLiteral(start);
9896                 return { type: type, value: tokenValue };
9897             }
9898         }
9899         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
9900             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
9901                 return;
9902             }
9903             var identifierStart = pos;
9904             var length = scanIdentifierParts().length;
9905             if (length === 1 && text[identifierStart] === "n") {
9906                 if (isScientific) {
9907                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
9908                 }
9909                 else {
9910                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
9911                 }
9912             }
9913             else {
9914                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
9915                 pos = identifierStart;
9916             }
9917         }
9918         function scanOctalDigits() {
9919             var start = pos;
9920             while (isOctalDigit(text.charCodeAt(pos))) {
9921                 pos++;
9922             }
9923             return +(text.substring(start, pos));
9924         }
9925         /**
9926          * Scans the given number of hexadecimal digits in the text,
9927          * returning -1 if the given number is unavailable.
9928          */
9929         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
9930             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
9931             return valueString ? parseInt(valueString, 16) : -1;
9932         }
9933         /**
9934          * Scans as many hexadecimal digits as are available in the text,
9935          * returning "" if the given number of digits was unavailable.
9936          */
9937         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
9938             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
9939         }
9940         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
9941             var valueChars = [];
9942             var allowSeparator = false;
9943             var isPreviousTokenSeparator = false;
9944             while (valueChars.length < minCount || scanAsManyAsPossible) {
9945                 var ch = text.charCodeAt(pos);
9946                 if (canHaveSeparators && ch === 95 /* _ */) {
9947                     tokenFlags |= 512 /* ContainsSeparator */;
9948                     if (allowSeparator) {
9949                         allowSeparator = false;
9950                         isPreviousTokenSeparator = true;
9951                     }
9952                     else if (isPreviousTokenSeparator) {
9953                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9954                     }
9955                     else {
9956                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9957                     }
9958                     pos++;
9959                     continue;
9960                 }
9961                 allowSeparator = canHaveSeparators;
9962                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
9963                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
9964                 }
9965                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
9966                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
9967                     break;
9968                 }
9969                 valueChars.push(ch);
9970                 pos++;
9971                 isPreviousTokenSeparator = false;
9972             }
9973             if (valueChars.length < minCount) {
9974                 valueChars = [];
9975             }
9976             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9977                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9978             }
9979             return String.fromCharCode.apply(String, valueChars);
9980         }
9981         function scanString(jsxAttributeString) {
9982             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
9983             var quote = text.charCodeAt(pos);
9984             pos++;
9985             var result = "";
9986             var start = pos;
9987             while (true) {
9988                 if (pos >= end) {
9989                     result += text.substring(start, pos);
9990                     tokenFlags |= 4 /* Unterminated */;
9991                     error(ts.Diagnostics.Unterminated_string_literal);
9992                     break;
9993                 }
9994                 var ch = text.charCodeAt(pos);
9995                 if (ch === quote) {
9996                     result += text.substring(start, pos);
9997                     pos++;
9998                     break;
9999                 }
10000                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
10001                     result += text.substring(start, pos);
10002                     result += scanEscapeSequence();
10003                     start = pos;
10004                     continue;
10005                 }
10006                 if (isLineBreak(ch) && !jsxAttributeString) {
10007                     result += text.substring(start, pos);
10008                     tokenFlags |= 4 /* Unterminated */;
10009                     error(ts.Diagnostics.Unterminated_string_literal);
10010                     break;
10011                 }
10012                 pos++;
10013             }
10014             return result;
10015         }
10016         /**
10017          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
10018          * a literal component of a TemplateExpression.
10019          */
10020         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
10021             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
10022             pos++;
10023             var start = pos;
10024             var contents = "";
10025             var resultingToken;
10026             while (true) {
10027                 if (pos >= end) {
10028                     contents += text.substring(start, pos);
10029                     tokenFlags |= 4 /* Unterminated */;
10030                     error(ts.Diagnostics.Unterminated_template_literal);
10031                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
10032                     break;
10033                 }
10034                 var currChar = text.charCodeAt(pos);
10035                 // '`'
10036                 if (currChar === 96 /* backtick */) {
10037                     contents += text.substring(start, pos);
10038                     pos++;
10039                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
10040                     break;
10041                 }
10042                 // '${'
10043                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
10044                     contents += text.substring(start, pos);
10045                     pos += 2;
10046                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
10047                     break;
10048                 }
10049                 // Escape character
10050                 if (currChar === 92 /* backslash */) {
10051                     contents += text.substring(start, pos);
10052                     contents += scanEscapeSequence(isTaggedTemplate);
10053                     start = pos;
10054                     continue;
10055                 }
10056                 // Speculated ECMAScript 6 Spec 11.8.6.1:
10057                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
10058                 if (currChar === 13 /* carriageReturn */) {
10059                     contents += text.substring(start, pos);
10060                     pos++;
10061                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
10062                         pos++;
10063                     }
10064                     contents += "\n";
10065                     start = pos;
10066                     continue;
10067                 }
10068                 pos++;
10069             }
10070             ts.Debug.assert(resultingToken !== undefined);
10071             tokenValue = contents;
10072             return resultingToken;
10073         }
10074         function scanEscapeSequence(isTaggedTemplate) {
10075             var start = pos;
10076             pos++;
10077             if (pos >= end) {
10078                 error(ts.Diagnostics.Unexpected_end_of_text);
10079                 return "";
10080             }
10081             var ch = text.charCodeAt(pos);
10082             pos++;
10083             switch (ch) {
10084                 case 48 /* _0 */:
10085                     // '\01'
10086                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
10087                         pos++;
10088                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
10089                         return text.substring(start, pos);
10090                     }
10091                     return "\0";
10092                 case 98 /* b */:
10093                     return "\b";
10094                 case 116 /* t */:
10095                     return "\t";
10096                 case 110 /* n */:
10097                     return "\n";
10098                 case 118 /* v */:
10099                     return "\v";
10100                 case 102 /* f */:
10101                     return "\f";
10102                 case 114 /* r */:
10103                     return "\r";
10104                 case 39 /* singleQuote */:
10105                     return "\'";
10106                 case 34 /* doubleQuote */:
10107                     return "\"";
10108                 case 117 /* u */:
10109                     if (isTaggedTemplate) {
10110                         // '\u' or '\u0' or '\u00' or '\u000'
10111                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
10112                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
10113                                 pos = escapePos;
10114                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
10115                                 return text.substring(start, pos);
10116                             }
10117                         }
10118                     }
10119                     // '\u{DDDDDDDD}'
10120                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
10121                         pos++;
10122                         // '\u{'
10123                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
10124                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10125                             return text.substring(start, pos);
10126                         }
10127                         if (isTaggedTemplate) {
10128                             var savePos = pos;
10129                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10130                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10131                             // '\u{Not Code Point' or '\u{CodePoint'
10132                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
10133                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
10134                                 return text.substring(start, pos);
10135                             }
10136                             else {
10137                                 pos = savePos;
10138                             }
10139                         }
10140                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10141                         return scanExtendedUnicodeEscape();
10142                     }
10143                     tokenFlags |= 1024 /* UnicodeEscape */;
10144                     // '\uDDDD'
10145                     return scanHexadecimalEscape(/*numDigits*/ 4);
10146                 case 120 /* x */:
10147                     if (isTaggedTemplate) {
10148                         if (!isHexDigit(text.charCodeAt(pos))) {
10149                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10150                             return text.substring(start, pos);
10151                         }
10152                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
10153                             pos++;
10154                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10155                             return text.substring(start, pos);
10156                         }
10157                     }
10158                     // '\xDD'
10159                     return scanHexadecimalEscape(/*numDigits*/ 2);
10160                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
10161                 // the line terminator is interpreted to be "the empty code unit sequence".
10162                 case 13 /* carriageReturn */:
10163                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
10164                         pos++;
10165                     }
10166                 // falls through
10167                 case 10 /* lineFeed */:
10168                 case 8232 /* lineSeparator */:
10169                 case 8233 /* paragraphSeparator */:
10170                     return "";
10171                 default:
10172                     return String.fromCharCode(ch);
10173             }
10174         }
10175         function scanHexadecimalEscape(numDigits) {
10176             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
10177             if (escapedValue >= 0) {
10178                 return String.fromCharCode(escapedValue);
10179             }
10180             else {
10181                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10182                 return "";
10183             }
10184         }
10185         function scanExtendedUnicodeEscape() {
10186             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10187             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10188             var isInvalidExtendedEscape = false;
10189             // Validate the value of the digit
10190             if (escapedValue < 0) {
10191                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10192                 isInvalidExtendedEscape = true;
10193             }
10194             else if (escapedValue > 0x10FFFF) {
10195                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
10196                 isInvalidExtendedEscape = true;
10197             }
10198             if (pos >= end) {
10199                 error(ts.Diagnostics.Unexpected_end_of_text);
10200                 isInvalidExtendedEscape = true;
10201             }
10202             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
10203                 // Only swallow the following character up if it's a '}'.
10204                 pos++;
10205             }
10206             else {
10207                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
10208                 isInvalidExtendedEscape = true;
10209             }
10210             if (isInvalidExtendedEscape) {
10211                 return "";
10212             }
10213             return utf16EncodeAsString(escapedValue);
10214         }
10215         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
10216         // and return code point value if valid Unicode escape is found. Otherwise return -1.
10217         function peekUnicodeEscape() {
10218             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
10219                 var start_1 = pos;
10220                 pos += 2;
10221                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
10222                 pos = start_1;
10223                 return value;
10224             }
10225             return -1;
10226         }
10227         function peekExtendedUnicodeEscape() {
10228             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
10229                 var start_2 = pos;
10230                 pos += 3;
10231                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10232                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10233                 pos = start_2;
10234                 return escapedValue;
10235             }
10236             return -1;
10237         }
10238         function scanIdentifierParts() {
10239             var result = "";
10240             var start = pos;
10241             while (pos < end) {
10242                 var ch = codePointAt(text, pos);
10243                 if (isIdentifierPart(ch, languageVersion)) {
10244                     pos += charSize(ch);
10245                 }
10246                 else if (ch === 92 /* backslash */) {
10247                     ch = peekExtendedUnicodeEscape();
10248                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
10249                         pos += 3;
10250                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10251                         result += scanExtendedUnicodeEscape();
10252                         start = pos;
10253                         continue;
10254                     }
10255                     ch = peekUnicodeEscape();
10256                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
10257                         break;
10258                     }
10259                     tokenFlags |= 1024 /* UnicodeEscape */;
10260                     result += text.substring(start, pos);
10261                     result += utf16EncodeAsString(ch);
10262                     // Valid Unicode escape is always six characters
10263                     pos += 6;
10264                     start = pos;
10265                 }
10266                 else {
10267                     break;
10268                 }
10269             }
10270             result += text.substring(start, pos);
10271             return result;
10272         }
10273         function getIdentifierToken() {
10274             // Reserved words are between 2 and 12 characters long and start with a lowercase letter
10275             var len = tokenValue.length;
10276             if (len >= 2 && len <= 12) {
10277                 var ch = tokenValue.charCodeAt(0);
10278                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
10279                     var keyword = textToKeyword.get(tokenValue);
10280                     if (keyword !== undefined) {
10281                         return token = keyword;
10282                     }
10283                 }
10284             }
10285             return token = 78 /* Identifier */;
10286         }
10287         function scanBinaryOrOctalDigits(base) {
10288             var value = "";
10289             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
10290             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
10291             var separatorAllowed = false;
10292             var isPreviousTokenSeparator = false;
10293             while (true) {
10294                 var ch = text.charCodeAt(pos);
10295                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
10296                 if (ch === 95 /* _ */) {
10297                     tokenFlags |= 512 /* ContainsSeparator */;
10298                     if (separatorAllowed) {
10299                         separatorAllowed = false;
10300                         isPreviousTokenSeparator = true;
10301                     }
10302                     else if (isPreviousTokenSeparator) {
10303                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
10304                     }
10305                     else {
10306                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
10307                     }
10308                     pos++;
10309                     continue;
10310                 }
10311                 separatorAllowed = true;
10312                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
10313                     break;
10314                 }
10315                 value += text[pos];
10316                 pos++;
10317                 isPreviousTokenSeparator = false;
10318             }
10319             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
10320                 // Literal ends with underscore - not allowed
10321                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
10322             }
10323             return value;
10324         }
10325         function checkBigIntSuffix() {
10326             if (text.charCodeAt(pos) === 110 /* n */) {
10327                 tokenValue += "n";
10328                 // Use base 10 instead of base 2 or base 8 for shorter literals
10329                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
10330                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
10331                 }
10332                 pos++;
10333                 return 9 /* BigIntLiteral */;
10334             }
10335             else { // not a bigint, so can convert to number in simplified form
10336                 // Number() may not support 0b or 0o, so use parseInt() instead
10337                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
10338                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
10339                     : tokenFlags & 256 /* OctalSpecifier */
10340                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
10341                         : +tokenValue;
10342                 tokenValue = "" + numericValue;
10343                 return 8 /* NumericLiteral */;
10344             }
10345         }
10346         function scan() {
10347             var _a;
10348             startPos = pos;
10349             tokenFlags = 0 /* None */;
10350             var asteriskSeen = false;
10351             while (true) {
10352                 tokenPos = pos;
10353                 if (pos >= end) {
10354                     return token = 1 /* EndOfFileToken */;
10355                 }
10356                 var ch = codePointAt(text, pos);
10357                 // Special handling for shebang
10358                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
10359                     pos = scanShebangTrivia(text, pos);
10360                     if (skipTrivia) {
10361                         continue;
10362                     }
10363                     else {
10364                         return token = 6 /* ShebangTrivia */;
10365                     }
10366                 }
10367                 switch (ch) {
10368                     case 10 /* lineFeed */:
10369                     case 13 /* carriageReturn */:
10370                         tokenFlags |= 1 /* PrecedingLineBreak */;
10371                         if (skipTrivia) {
10372                             pos++;
10373                             continue;
10374                         }
10375                         else {
10376                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
10377                                 // consume both CR and LF
10378                                 pos += 2;
10379                             }
10380                             else {
10381                                 pos++;
10382                             }
10383                             return token = 4 /* NewLineTrivia */;
10384                         }
10385                     case 9 /* tab */:
10386                     case 11 /* verticalTab */:
10387                     case 12 /* formFeed */:
10388                     case 32 /* space */:
10389                     case 160 /* nonBreakingSpace */:
10390                     case 5760 /* ogham */:
10391                     case 8192 /* enQuad */:
10392                     case 8193 /* emQuad */:
10393                     case 8194 /* enSpace */:
10394                     case 8195 /* emSpace */:
10395                     case 8196 /* threePerEmSpace */:
10396                     case 8197 /* fourPerEmSpace */:
10397                     case 8198 /* sixPerEmSpace */:
10398                     case 8199 /* figureSpace */:
10399                     case 8200 /* punctuationSpace */:
10400                     case 8201 /* thinSpace */:
10401                     case 8202 /* hairSpace */:
10402                     case 8203 /* zeroWidthSpace */:
10403                     case 8239 /* narrowNoBreakSpace */:
10404                     case 8287 /* mathematicalSpace */:
10405                     case 12288 /* ideographicSpace */:
10406                     case 65279 /* byteOrderMark */:
10407                         if (skipTrivia) {
10408                             pos++;
10409                             continue;
10410                         }
10411                         else {
10412                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10413                                 pos++;
10414                             }
10415                             return token = 5 /* WhitespaceTrivia */;
10416                         }
10417                     case 33 /* exclamation */:
10418                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10419                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10420                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
10421                             }
10422                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
10423                         }
10424                         pos++;
10425                         return token = 53 /* ExclamationToken */;
10426                     case 34 /* doubleQuote */:
10427                     case 39 /* singleQuote */:
10428                         tokenValue = scanString();
10429                         return token = 10 /* StringLiteral */;
10430                     case 96 /* backtick */:
10431                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
10432                     case 37 /* percent */:
10433                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10434                             return pos += 2, token = 68 /* PercentEqualsToken */;
10435                         }
10436                         pos++;
10437                         return token = 44 /* PercentToken */;
10438                     case 38 /* ampersand */:
10439                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
10440                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10441                                 return pos += 3, token = 75 /* AmpersandAmpersandEqualsToken */;
10442                             }
10443                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
10444                         }
10445                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10446                             return pos += 2, token = 72 /* AmpersandEqualsToken */;
10447                         }
10448                         pos++;
10449                         return token = 50 /* AmpersandToken */;
10450                     case 40 /* openParen */:
10451                         pos++;
10452                         return token = 20 /* OpenParenToken */;
10453                     case 41 /* closeParen */:
10454                         pos++;
10455                         return token = 21 /* CloseParenToken */;
10456                     case 42 /* asterisk */:
10457                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10458                             return pos += 2, token = 65 /* AsteriskEqualsToken */;
10459                         }
10460                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
10461                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10462                                 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
10463                             }
10464                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
10465                         }
10466                         pos++;
10467                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
10468                             // decoration at the start of a JSDoc comment line
10469                             asteriskSeen = true;
10470                             continue;
10471                         }
10472                         return token = 41 /* AsteriskToken */;
10473                     case 43 /* plus */:
10474                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
10475                             return pos += 2, token = 45 /* PlusPlusToken */;
10476                         }
10477                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10478                             return pos += 2, token = 63 /* PlusEqualsToken */;
10479                         }
10480                         pos++;
10481                         return token = 39 /* PlusToken */;
10482                     case 44 /* comma */:
10483                         pos++;
10484                         return token = 27 /* CommaToken */;
10485                     case 45 /* minus */:
10486                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
10487                             return pos += 2, token = 46 /* MinusMinusToken */;
10488                         }
10489                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10490                             return pos += 2, token = 64 /* MinusEqualsToken */;
10491                         }
10492                         pos++;
10493                         return token = 40 /* MinusToken */;
10494                     case 46 /* dot */:
10495                         if (isDigit(text.charCodeAt(pos + 1))) {
10496                             tokenValue = scanNumber().value;
10497                             return token = 8 /* NumericLiteral */;
10498                         }
10499                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
10500                             return pos += 3, token = 25 /* DotDotDotToken */;
10501                         }
10502                         pos++;
10503                         return token = 24 /* DotToken */;
10504                     case 47 /* slash */:
10505                         // Single-line comment
10506                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10507                             pos += 2;
10508                             while (pos < end) {
10509                                 if (isLineBreak(text.charCodeAt(pos))) {
10510                                     break;
10511                                 }
10512                                 pos++;
10513                             }
10514                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
10515                             if (skipTrivia) {
10516                                 continue;
10517                             }
10518                             else {
10519                                 return token = 2 /* SingleLineCommentTrivia */;
10520                             }
10521                         }
10522                         // Multi-line comment
10523                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
10524                             pos += 2;
10525                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
10526                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
10527                             }
10528                             var commentClosed = false;
10529                             var lastLineStart = tokenPos;
10530                             while (pos < end) {
10531                                 var ch_1 = text.charCodeAt(pos);
10532                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
10533                                     pos += 2;
10534                                     commentClosed = true;
10535                                     break;
10536                                 }
10537                                 pos++;
10538                                 if (isLineBreak(ch_1)) {
10539                                     lastLineStart = pos;
10540                                     tokenFlags |= 1 /* PrecedingLineBreak */;
10541                                 }
10542                             }
10543                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
10544                             if (!commentClosed) {
10545                                 error(ts.Diagnostics.Asterisk_Slash_expected);
10546                             }
10547                             if (skipTrivia) {
10548                                 continue;
10549                             }
10550                             else {
10551                                 if (!commentClosed) {
10552                                     tokenFlags |= 4 /* Unterminated */;
10553                                 }
10554                                 return token = 3 /* MultiLineCommentTrivia */;
10555                             }
10556                         }
10557                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10558                             return pos += 2, token = 67 /* SlashEqualsToken */;
10559                         }
10560                         pos++;
10561                         return token = 43 /* SlashToken */;
10562                     case 48 /* _0 */:
10563                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
10564                             pos += 2;
10565                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
10566                             if (!tokenValue) {
10567                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10568                                 tokenValue = "0";
10569                             }
10570                             tokenValue = "0x" + tokenValue;
10571                             tokenFlags |= 64 /* HexSpecifier */;
10572                             return token = checkBigIntSuffix();
10573                         }
10574                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
10575                             pos += 2;
10576                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
10577                             if (!tokenValue) {
10578                                 error(ts.Diagnostics.Binary_digit_expected);
10579                                 tokenValue = "0";
10580                             }
10581                             tokenValue = "0b" + tokenValue;
10582                             tokenFlags |= 128 /* BinarySpecifier */;
10583                             return token = checkBigIntSuffix();
10584                         }
10585                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
10586                             pos += 2;
10587                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
10588                             if (!tokenValue) {
10589                                 error(ts.Diagnostics.Octal_digit_expected);
10590                                 tokenValue = "0";
10591                             }
10592                             tokenValue = "0o" + tokenValue;
10593                             tokenFlags |= 256 /* OctalSpecifier */;
10594                             return token = checkBigIntSuffix();
10595                         }
10596                         // Try to parse as an octal
10597                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
10598                             tokenValue = "" + scanOctalDigits();
10599                             tokenFlags |= 32 /* Octal */;
10600                             return token = 8 /* NumericLiteral */;
10601                         }
10602                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
10603                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
10604                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
10605                     // falls through
10606                     case 49 /* _1 */:
10607                     case 50 /* _2 */:
10608                     case 51 /* _3 */:
10609                     case 52 /* _4 */:
10610                     case 53 /* _5 */:
10611                     case 54 /* _6 */:
10612                     case 55 /* _7 */:
10613                     case 56 /* _8 */:
10614                     case 57 /* _9 */:
10615                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
10616                         return token;
10617                     case 58 /* colon */:
10618                         pos++;
10619                         return token = 58 /* ColonToken */;
10620                     case 59 /* semicolon */:
10621                         pos++;
10622                         return token = 26 /* SemicolonToken */;
10623                     case 60 /* lessThan */:
10624                         if (isConflictMarkerTrivia(text, pos)) {
10625                             pos = scanConflictMarkerTrivia(text, pos, error);
10626                             if (skipTrivia) {
10627                                 continue;
10628                             }
10629                             else {
10630                                 return token = 7 /* ConflictMarkerTrivia */;
10631                             }
10632                         }
10633                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
10634                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10635                                 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
10636                             }
10637                             return pos += 2, token = 47 /* LessThanLessThanToken */;
10638                         }
10639                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10640                             return pos += 2, token = 32 /* LessThanEqualsToken */;
10641                         }
10642                         if (languageVariant === 1 /* JSX */ &&
10643                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
10644                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
10645                             return pos += 2, token = 30 /* LessThanSlashToken */;
10646                         }
10647                         pos++;
10648                         return token = 29 /* LessThanToken */;
10649                     case 61 /* equals */:
10650                         if (isConflictMarkerTrivia(text, pos)) {
10651                             pos = scanConflictMarkerTrivia(text, pos, error);
10652                             if (skipTrivia) {
10653                                 continue;
10654                             }
10655                             else {
10656                                 return token = 7 /* ConflictMarkerTrivia */;
10657                             }
10658                         }
10659                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10660                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10661                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
10662                             }
10663                             return pos += 2, token = 34 /* EqualsEqualsToken */;
10664                         }
10665                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
10666                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
10667                         }
10668                         pos++;
10669                         return token = 62 /* EqualsToken */;
10670                     case 62 /* greaterThan */:
10671                         if (isConflictMarkerTrivia(text, pos)) {
10672                             pos = scanConflictMarkerTrivia(text, pos, error);
10673                             if (skipTrivia) {
10674                                 continue;
10675                             }
10676                             else {
10677                                 return token = 7 /* ConflictMarkerTrivia */;
10678                             }
10679                         }
10680                         pos++;
10681                         return token = 31 /* GreaterThanToken */;
10682                     case 63 /* question */:
10683                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) {
10684                             return pos += 2, token = 28 /* QuestionDotToken */;
10685                         }
10686                         if (text.charCodeAt(pos + 1) === 63 /* question */) {
10687                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10688                                 return pos += 3, token = 76 /* QuestionQuestionEqualsToken */;
10689                             }
10690                             return pos += 2, token = 60 /* QuestionQuestionToken */;
10691                         }
10692                         pos++;
10693                         return token = 57 /* QuestionToken */;
10694                     case 91 /* openBracket */:
10695                         pos++;
10696                         return token = 22 /* OpenBracketToken */;
10697                     case 93 /* closeBracket */:
10698                         pos++;
10699                         return token = 23 /* CloseBracketToken */;
10700                     case 94 /* caret */:
10701                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10702                             return pos += 2, token = 77 /* CaretEqualsToken */;
10703                         }
10704                         pos++;
10705                         return token = 52 /* CaretToken */;
10706                     case 123 /* openBrace */:
10707                         pos++;
10708                         return token = 18 /* OpenBraceToken */;
10709                     case 124 /* bar */:
10710                         if (isConflictMarkerTrivia(text, pos)) {
10711                             pos = scanConflictMarkerTrivia(text, pos, error);
10712                             if (skipTrivia) {
10713                                 continue;
10714                             }
10715                             else {
10716                                 return token = 7 /* ConflictMarkerTrivia */;
10717                             }
10718                         }
10719                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
10720                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10721                                 return pos += 3, token = 74 /* BarBarEqualsToken */;
10722                             }
10723                             return pos += 2, token = 56 /* BarBarToken */;
10724                         }
10725                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10726                             return pos += 2, token = 73 /* BarEqualsToken */;
10727                         }
10728                         pos++;
10729                         return token = 51 /* BarToken */;
10730                     case 125 /* closeBrace */:
10731                         pos++;
10732                         return token = 19 /* CloseBraceToken */;
10733                     case 126 /* tilde */:
10734                         pos++;
10735                         return token = 54 /* TildeToken */;
10736                     case 64 /* at */:
10737                         pos++;
10738                         return token = 59 /* AtToken */;
10739                     case 92 /* backslash */:
10740                         var extendedCookedChar = peekExtendedUnicodeEscape();
10741                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10742                             pos += 3;
10743                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10744                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10745                             return token = getIdentifierToken();
10746                         }
10747                         var cookedChar = peekUnicodeEscape();
10748                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10749                             pos += 6;
10750                             tokenFlags |= 1024 /* UnicodeEscape */;
10751                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10752                             return token = getIdentifierToken();
10753                         }
10754                         error(ts.Diagnostics.Invalid_character);
10755                         pos++;
10756                         return token = 0 /* Unknown */;
10757                     case 35 /* hash */:
10758                         if (pos !== 0 && text[pos + 1] === "!") {
10759                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
10760                             pos++;
10761                             return token = 0 /* Unknown */;
10762                         }
10763                         pos++;
10764                         if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
10765                             pos++;
10766                             while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
10767                                 pos++;
10768                             tokenValue = text.substring(tokenPos, pos);
10769                             if (ch === 92 /* backslash */) {
10770                                 tokenValue += scanIdentifierParts();
10771                             }
10772                         }
10773                         else {
10774                             tokenValue = "#";
10775                             error(ts.Diagnostics.Invalid_character);
10776                         }
10777                         return token = 79 /* PrivateIdentifier */;
10778                     default:
10779                         if (isIdentifierStart(ch, languageVersion)) {
10780                             pos += charSize(ch);
10781                             while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
10782                                 pos += charSize(ch);
10783                             tokenValue = text.substring(tokenPos, pos);
10784                             if (ch === 92 /* backslash */) {
10785                                 tokenValue += scanIdentifierParts();
10786                             }
10787                             return token = getIdentifierToken();
10788                         }
10789                         else if (isWhiteSpaceSingleLine(ch)) {
10790                             pos += charSize(ch);
10791                             continue;
10792                         }
10793                         else if (isLineBreak(ch)) {
10794                             tokenFlags |= 1 /* PrecedingLineBreak */;
10795                             pos += charSize(ch);
10796                             continue;
10797                         }
10798                         error(ts.Diagnostics.Invalid_character);
10799                         pos += charSize(ch);
10800                         return token = 0 /* Unknown */;
10801                 }
10802             }
10803         }
10804         function reScanGreaterToken() {
10805             if (token === 31 /* GreaterThanToken */) {
10806                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
10807                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
10808                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10809                             return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
10810                         }
10811                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
10812                     }
10813                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10814                         return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
10815                     }
10816                     pos++;
10817                     return token = 48 /* GreaterThanGreaterThanToken */;
10818                 }
10819                 if (text.charCodeAt(pos) === 61 /* equals */) {
10820                     pos++;
10821                     return token = 33 /* GreaterThanEqualsToken */;
10822                 }
10823             }
10824             return token;
10825         }
10826         function reScanAsteriskEqualsToken() {
10827             ts.Debug.assert(token === 65 /* AsteriskEqualsToken */, "'reScanAsteriskEqualsToken' should only be called on a '*='");
10828             pos = tokenPos + 1;
10829             return token = 62 /* EqualsToken */;
10830         }
10831         function reScanSlashToken() {
10832             if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
10833                 var p = tokenPos + 1;
10834                 var inEscape = false;
10835                 var inCharacterClass = false;
10836                 while (true) {
10837                     // If we reach the end of a file, or hit a newline, then this is an unterminated
10838                     // regex.  Report error and return what we have so far.
10839                     if (p >= end) {
10840                         tokenFlags |= 4 /* Unterminated */;
10841                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
10842                         break;
10843                     }
10844                     var ch = text.charCodeAt(p);
10845                     if (isLineBreak(ch)) {
10846                         tokenFlags |= 4 /* Unterminated */;
10847                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
10848                         break;
10849                     }
10850                     if (inEscape) {
10851                         // Parsing an escape character;
10852                         // reset the flag and just advance to the next char.
10853                         inEscape = false;
10854                     }
10855                     else if (ch === 47 /* slash */ && !inCharacterClass) {
10856                         // A slash within a character class is permissible,
10857                         // but in general it signals the end of the regexp literal.
10858                         p++;
10859                         break;
10860                     }
10861                     else if (ch === 91 /* openBracket */) {
10862                         inCharacterClass = true;
10863                     }
10864                     else if (ch === 92 /* backslash */) {
10865                         inEscape = true;
10866                     }
10867                     else if (ch === 93 /* closeBracket */) {
10868                         inCharacterClass = false;
10869                     }
10870                     p++;
10871                 }
10872                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
10873                     p++;
10874                 }
10875                 pos = p;
10876                 tokenValue = text.substring(tokenPos, pos);
10877                 token = 13 /* RegularExpressionLiteral */;
10878             }
10879             return token;
10880         }
10881         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
10882             var type = getDirectiveFromComment(text, commentDirectiveRegEx);
10883             if (type === undefined) {
10884                 return commentDirectives;
10885             }
10886             return ts.append(commentDirectives, {
10887                 range: { pos: lineStart, end: pos },
10888                 type: type,
10889             });
10890         }
10891         function getDirectiveFromComment(text, commentDirectiveRegEx) {
10892             var match = commentDirectiveRegEx.exec(text);
10893             if (!match) {
10894                 return undefined;
10895             }
10896             switch (match[1]) {
10897                 case "ts-expect-error":
10898                     return 0 /* ExpectError */;
10899                 case "ts-ignore":
10900                     return 1 /* Ignore */;
10901             }
10902             return undefined;
10903         }
10904         /**
10905          * Unconditionally back up and scan a template expression portion.
10906          */
10907         function reScanTemplateToken(isTaggedTemplate) {
10908             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
10909             pos = tokenPos;
10910             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
10911         }
10912         function reScanTemplateHeadOrNoSubstitutionTemplate() {
10913             pos = tokenPos;
10914             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
10915         }
10916         function reScanJsxToken() {
10917             pos = tokenPos = startPos;
10918             return token = scanJsxToken();
10919         }
10920         function reScanLessThanToken() {
10921             if (token === 47 /* LessThanLessThanToken */) {
10922                 pos = tokenPos + 1;
10923                 return token = 29 /* LessThanToken */;
10924             }
10925             return token;
10926         }
10927         function reScanQuestionToken() {
10928             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
10929             pos = tokenPos + 1;
10930             return token = 57 /* QuestionToken */;
10931         }
10932         function scanJsxToken() {
10933             startPos = tokenPos = pos;
10934             if (pos >= end) {
10935                 return token = 1 /* EndOfFileToken */;
10936             }
10937             var char = text.charCodeAt(pos);
10938             if (char === 60 /* lessThan */) {
10939                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10940                     pos += 2;
10941                     return token = 30 /* LessThanSlashToken */;
10942                 }
10943                 pos++;
10944                 return token = 29 /* LessThanToken */;
10945             }
10946             if (char === 123 /* openBrace */) {
10947                 pos++;
10948                 return token = 18 /* OpenBraceToken */;
10949             }
10950             // First non-whitespace character on this line.
10951             var firstNonWhitespace = 0;
10952             var lastNonWhitespace = -1;
10953             // These initial values are special because the first line is:
10954             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
10955             while (pos < end) {
10956                 // We want to keep track of the last non-whitespace (but including
10957                 // newlines character for hitting the end of the JSX Text region)
10958                 if (!isWhiteSpaceSingleLine(char)) {
10959                     lastNonWhitespace = pos;
10960                 }
10961                 char = text.charCodeAt(pos);
10962                 if (char === 123 /* openBrace */) {
10963                     break;
10964                 }
10965                 if (char === 60 /* lessThan */) {
10966                     if (isConflictMarkerTrivia(text, pos)) {
10967                         pos = scanConflictMarkerTrivia(text, pos, error);
10968                         return token = 7 /* ConflictMarkerTrivia */;
10969                     }
10970                     break;
10971                 }
10972                 if (char === 62 /* greaterThan */) {
10973                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
10974                 }
10975                 if (char === 125 /* closeBrace */) {
10976                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
10977                 }
10978                 if (lastNonWhitespace > 0)
10979                     lastNonWhitespace++;
10980                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
10981                 // i.e (- : whitespace)
10982                 //      <div>----
10983                 //      </div> becomes <div></div>
10984                 //
10985                 //      <div>----</div> becomes <div>----</div>
10986                 if (isLineBreak(char) && firstNonWhitespace === 0) {
10987                     firstNonWhitespace = -1;
10988                 }
10989                 else if (!isWhiteSpaceLike(char)) {
10990                     firstNonWhitespace = pos;
10991                 }
10992                 pos++;
10993             }
10994             var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
10995             tokenValue = text.substring(startPos, endPosition);
10996             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
10997         }
10998         // Scans a JSX identifier; these differ from normal identifiers in that
10999         // they allow dashes
11000         function scanJsxIdentifier() {
11001             if (tokenIsIdentifierOrKeyword(token)) {
11002                 // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
11003                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
11004                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
11005                 while (pos < end) {
11006                     var ch = text.charCodeAt(pos);
11007                     if (ch === 45 /* minus */) {
11008                         tokenValue += "-";
11009                         pos++;
11010                         continue;
11011                     }
11012                     var oldPos = pos;
11013                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
11014                     if (pos === oldPos) {
11015                         break;
11016                     }
11017                 }
11018             }
11019             return token;
11020         }
11021         function scanJsxAttributeValue() {
11022             startPos = pos;
11023             switch (text.charCodeAt(pos)) {
11024                 case 34 /* doubleQuote */:
11025                 case 39 /* singleQuote */:
11026                     tokenValue = scanString(/*jsxAttributeString*/ true);
11027                     return token = 10 /* StringLiteral */;
11028                 default:
11029                     // If this scans anything other than `{`, it's a parse error.
11030                     return scan();
11031             }
11032         }
11033         function reScanJsxAttributeValue() {
11034             pos = tokenPos = startPos;
11035             return scanJsxAttributeValue();
11036         }
11037         function scanJsDocToken() {
11038             startPos = tokenPos = pos;
11039             tokenFlags = 0 /* None */;
11040             if (pos >= end) {
11041                 return token = 1 /* EndOfFileToken */;
11042             }
11043             var ch = codePointAt(text, pos);
11044             pos += charSize(ch);
11045             switch (ch) {
11046                 case 9 /* tab */:
11047                 case 11 /* verticalTab */:
11048                 case 12 /* formFeed */:
11049                 case 32 /* space */:
11050                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
11051                         pos++;
11052                     }
11053                     return token = 5 /* WhitespaceTrivia */;
11054                 case 64 /* at */:
11055                     return token = 59 /* AtToken */;
11056                 case 13 /* carriageReturn */:
11057                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
11058                         pos++;
11059                     }
11060                 // falls through
11061                 case 10 /* lineFeed */:
11062                     tokenFlags |= 1 /* PrecedingLineBreak */;
11063                     return token = 4 /* NewLineTrivia */;
11064                 case 42 /* asterisk */:
11065                     return token = 41 /* AsteriskToken */;
11066                 case 123 /* openBrace */:
11067                     return token = 18 /* OpenBraceToken */;
11068                 case 125 /* closeBrace */:
11069                     return token = 19 /* CloseBraceToken */;
11070                 case 91 /* openBracket */:
11071                     return token = 22 /* OpenBracketToken */;
11072                 case 93 /* closeBracket */:
11073                     return token = 23 /* CloseBracketToken */;
11074                 case 60 /* lessThan */:
11075                     return token = 29 /* LessThanToken */;
11076                 case 62 /* greaterThan */:
11077                     return token = 31 /* GreaterThanToken */;
11078                 case 61 /* equals */:
11079                     return token = 62 /* EqualsToken */;
11080                 case 44 /* comma */:
11081                     return token = 27 /* CommaToken */;
11082                 case 46 /* dot */:
11083                     return token = 24 /* DotToken */;
11084                 case 96 /* backtick */:
11085                     return token = 61 /* BacktickToken */;
11086                 case 92 /* backslash */:
11087                     pos--;
11088                     var extendedCookedChar = peekExtendedUnicodeEscape();
11089                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
11090                         pos += 3;
11091                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
11092                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
11093                         return token = getIdentifierToken();
11094                     }
11095                     var cookedChar = peekUnicodeEscape();
11096                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
11097                         pos += 6;
11098                         tokenFlags |= 1024 /* UnicodeEscape */;
11099                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
11100                         return token = getIdentifierToken();
11101                     }
11102                     pos++;
11103                     return token = 0 /* Unknown */;
11104             }
11105             if (isIdentifierStart(ch, languageVersion)) {
11106                 var char = ch;
11107                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
11108                     pos += charSize(char);
11109                 tokenValue = text.substring(tokenPos, pos);
11110                 if (char === 92 /* backslash */) {
11111                     tokenValue += scanIdentifierParts();
11112                 }
11113                 return token = getIdentifierToken();
11114             }
11115             else {
11116                 return token = 0 /* Unknown */;
11117             }
11118         }
11119         function speculationHelper(callback, isLookahead) {
11120             var savePos = pos;
11121             var saveStartPos = startPos;
11122             var saveTokenPos = tokenPos;
11123             var saveToken = token;
11124             var saveTokenValue = tokenValue;
11125             var saveTokenFlags = tokenFlags;
11126             var result = callback();
11127             // If our callback returned something 'falsy' or we're just looking ahead,
11128             // then unconditionally restore us to where we were.
11129             if (!result || isLookahead) {
11130                 pos = savePos;
11131                 startPos = saveStartPos;
11132                 tokenPos = saveTokenPos;
11133                 token = saveToken;
11134                 tokenValue = saveTokenValue;
11135                 tokenFlags = saveTokenFlags;
11136             }
11137             return result;
11138         }
11139         function scanRange(start, length, callback) {
11140             var saveEnd = end;
11141             var savePos = pos;
11142             var saveStartPos = startPos;
11143             var saveTokenPos = tokenPos;
11144             var saveToken = token;
11145             var saveTokenValue = tokenValue;
11146             var saveTokenFlags = tokenFlags;
11147             var saveErrorExpectations = commentDirectives;
11148             setText(text, start, length);
11149             var result = callback();
11150             end = saveEnd;
11151             pos = savePos;
11152             startPos = saveStartPos;
11153             tokenPos = saveTokenPos;
11154             token = saveToken;
11155             tokenValue = saveTokenValue;
11156             tokenFlags = saveTokenFlags;
11157             commentDirectives = saveErrorExpectations;
11158             return result;
11159         }
11160         function lookAhead(callback) {
11161             return speculationHelper(callback, /*isLookahead*/ true);
11162         }
11163         function tryScan(callback) {
11164             return speculationHelper(callback, /*isLookahead*/ false);
11165         }
11166         function getText() {
11167             return text;
11168         }
11169         function clearCommentDirectives() {
11170             commentDirectives = undefined;
11171         }
11172         function setText(newText, start, length) {
11173             text = newText || "";
11174             end = length === undefined ? text.length : start + length;
11175             setTextPos(start || 0);
11176         }
11177         function setOnError(errorCallback) {
11178             onError = errorCallback;
11179         }
11180         function setScriptTarget(scriptTarget) {
11181             languageVersion = scriptTarget;
11182         }
11183         function setLanguageVariant(variant) {
11184             languageVariant = variant;
11185         }
11186         function setTextPos(textPos) {
11187             ts.Debug.assert(textPos >= 0);
11188             pos = textPos;
11189             startPos = textPos;
11190             tokenPos = textPos;
11191             token = 0 /* Unknown */;
11192             tokenValue = undefined;
11193             tokenFlags = 0 /* None */;
11194         }
11195         function setInJSDocType(inType) {
11196             inJSDocType += inType ? 1 : -1;
11197         }
11198     }
11199     ts.createScanner = createScanner;
11200     /* @internal */
11201     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
11202         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
11203         var size = str.length;
11204         // Account for out-of-bounds indices:
11205         if (i < 0 || i >= size) {
11206             return undefined; // String.codePointAt returns `undefined` for OOB indexes
11207         }
11208         // Get the first code unit
11209         var first = str.charCodeAt(i);
11210         // check if it’s the start of a surrogate pair
11211         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
11212             var second = str.charCodeAt(i + 1);
11213             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
11214                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
11215                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
11216             }
11217         }
11218         return first;
11219     };
11220     /* @internal */
11221     function charSize(ch) {
11222         if (ch >= 0x10000) {
11223             return 2;
11224         }
11225         return 1;
11226     }
11227     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
11228     function utf16EncodeAsStringFallback(codePoint) {
11229         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
11230         if (codePoint <= 65535) {
11231             return String.fromCharCode(codePoint);
11232         }
11233         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
11234         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
11235         return String.fromCharCode(codeUnit1, codeUnit2);
11236     }
11237     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
11238     /* @internal */
11239     function utf16EncodeAsString(codePoint) {
11240         return utf16EncodeAsStringWorker(codePoint);
11241     }
11242     ts.utf16EncodeAsString = utf16EncodeAsString;
11243 })(ts || (ts = {}));
11244 var ts;
11245 (function (ts) {
11246     function isExternalModuleNameRelative(moduleName) {
11247         // TypeScript 1.0 spec (April 2014): 11.2.1
11248         // An external module name is "relative" if the first term is "." or "..".
11249         // 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.
11250         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
11251     }
11252     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
11253     function sortAndDeduplicateDiagnostics(diagnostics) {
11254         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
11255     }
11256     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
11257     function getDefaultLibFileName(options) {
11258         switch (options.target) {
11259             case 99 /* ESNext */:
11260                 return "lib.esnext.full.d.ts";
11261             case 7 /* ES2020 */:
11262                 return "lib.es2020.full.d.ts";
11263             case 6 /* ES2019 */:
11264                 return "lib.es2019.full.d.ts";
11265             case 5 /* ES2018 */:
11266                 return "lib.es2018.full.d.ts";
11267             case 4 /* ES2017 */:
11268                 return "lib.es2017.full.d.ts";
11269             case 3 /* ES2016 */:
11270                 return "lib.es2016.full.d.ts";
11271             case 2 /* ES2015 */:
11272                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
11273             default:
11274                 return "lib.d.ts";
11275         }
11276     }
11277     ts.getDefaultLibFileName = getDefaultLibFileName;
11278     function textSpanEnd(span) {
11279         return span.start + span.length;
11280     }
11281     ts.textSpanEnd = textSpanEnd;
11282     function textSpanIsEmpty(span) {
11283         return span.length === 0;
11284     }
11285     ts.textSpanIsEmpty = textSpanIsEmpty;
11286     function textSpanContainsPosition(span, position) {
11287         return position >= span.start && position < textSpanEnd(span);
11288     }
11289     ts.textSpanContainsPosition = textSpanContainsPosition;
11290     /* @internal */
11291     function textRangeContainsPositionInclusive(span, position) {
11292         return position >= span.pos && position <= span.end;
11293     }
11294     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
11295     // Returns true if 'span' contains 'other'.
11296     function textSpanContainsTextSpan(span, other) {
11297         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
11298     }
11299     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
11300     function textSpanOverlapsWith(span, other) {
11301         return textSpanOverlap(span, other) !== undefined;
11302     }
11303     ts.textSpanOverlapsWith = textSpanOverlapsWith;
11304     function textSpanOverlap(span1, span2) {
11305         var overlap = textSpanIntersection(span1, span2);
11306         return overlap && overlap.length === 0 ? undefined : overlap;
11307     }
11308     ts.textSpanOverlap = textSpanOverlap;
11309     function textSpanIntersectsWithTextSpan(span, other) {
11310         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
11311     }
11312     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
11313     function textSpanIntersectsWith(span, start, length) {
11314         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
11315     }
11316     ts.textSpanIntersectsWith = textSpanIntersectsWith;
11317     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
11318         var end1 = start1 + length1;
11319         var end2 = start2 + length2;
11320         return start2 <= end1 && end2 >= start1;
11321     }
11322     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
11323     function textSpanIntersectsWithPosition(span, position) {
11324         return position <= textSpanEnd(span) && position >= span.start;
11325     }
11326     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
11327     function textSpanIntersection(span1, span2) {
11328         var start = Math.max(span1.start, span2.start);
11329         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
11330         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
11331     }
11332     ts.textSpanIntersection = textSpanIntersection;
11333     function createTextSpan(start, length) {
11334         if (start < 0) {
11335             throw new Error("start < 0");
11336         }
11337         if (length < 0) {
11338             throw new Error("length < 0");
11339         }
11340         return { start: start, length: length };
11341     }
11342     ts.createTextSpan = createTextSpan;
11343     function createTextSpanFromBounds(start, end) {
11344         return createTextSpan(start, end - start);
11345     }
11346     ts.createTextSpanFromBounds = createTextSpanFromBounds;
11347     function textChangeRangeNewSpan(range) {
11348         return createTextSpan(range.span.start, range.newLength);
11349     }
11350     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
11351     function textChangeRangeIsUnchanged(range) {
11352         return textSpanIsEmpty(range.span) && range.newLength === 0;
11353     }
11354     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
11355     function createTextChangeRange(span, newLength) {
11356         if (newLength < 0) {
11357             throw new Error("newLength < 0");
11358         }
11359         return { span: span, newLength: newLength };
11360     }
11361     ts.createTextChangeRange = createTextChangeRange;
11362     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
11363     /**
11364      * Called to merge all the changes that occurred across several versions of a script snapshot
11365      * into a single change.  i.e. if a user keeps making successive edits to a script we will
11366      * have a text change from V1 to V2, V2 to V3, ..., Vn.
11367      *
11368      * This function will then merge those changes into a single change range valid between V1 and
11369      * Vn.
11370      */
11371     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
11372         if (changes.length === 0) {
11373             return ts.unchangedTextChangeRange;
11374         }
11375         if (changes.length === 1) {
11376             return changes[0];
11377         }
11378         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
11379         // as it makes things much easier to reason about.
11380         var change0 = changes[0];
11381         var oldStartN = change0.span.start;
11382         var oldEndN = textSpanEnd(change0.span);
11383         var newEndN = oldStartN + change0.newLength;
11384         for (var i = 1; i < changes.length; i++) {
11385             var nextChange = changes[i];
11386             // Consider the following case:
11387             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
11388             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
11389             // i.e. the span starting at 30 with length 30 is increased to length 40.
11390             //
11391             //      0         10        20        30        40        50        60        70        80        90        100
11392             //      -------------------------------------------------------------------------------------------------------
11393             //                |                                                 /
11394             //                |                                            /----
11395             //  T1            |                                       /----
11396             //                |                                  /----
11397             //                |                             /----
11398             //      -------------------------------------------------------------------------------------------------------
11399             //                                     |                            \
11400             //                                     |                               \
11401             //   T2                                |                                 \
11402             //                                     |                                   \
11403             //                                     |                                      \
11404             //      -------------------------------------------------------------------------------------------------------
11405             //
11406             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
11407             // it's just the min of the old and new starts.  i.e.:
11408             //
11409             //      0         10        20        30        40        50        60        70        80        90        100
11410             //      ------------------------------------------------------------*------------------------------------------
11411             //                |                                                 /
11412             //                |                                            /----
11413             //  T1            |                                       /----
11414             //                |                                  /----
11415             //                |                             /----
11416             //      ----------------------------------------$-------------------$------------------------------------------
11417             //                .                    |                            \
11418             //                .                    |                               \
11419             //   T2           .                    |                                 \
11420             //                .                    |                                   \
11421             //                .                    |                                      \
11422             //      ----------------------------------------------------------------------*--------------------------------
11423             //
11424             // (Note the dots represent the newly inferred start.
11425             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
11426             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
11427             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
11428             // means:
11429             //
11430             //      0         10        20        30        40        50        60        70        80        90        100
11431             //      --------------------------------------------------------------------------------*----------------------
11432             //                |                                                                     /
11433             //                |                                                                /----
11434             //  T1            |                                                           /----
11435             //                |                                                      /----
11436             //                |                                                 /----
11437             //      ------------------------------------------------------------$------------------------------------------
11438             //                .                    |                            \
11439             //                .                    |                               \
11440             //   T2           .                    |                                 \
11441             //                .                    |                                   \
11442             //                .                    |                                      \
11443             //      ----------------------------------------------------------------------*--------------------------------
11444             //
11445             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
11446             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
11447             // that's the same as if we started at char 80 instead of 60.
11448             //
11449             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
11450             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
11451             // first.
11452             //
11453             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
11454             // semantics: { { start: 10, length: 70 }, newLength: 60 }
11455             //
11456             // The math then works out as follows.
11457             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
11458             // final result like so:
11459             //
11460             // {
11461             //      oldStart3: Min(oldStart1, oldStart2),
11462             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
11463             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
11464             // }
11465             var oldStart1 = oldStartN;
11466             var oldEnd1 = oldEndN;
11467             var newEnd1 = newEndN;
11468             var oldStart2 = nextChange.span.start;
11469             var oldEnd2 = textSpanEnd(nextChange.span);
11470             var newEnd2 = oldStart2 + nextChange.newLength;
11471             oldStartN = Math.min(oldStart1, oldStart2);
11472             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
11473             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
11474         }
11475         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
11476     }
11477     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
11478     function getTypeParameterOwner(d) {
11479         if (d && d.kind === 159 /* TypeParameter */) {
11480             for (var current = d; current; current = current.parent) {
11481                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 253 /* InterfaceDeclaration */) {
11482                     return current;
11483                 }
11484             }
11485         }
11486     }
11487     ts.getTypeParameterOwner = getTypeParameterOwner;
11488     function isParameterPropertyDeclaration(node, parent) {
11489         return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 166 /* Constructor */;
11490     }
11491     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
11492     function isEmptyBindingPattern(node) {
11493         if (isBindingPattern(node)) {
11494             return ts.every(node.elements, isEmptyBindingElement);
11495         }
11496         return false;
11497     }
11498     ts.isEmptyBindingPattern = isEmptyBindingPattern;
11499     function isEmptyBindingElement(node) {
11500         if (ts.isOmittedExpression(node)) {
11501             return true;
11502         }
11503         return isEmptyBindingPattern(node.name);
11504     }
11505     ts.isEmptyBindingElement = isEmptyBindingElement;
11506     function walkUpBindingElementsAndPatterns(binding) {
11507         var node = binding.parent;
11508         while (ts.isBindingElement(node.parent)) {
11509             node = node.parent.parent;
11510         }
11511         return node.parent;
11512     }
11513     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
11514     function getCombinedFlags(node, getFlags) {
11515         if (ts.isBindingElement(node)) {
11516             node = walkUpBindingElementsAndPatterns(node);
11517         }
11518         var flags = getFlags(node);
11519         if (node.kind === 249 /* VariableDeclaration */) {
11520             node = node.parent;
11521         }
11522         if (node && node.kind === 250 /* VariableDeclarationList */) {
11523             flags |= getFlags(node);
11524             node = node.parent;
11525         }
11526         if (node && node.kind === 232 /* VariableStatement */) {
11527             flags |= getFlags(node);
11528         }
11529         return flags;
11530     }
11531     function getCombinedModifierFlags(node) {
11532         return getCombinedFlags(node, ts.getEffectiveModifierFlags);
11533     }
11534     ts.getCombinedModifierFlags = getCombinedModifierFlags;
11535     /* @internal */
11536     function getCombinedNodeFlagsAlwaysIncludeJSDoc(node) {
11537         return getCombinedFlags(node, ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc);
11538     }
11539     ts.getCombinedNodeFlagsAlwaysIncludeJSDoc = getCombinedNodeFlagsAlwaysIncludeJSDoc;
11540     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
11541     // nodes like variable declarations and binding elements can returned a view of their flags
11542     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
11543     // stored on the variable declaration directly, but on the containing variable statement
11544     // (if it has one).  Similarly, flags for let/const are store on the variable declaration
11545     // list.  By calling this function, all those flags are combined so that the client can treat
11546     // the node as if it actually had those flags.
11547     function getCombinedNodeFlags(node) {
11548         return getCombinedFlags(node, function (n) { return n.flags; });
11549     }
11550     ts.getCombinedNodeFlags = getCombinedNodeFlags;
11551     /**
11552      * Checks to see if the locale is in the appropriate format,
11553      * and if it is, attempts to set the appropriate language.
11554      */
11555     function validateLocaleAndSetLanguage(locale, sys, errors) {
11556         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
11557         if (!matchResult) {
11558             if (errors) {
11559                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
11560             }
11561             return;
11562         }
11563         var language = matchResult[1];
11564         var territory = matchResult[3];
11565         // First try the entire locale, then fall back to just language if that's all we have.
11566         // Either ways do not fail, and fallback to the English diagnostic strings.
11567         if (!trySetLanguageAndTerritory(language, territory, errors)) {
11568             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
11569         }
11570         // Set the UI locale for string collation
11571         ts.setUILocale(locale);
11572         function trySetLanguageAndTerritory(language, territory, errors) {
11573             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
11574             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
11575             var filePath = ts.combinePaths(containingDirectoryPath, language);
11576             if (territory) {
11577                 filePath = filePath + "-" + territory;
11578             }
11579             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
11580             if (!sys.fileExists(filePath)) {
11581                 return false;
11582             }
11583             // TODO: Add codePage support for readFile?
11584             var fileContents = "";
11585             try {
11586                 fileContents = sys.readFile(filePath);
11587             }
11588             catch (e) {
11589                 if (errors) {
11590                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
11591                 }
11592                 return false;
11593             }
11594             try {
11595                 // this is a global mutation (or live binding update)!
11596                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
11597             }
11598             catch (_a) {
11599                 if (errors) {
11600                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
11601                 }
11602                 return false;
11603             }
11604             return true;
11605         }
11606     }
11607     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
11608     function getOriginalNode(node, nodeTest) {
11609         if (node) {
11610             while (node.original !== undefined) {
11611                 node = node.original;
11612             }
11613         }
11614         return !nodeTest || nodeTest(node) ? node : undefined;
11615     }
11616     ts.getOriginalNode = getOriginalNode;
11617     function findAncestor(node, callback) {
11618         while (node) {
11619             var result = callback(node);
11620             if (result === "quit") {
11621                 return undefined;
11622             }
11623             else if (result) {
11624                 return node;
11625             }
11626             node = node.parent;
11627         }
11628         return undefined;
11629     }
11630     ts.findAncestor = findAncestor;
11631     /**
11632      * Gets a value indicating whether a node originated in the parse tree.
11633      *
11634      * @param node The node to test.
11635      */
11636     function isParseTreeNode(node) {
11637         return (node.flags & 8 /* Synthesized */) === 0;
11638     }
11639     ts.isParseTreeNode = isParseTreeNode;
11640     function getParseTreeNode(node, nodeTest) {
11641         if (node === undefined || isParseTreeNode(node)) {
11642             return node;
11643         }
11644         node = node.original;
11645         while (node) {
11646             if (isParseTreeNode(node)) {
11647                 return !nodeTest || nodeTest(node) ? node : undefined;
11648             }
11649             node = node.original;
11650         }
11651     }
11652     ts.getParseTreeNode = getParseTreeNode;
11653     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
11654     function escapeLeadingUnderscores(identifier) {
11655         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
11656     }
11657     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
11658     /**
11659      * Remove extra underscore from escaped identifier text content.
11660      *
11661      * @param identifier The escaped identifier text.
11662      * @returns The unescaped identifier text.
11663      */
11664     function unescapeLeadingUnderscores(identifier) {
11665         var id = identifier;
11666         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
11667     }
11668     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
11669     function idText(identifierOrPrivateName) {
11670         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
11671     }
11672     ts.idText = idText;
11673     function symbolName(symbol) {
11674         if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
11675             return idText(symbol.valueDeclaration.name);
11676         }
11677         return unescapeLeadingUnderscores(symbol.escapedName);
11678     }
11679     ts.symbolName = symbolName;
11680     /**
11681      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
11682      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
11683      * will be merged with)
11684      */
11685     function nameForNamelessJSDocTypedef(declaration) {
11686         var hostNode = declaration.parent.parent;
11687         if (!hostNode) {
11688             return undefined;
11689         }
11690         // Covers classes, functions - any named declaration host node
11691         if (isDeclaration(hostNode)) {
11692             return getDeclarationIdentifier(hostNode);
11693         }
11694         // Covers remaining cases (returning undefined if none match).
11695         switch (hostNode.kind) {
11696             case 232 /* VariableStatement */:
11697                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
11698                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
11699                 }
11700                 break;
11701             case 233 /* ExpressionStatement */:
11702                 var expr = hostNode.expression;
11703                 if (expr.kind === 216 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
11704                     expr = expr.left;
11705                 }
11706                 switch (expr.kind) {
11707                     case 201 /* PropertyAccessExpression */:
11708                         return expr.name;
11709                     case 202 /* ElementAccessExpression */:
11710                         var arg = expr.argumentExpression;
11711                         if (ts.isIdentifier(arg)) {
11712                             return arg;
11713                         }
11714                 }
11715                 break;
11716             case 207 /* ParenthesizedExpression */: {
11717                 return getDeclarationIdentifier(hostNode.expression);
11718             }
11719             case 245 /* LabeledStatement */: {
11720                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
11721                     return getDeclarationIdentifier(hostNode.statement);
11722                 }
11723                 break;
11724             }
11725         }
11726     }
11727     function getDeclarationIdentifier(node) {
11728         var name = getNameOfDeclaration(node);
11729         return name && ts.isIdentifier(name) ? name : undefined;
11730     }
11731     /** @internal */
11732     function nodeHasName(statement, name) {
11733         if (isNamedDeclaration(statement) && ts.isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
11734             return true;
11735         }
11736         if (ts.isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
11737             return true;
11738         }
11739         return false;
11740     }
11741     ts.nodeHasName = nodeHasName;
11742     function getNameOfJSDocTypedef(declaration) {
11743         return declaration.name || nameForNamelessJSDocTypedef(declaration);
11744     }
11745     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
11746     /** @internal */
11747     function isNamedDeclaration(node) {
11748         return !!node.name; // A 'name' property should always be a DeclarationName.
11749     }
11750     ts.isNamedDeclaration = isNamedDeclaration;
11751     /** @internal */
11752     function getNonAssignedNameOfDeclaration(declaration) {
11753         switch (declaration.kind) {
11754             case 78 /* Identifier */:
11755                 return declaration;
11756             case 333 /* JSDocPropertyTag */:
11757             case 326 /* JSDocParameterTag */: {
11758                 var name = declaration.name;
11759                 if (name.kind === 157 /* QualifiedName */) {
11760                     return name.right;
11761                 }
11762                 break;
11763             }
11764             case 203 /* CallExpression */:
11765             case 216 /* BinaryExpression */: {
11766                 var expr_1 = declaration;
11767                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
11768                     case 1 /* ExportsProperty */:
11769                     case 4 /* ThisProperty */:
11770                     case 5 /* Property */:
11771                     case 3 /* PrototypeProperty */:
11772                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
11773                     case 7 /* ObjectDefinePropertyValue */:
11774                     case 8 /* ObjectDefinePropertyExports */:
11775                     case 9 /* ObjectDefinePrototypeProperty */:
11776                         return expr_1.arguments[1];
11777                     default:
11778                         return undefined;
11779                 }
11780             }
11781             case 331 /* JSDocTypedefTag */:
11782                 return getNameOfJSDocTypedef(declaration);
11783             case 325 /* JSDocEnumTag */:
11784                 return nameForNamelessJSDocTypedef(declaration);
11785             case 266 /* ExportAssignment */: {
11786                 var expression = declaration.expression;
11787                 return ts.isIdentifier(expression) ? expression : undefined;
11788             }
11789             case 202 /* ElementAccessExpression */:
11790                 var expr = declaration;
11791                 if (ts.isBindableStaticElementAccessExpression(expr)) {
11792                     return expr.argumentExpression;
11793                 }
11794         }
11795         return declaration.name;
11796     }
11797     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
11798     function getNameOfDeclaration(declaration) {
11799         if (declaration === undefined)
11800             return undefined;
11801         return getNonAssignedNameOfDeclaration(declaration) ||
11802             (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
11803     }
11804     ts.getNameOfDeclaration = getNameOfDeclaration;
11805     /*@internal*/
11806     function getAssignedName(node) {
11807         if (!node.parent) {
11808             return undefined;
11809         }
11810         else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) {
11811             return node.parent.name;
11812         }
11813         else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) {
11814             if (ts.isIdentifier(node.parent.left)) {
11815                 return node.parent.left;
11816             }
11817             else if (ts.isAccessExpression(node.parent.left)) {
11818                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
11819             }
11820         }
11821         else if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
11822             return node.parent.name;
11823         }
11824     }
11825     ts.getAssignedName = getAssignedName;
11826     function getJSDocParameterTagsWorker(param, noCache) {
11827         if (param.name) {
11828             if (ts.isIdentifier(param.name)) {
11829                 var name_1 = param.name.escapedText;
11830                 return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; });
11831             }
11832             else {
11833                 var i = param.parent.parameters.indexOf(param);
11834                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
11835                 var paramTags = getJSDocTagsWorker(param.parent, noCache).filter(ts.isJSDocParameterTag);
11836                 if (i < paramTags.length) {
11837                     return [paramTags[i]];
11838                 }
11839             }
11840         }
11841         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
11842         return ts.emptyArray;
11843     }
11844     /**
11845      * Gets the JSDoc parameter tags for the node if present.
11846      *
11847      * @remarks Returns any JSDoc param tag whose name matches the provided
11848      * parameter, whether a param tag on a containing function
11849      * expression, or a param tag on a variable declaration whose
11850      * initializer is the containing function. The tags closest to the
11851      * node are returned first, so in the previous example, the param
11852      * tag on the containing function expression would be first.
11853      *
11854      * For binding patterns, parameter tags are matched by position.
11855      */
11856     function getJSDocParameterTags(param) {
11857         return getJSDocParameterTagsWorker(param, /*noCache*/ false);
11858     }
11859     ts.getJSDocParameterTags = getJSDocParameterTags;
11860     /* @internal */
11861     function getJSDocParameterTagsNoCache(param) {
11862         return getJSDocParameterTagsWorker(param, /*noCache*/ true);
11863     }
11864     ts.getJSDocParameterTagsNoCache = getJSDocParameterTagsNoCache;
11865     function getJSDocTypeParameterTagsWorker(param, noCache) {
11866         var name = param.name.escapedText;
11867         return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) {
11868             return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
11869         });
11870     }
11871     /**
11872      * Gets the JSDoc type parameter tags for the node if present.
11873      *
11874      * @remarks Returns any JSDoc template tag whose names match the provided
11875      * parameter, whether a template tag on a containing function
11876      * expression, or a template tag on a variable declaration whose
11877      * initializer is the containing function. The tags closest to the
11878      * node are returned first, so in the previous example, the template
11879      * tag on the containing function expression would be first.
11880      */
11881     function getJSDocTypeParameterTags(param) {
11882         return getJSDocTypeParameterTagsWorker(param, /*noCache*/ false);
11883     }
11884     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
11885     /* @internal */
11886     function getJSDocTypeParameterTagsNoCache(param) {
11887         return getJSDocTypeParameterTagsWorker(param, /*noCache*/ true);
11888     }
11889     ts.getJSDocTypeParameterTagsNoCache = getJSDocTypeParameterTagsNoCache;
11890     /**
11891      * Return true if the node has JSDoc parameter tags.
11892      *
11893      * @remarks Includes parameter tags that are not directly on the node,
11894      * for example on a variable declaration whose initializer is a function expression.
11895      */
11896     function hasJSDocParameterTags(node) {
11897         return !!getFirstJSDocTag(node, ts.isJSDocParameterTag);
11898     }
11899     ts.hasJSDocParameterTags = hasJSDocParameterTags;
11900     /** Gets the JSDoc augments tag for the node if present */
11901     function getJSDocAugmentsTag(node) {
11902         return getFirstJSDocTag(node, ts.isJSDocAugmentsTag);
11903     }
11904     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
11905     /** Gets the JSDoc implements tags for the node if present */
11906     function getJSDocImplementsTags(node) {
11907         return getAllJSDocTags(node, ts.isJSDocImplementsTag);
11908     }
11909     ts.getJSDocImplementsTags = getJSDocImplementsTags;
11910     /** Gets the JSDoc class tag for the node if present */
11911     function getJSDocClassTag(node) {
11912         return getFirstJSDocTag(node, ts.isJSDocClassTag);
11913     }
11914     ts.getJSDocClassTag = getJSDocClassTag;
11915     /** Gets the JSDoc public tag for the node if present */
11916     function getJSDocPublicTag(node) {
11917         return getFirstJSDocTag(node, ts.isJSDocPublicTag);
11918     }
11919     ts.getJSDocPublicTag = getJSDocPublicTag;
11920     /*@internal*/
11921     function getJSDocPublicTagNoCache(node) {
11922         return getFirstJSDocTag(node, ts.isJSDocPublicTag, /*noCache*/ true);
11923     }
11924     ts.getJSDocPublicTagNoCache = getJSDocPublicTagNoCache;
11925     /** Gets the JSDoc private tag for the node if present */
11926     function getJSDocPrivateTag(node) {
11927         return getFirstJSDocTag(node, ts.isJSDocPrivateTag);
11928     }
11929     ts.getJSDocPrivateTag = getJSDocPrivateTag;
11930     /*@internal*/
11931     function getJSDocPrivateTagNoCache(node) {
11932         return getFirstJSDocTag(node, ts.isJSDocPrivateTag, /*noCache*/ true);
11933     }
11934     ts.getJSDocPrivateTagNoCache = getJSDocPrivateTagNoCache;
11935     /** Gets the JSDoc protected tag for the node if present */
11936     function getJSDocProtectedTag(node) {
11937         return getFirstJSDocTag(node, ts.isJSDocProtectedTag);
11938     }
11939     ts.getJSDocProtectedTag = getJSDocProtectedTag;
11940     /*@internal*/
11941     function getJSDocProtectedTagNoCache(node) {
11942         return getFirstJSDocTag(node, ts.isJSDocProtectedTag, /*noCache*/ true);
11943     }
11944     ts.getJSDocProtectedTagNoCache = getJSDocProtectedTagNoCache;
11945     /** Gets the JSDoc protected tag for the node if present */
11946     function getJSDocReadonlyTag(node) {
11947         return getFirstJSDocTag(node, ts.isJSDocReadonlyTag);
11948     }
11949     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
11950     /*@internal*/
11951     function getJSDocReadonlyTagNoCache(node) {
11952         return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true);
11953     }
11954     ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache;
11955     /** Gets the JSDoc deprecated tag for the node if present */
11956     function getJSDocDeprecatedTag(node) {
11957         return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag);
11958     }
11959     ts.getJSDocDeprecatedTag = getJSDocDeprecatedTag;
11960     /*@internal */
11961     function getJSDocDeprecatedTagNoCache(node) {
11962         return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag, /*noCache*/ true);
11963     }
11964     ts.getJSDocDeprecatedTagNoCache = getJSDocDeprecatedTagNoCache;
11965     /** Gets the JSDoc enum tag for the node if present */
11966     function getJSDocEnumTag(node) {
11967         return getFirstJSDocTag(node, ts.isJSDocEnumTag);
11968     }
11969     ts.getJSDocEnumTag = getJSDocEnumTag;
11970     /** Gets the JSDoc this tag for the node if present */
11971     function getJSDocThisTag(node) {
11972         return getFirstJSDocTag(node, ts.isJSDocThisTag);
11973     }
11974     ts.getJSDocThisTag = getJSDocThisTag;
11975     /** Gets the JSDoc return tag for the node if present */
11976     function getJSDocReturnTag(node) {
11977         return getFirstJSDocTag(node, ts.isJSDocReturnTag);
11978     }
11979     ts.getJSDocReturnTag = getJSDocReturnTag;
11980     /** Gets the JSDoc template tag for the node if present */
11981     function getJSDocTemplateTag(node) {
11982         return getFirstJSDocTag(node, ts.isJSDocTemplateTag);
11983     }
11984     ts.getJSDocTemplateTag = getJSDocTemplateTag;
11985     /** Gets the JSDoc type tag for the node if present and valid */
11986     function getJSDocTypeTag(node) {
11987         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
11988         var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
11989         if (tag && tag.typeExpression && tag.typeExpression.type) {
11990             return tag;
11991         }
11992         return undefined;
11993     }
11994     ts.getJSDocTypeTag = getJSDocTypeTag;
11995     /**
11996      * Gets the type node for the node if provided via JSDoc.
11997      *
11998      * @remarks The search includes any JSDoc param tag that relates
11999      * to the provided parameter, for example a type tag on the
12000      * parameter itself, or a param tag on a containing function
12001      * expression, or a param tag on a variable declaration whose
12002      * initializer is the containing function. The tags closest to the
12003      * node are examined first, so in the previous example, the type
12004      * tag directly on the node would be returned.
12005      */
12006     function getJSDocType(node) {
12007         var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
12008         if (!tag && ts.isParameter(node)) {
12009             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
12010         }
12011         return tag && tag.typeExpression && tag.typeExpression.type;
12012     }
12013     ts.getJSDocType = getJSDocType;
12014     /**
12015      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
12016      *
12017      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
12018      * gets the type from inside the braces, after the fat arrow, etc.
12019      */
12020     function getJSDocReturnType(node) {
12021         var returnTag = getJSDocReturnTag(node);
12022         if (returnTag && returnTag.typeExpression) {
12023             return returnTag.typeExpression.type;
12024         }
12025         var typeTag = getJSDocTypeTag(node);
12026         if (typeTag && typeTag.typeExpression) {
12027             var type = typeTag.typeExpression.type;
12028             if (ts.isTypeLiteralNode(type)) {
12029                 var sig = ts.find(type.members, ts.isCallSignatureDeclaration);
12030                 return sig && sig.type;
12031             }
12032             if (ts.isFunctionTypeNode(type) || ts.isJSDocFunctionType(type)) {
12033                 return type.type;
12034             }
12035         }
12036     }
12037     ts.getJSDocReturnType = getJSDocReturnType;
12038     function getJSDocTagsWorker(node, noCache) {
12039         var tags = node.jsDocCache;
12040         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
12041         if (tags === undefined || noCache) {
12042             var comments = ts.getJSDocCommentsAndTags(node, noCache);
12043             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
12044             tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
12045             if (!noCache) {
12046                 node.jsDocCache = tags;
12047             }
12048         }
12049         return tags;
12050     }
12051     /** Get all JSDoc tags related to a node, including those on parent nodes. */
12052     function getJSDocTags(node) {
12053         return getJSDocTagsWorker(node, /*noCache*/ false);
12054     }
12055     ts.getJSDocTags = getJSDocTags;
12056     /* @internal */
12057     function getJSDocTagsNoCache(node) {
12058         return getJSDocTagsWorker(node, /*noCache*/ true);
12059     }
12060     ts.getJSDocTagsNoCache = getJSDocTagsNoCache;
12061     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
12062     function getFirstJSDocTag(node, predicate, noCache) {
12063         return ts.find(getJSDocTagsWorker(node, noCache), predicate);
12064     }
12065     /** Gets all JSDoc tags that match a specified predicate */
12066     function getAllJSDocTags(node, predicate) {
12067         return getJSDocTags(node).filter(predicate);
12068     }
12069     ts.getAllJSDocTags = getAllJSDocTags;
12070     /** Gets all JSDoc tags of a specified kind */
12071     function getAllJSDocTagsOfKind(node, kind) {
12072         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
12073     }
12074     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
12075     /**
12076      * Gets the effective type parameters. If the node was parsed in a
12077      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
12078      */
12079     function getEffectiveTypeParameterDeclarations(node) {
12080         if (ts.isJSDocSignature(node)) {
12081             return ts.emptyArray;
12082         }
12083         if (ts.isJSDocTypeAlias(node)) {
12084             ts.Debug.assert(node.parent.kind === 311 /* JSDocComment */);
12085             return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
12086         }
12087         if (node.typeParameters) {
12088             return node.typeParameters;
12089         }
12090         if (ts.isInJSFile(node)) {
12091             var decls = ts.getJSDocTypeParameterDeclarations(node);
12092             if (decls.length) {
12093                 return decls;
12094             }
12095             var typeTag = getJSDocType(node);
12096             if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
12097                 return typeTag.typeParameters;
12098             }
12099         }
12100         return ts.emptyArray;
12101     }
12102     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
12103     function getEffectiveConstraintOfTypeParameter(node) {
12104         return node.constraint ? node.constraint :
12105             ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
12106                 undefined;
12107     }
12108     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
12109     // #region
12110     function isIdentifierOrPrivateIdentifier(node) {
12111         return node.kind === 78 /* Identifier */ || node.kind === 79 /* PrivateIdentifier */;
12112     }
12113     ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
12114     /* @internal */
12115     function isGetOrSetAccessorDeclaration(node) {
12116         return node.kind === 168 /* SetAccessor */ || node.kind === 167 /* GetAccessor */;
12117     }
12118     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
12119     function isPropertyAccessChain(node) {
12120         return ts.isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12121     }
12122     ts.isPropertyAccessChain = isPropertyAccessChain;
12123     function isElementAccessChain(node) {
12124         return ts.isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12125     }
12126     ts.isElementAccessChain = isElementAccessChain;
12127     function isCallChain(node) {
12128         return ts.isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12129     }
12130     ts.isCallChain = isCallChain;
12131     function isOptionalChain(node) {
12132         var kind = node.kind;
12133         return !!(node.flags & 32 /* OptionalChain */) &&
12134             (kind === 201 /* PropertyAccessExpression */
12135                 || kind === 202 /* ElementAccessExpression */
12136                 || kind === 203 /* CallExpression */
12137                 || kind === 225 /* NonNullExpression */);
12138     }
12139     ts.isOptionalChain = isOptionalChain;
12140     /* @internal */
12141     function isOptionalChainRoot(node) {
12142         return isOptionalChain(node) && !ts.isNonNullExpression(node) && !!node.questionDotToken;
12143     }
12144     ts.isOptionalChainRoot = isOptionalChainRoot;
12145     /**
12146      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
12147      */
12148     /* @internal */
12149     function isExpressionOfOptionalChainRoot(node) {
12150         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
12151     }
12152     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
12153     /**
12154      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
12155      *
12156      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
12157      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
12158      * 3. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain)
12159      * 4. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is
12160      *   the end of the chain starting at `c?.`)
12161      * 5. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is
12162      *   the end of the chain starting at `a?.`)
12163      */
12164     /* @internal */
12165     function isOutermostOptionalChain(node) {
12166         return !isOptionalChain(node.parent) // cases 1, 2, and 3
12167             || isOptionalChainRoot(node.parent) // case 4
12168             || node !== node.parent.expression; // case 5
12169     }
12170     ts.isOutermostOptionalChain = isOutermostOptionalChain;
12171     function isNullishCoalesce(node) {
12172         return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
12173     }
12174     ts.isNullishCoalesce = isNullishCoalesce;
12175     function isConstTypeReference(node) {
12176         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) &&
12177             node.typeName.escapedText === "const" && !node.typeArguments;
12178     }
12179     ts.isConstTypeReference = isConstTypeReference;
12180     function skipPartiallyEmittedExpressions(node) {
12181         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
12182     }
12183     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
12184     function isNonNullChain(node) {
12185         return ts.isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12186     }
12187     ts.isNonNullChain = isNonNullChain;
12188     function isBreakOrContinueStatement(node) {
12189         return node.kind === 241 /* BreakStatement */ || node.kind === 240 /* ContinueStatement */;
12190     }
12191     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
12192     function isNamedExportBindings(node) {
12193         return node.kind === 269 /* NamespaceExport */ || node.kind === 268 /* NamedExports */;
12194     }
12195     ts.isNamedExportBindings = isNamedExportBindings;
12196     function isUnparsedTextLike(node) {
12197         switch (node.kind) {
12198             case 294 /* UnparsedText */:
12199             case 295 /* UnparsedInternalText */:
12200                 return true;
12201             default:
12202                 return false;
12203         }
12204     }
12205     ts.isUnparsedTextLike = isUnparsedTextLike;
12206     function isUnparsedNode(node) {
12207         return isUnparsedTextLike(node) ||
12208             node.kind === 292 /* UnparsedPrologue */ ||
12209             node.kind === 296 /* UnparsedSyntheticReference */;
12210     }
12211     ts.isUnparsedNode = isUnparsedNode;
12212     function isJSDocPropertyLikeTag(node) {
12213         return node.kind === 333 /* JSDocPropertyTag */ || node.kind === 326 /* JSDocParameterTag */;
12214     }
12215     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
12216     // #endregion
12217     // #region
12218     // Node tests
12219     //
12220     // All node tests in the following list should *not* reference parent pointers so that
12221     // they may be used with transformations.
12222     /* @internal */
12223     function isNode(node) {
12224         return isNodeKind(node.kind);
12225     }
12226     ts.isNode = isNode;
12227     /* @internal */
12228     function isNodeKind(kind) {
12229         return kind >= 157 /* FirstNode */;
12230     }
12231     ts.isNodeKind = isNodeKind;
12232     /**
12233      * True if node is of some token syntax kind.
12234      * For example, this is true for an IfKeyword but not for an IfStatement.
12235      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
12236      */
12237     function isToken(n) {
12238         return n.kind >= 0 /* FirstToken */ && n.kind <= 156 /* LastToken */;
12239     }
12240     ts.isToken = isToken;
12241     // Node Arrays
12242     /* @internal */
12243     function isNodeArray(array) {
12244         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
12245     }
12246     ts.isNodeArray = isNodeArray;
12247     // Literals
12248     /* @internal */
12249     function isLiteralKind(kind) {
12250         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
12251     }
12252     ts.isLiteralKind = isLiteralKind;
12253     function isLiteralExpression(node) {
12254         return isLiteralKind(node.kind);
12255     }
12256     ts.isLiteralExpression = isLiteralExpression;
12257     // Pseudo-literals
12258     /* @internal */
12259     function isTemplateLiteralKind(kind) {
12260         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
12261     }
12262     ts.isTemplateLiteralKind = isTemplateLiteralKind;
12263     function isTemplateLiteralToken(node) {
12264         return isTemplateLiteralKind(node.kind);
12265     }
12266     ts.isTemplateLiteralToken = isTemplateLiteralToken;
12267     function isTemplateMiddleOrTemplateTail(node) {
12268         var kind = node.kind;
12269         return kind === 16 /* TemplateMiddle */
12270             || kind === 17 /* TemplateTail */;
12271     }
12272     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
12273     function isImportOrExportSpecifier(node) {
12274         return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
12275     }
12276     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
12277     function isTypeOnlyImportOrExportDeclaration(node) {
12278         switch (node.kind) {
12279             case 265 /* ImportSpecifier */:
12280             case 270 /* ExportSpecifier */:
12281                 return node.parent.parent.isTypeOnly;
12282             case 263 /* NamespaceImport */:
12283                 return node.parent.isTypeOnly;
12284             case 262 /* ImportClause */:
12285                 return node.isTypeOnly;
12286             default:
12287                 return false;
12288         }
12289     }
12290     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
12291     function isStringTextContainingNode(node) {
12292         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
12293     }
12294     ts.isStringTextContainingNode = isStringTextContainingNode;
12295     // Identifiers
12296     /* @internal */
12297     function isGeneratedIdentifier(node) {
12298         return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
12299     }
12300     ts.isGeneratedIdentifier = isGeneratedIdentifier;
12301     // Private Identifiers
12302     /*@internal*/
12303     function isPrivateIdentifierPropertyDeclaration(node) {
12304         return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name);
12305     }
12306     ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
12307     /*@internal*/
12308     function isPrivateIdentifierPropertyAccessExpression(node) {
12309         return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name);
12310     }
12311     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
12312     // Keywords
12313     /* @internal */
12314     function isModifierKind(token) {
12315         switch (token) {
12316             case 125 /* AbstractKeyword */:
12317             case 129 /* AsyncKeyword */:
12318             case 84 /* ConstKeyword */:
12319             case 133 /* DeclareKeyword */:
12320             case 87 /* DefaultKeyword */:
12321             case 92 /* ExportKeyword */:
12322             case 122 /* PublicKeyword */:
12323             case 120 /* PrivateKeyword */:
12324             case 121 /* ProtectedKeyword */:
12325             case 142 /* ReadonlyKeyword */:
12326             case 123 /* StaticKeyword */:
12327                 return true;
12328         }
12329         return false;
12330     }
12331     ts.isModifierKind = isModifierKind;
12332     /* @internal */
12333     function isParameterPropertyModifier(kind) {
12334         return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
12335     }
12336     ts.isParameterPropertyModifier = isParameterPropertyModifier;
12337     /* @internal */
12338     function isClassMemberModifier(idToken) {
12339         return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */;
12340     }
12341     ts.isClassMemberModifier = isClassMemberModifier;
12342     function isModifier(node) {
12343         return isModifierKind(node.kind);
12344     }
12345     ts.isModifier = isModifier;
12346     function isEntityName(node) {
12347         var kind = node.kind;
12348         return kind === 157 /* QualifiedName */
12349             || kind === 78 /* Identifier */;
12350     }
12351     ts.isEntityName = isEntityName;
12352     function isPropertyName(node) {
12353         var kind = node.kind;
12354         return kind === 78 /* Identifier */
12355             || kind === 79 /* PrivateIdentifier */
12356             || kind === 10 /* StringLiteral */
12357             || kind === 8 /* NumericLiteral */
12358             || kind === 158 /* ComputedPropertyName */;
12359     }
12360     ts.isPropertyName = isPropertyName;
12361     function isBindingName(node) {
12362         var kind = node.kind;
12363         return kind === 78 /* Identifier */
12364             || kind === 196 /* ObjectBindingPattern */
12365             || kind === 197 /* ArrayBindingPattern */;
12366     }
12367     ts.isBindingName = isBindingName;
12368     // Functions
12369     function isFunctionLike(node) {
12370         return node && isFunctionLikeKind(node.kind);
12371     }
12372     ts.isFunctionLike = isFunctionLike;
12373     /* @internal */
12374     function isFunctionLikeDeclaration(node) {
12375         return node && isFunctionLikeDeclarationKind(node.kind);
12376     }
12377     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
12378     function isFunctionLikeDeclarationKind(kind) {
12379         switch (kind) {
12380             case 251 /* FunctionDeclaration */:
12381             case 165 /* MethodDeclaration */:
12382             case 166 /* Constructor */:
12383             case 167 /* GetAccessor */:
12384             case 168 /* SetAccessor */:
12385             case 208 /* FunctionExpression */:
12386             case 209 /* ArrowFunction */:
12387                 return true;
12388             default:
12389                 return false;
12390         }
12391     }
12392     /* @internal */
12393     function isFunctionLikeKind(kind) {
12394         switch (kind) {
12395             case 164 /* MethodSignature */:
12396             case 169 /* CallSignature */:
12397             case 313 /* JSDocSignature */:
12398             case 170 /* ConstructSignature */:
12399             case 171 /* IndexSignature */:
12400             case 174 /* FunctionType */:
12401             case 308 /* JSDocFunctionType */:
12402             case 175 /* ConstructorType */:
12403                 return true;
12404             default:
12405                 return isFunctionLikeDeclarationKind(kind);
12406         }
12407     }
12408     ts.isFunctionLikeKind = isFunctionLikeKind;
12409     /* @internal */
12410     function isFunctionOrModuleBlock(node) {
12411         return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent);
12412     }
12413     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
12414     // Classes
12415     function isClassElement(node) {
12416         var kind = node.kind;
12417         return kind === 166 /* Constructor */
12418             || kind === 163 /* PropertyDeclaration */
12419             || kind === 165 /* MethodDeclaration */
12420             || kind === 167 /* GetAccessor */
12421             || kind === 168 /* SetAccessor */
12422             || kind === 171 /* IndexSignature */
12423             || kind === 229 /* SemicolonClassElement */;
12424     }
12425     ts.isClassElement = isClassElement;
12426     function isClassLike(node) {
12427         return node && (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */);
12428     }
12429     ts.isClassLike = isClassLike;
12430     function isAccessor(node) {
12431         return node && (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */);
12432     }
12433     ts.isAccessor = isAccessor;
12434     /* @internal */
12435     function isMethodOrAccessor(node) {
12436         switch (node.kind) {
12437             case 165 /* MethodDeclaration */:
12438             case 167 /* GetAccessor */:
12439             case 168 /* SetAccessor */:
12440                 return true;
12441             default:
12442                 return false;
12443         }
12444     }
12445     ts.isMethodOrAccessor = isMethodOrAccessor;
12446     // Type members
12447     function isTypeElement(node) {
12448         var kind = node.kind;
12449         return kind === 170 /* ConstructSignature */
12450             || kind === 169 /* CallSignature */
12451             || kind === 162 /* PropertySignature */
12452             || kind === 164 /* MethodSignature */
12453             || kind === 171 /* IndexSignature */;
12454     }
12455     ts.isTypeElement = isTypeElement;
12456     function isClassOrTypeElement(node) {
12457         return isTypeElement(node) || isClassElement(node);
12458     }
12459     ts.isClassOrTypeElement = isClassOrTypeElement;
12460     function isObjectLiteralElementLike(node) {
12461         var kind = node.kind;
12462         return kind === 288 /* PropertyAssignment */
12463             || kind === 289 /* ShorthandPropertyAssignment */
12464             || kind === 290 /* SpreadAssignment */
12465             || kind === 165 /* MethodDeclaration */
12466             || kind === 167 /* GetAccessor */
12467             || kind === 168 /* SetAccessor */;
12468     }
12469     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
12470     // Type
12471     /**
12472      * Node test that determines whether a node is a valid type node.
12473      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
12474      * of a TypeNode.
12475      */
12476     function isTypeNode(node) {
12477         return ts.isTypeNodeKind(node.kind);
12478     }
12479     ts.isTypeNode = isTypeNode;
12480     function isFunctionOrConstructorTypeNode(node) {
12481         switch (node.kind) {
12482             case 174 /* FunctionType */:
12483             case 175 /* ConstructorType */:
12484                 return true;
12485         }
12486         return false;
12487     }
12488     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
12489     // Binding patterns
12490     /* @internal */
12491     function isBindingPattern(node) {
12492         if (node) {
12493             var kind = node.kind;
12494             return kind === 197 /* ArrayBindingPattern */
12495                 || kind === 196 /* ObjectBindingPattern */;
12496         }
12497         return false;
12498     }
12499     ts.isBindingPattern = isBindingPattern;
12500     /* @internal */
12501     function isAssignmentPattern(node) {
12502         var kind = node.kind;
12503         return kind === 199 /* ArrayLiteralExpression */
12504             || kind === 200 /* ObjectLiteralExpression */;
12505     }
12506     ts.isAssignmentPattern = isAssignmentPattern;
12507     /* @internal */
12508     function isArrayBindingElement(node) {
12509         var kind = node.kind;
12510         return kind === 198 /* BindingElement */
12511             || kind === 222 /* OmittedExpression */;
12512     }
12513     ts.isArrayBindingElement = isArrayBindingElement;
12514     /**
12515      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
12516      */
12517     /* @internal */
12518     function isDeclarationBindingElement(bindingElement) {
12519         switch (bindingElement.kind) {
12520             case 249 /* VariableDeclaration */:
12521             case 160 /* Parameter */:
12522             case 198 /* BindingElement */:
12523                 return true;
12524         }
12525         return false;
12526     }
12527     ts.isDeclarationBindingElement = isDeclarationBindingElement;
12528     /**
12529      * Determines whether a node is a BindingOrAssignmentPattern
12530      */
12531     /* @internal */
12532     function isBindingOrAssignmentPattern(node) {
12533         return isObjectBindingOrAssignmentPattern(node)
12534             || isArrayBindingOrAssignmentPattern(node);
12535     }
12536     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
12537     /**
12538      * Determines whether a node is an ObjectBindingOrAssignmentPattern
12539      */
12540     /* @internal */
12541     function isObjectBindingOrAssignmentPattern(node) {
12542         switch (node.kind) {
12543             case 196 /* ObjectBindingPattern */:
12544             case 200 /* ObjectLiteralExpression */:
12545                 return true;
12546         }
12547         return false;
12548     }
12549     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
12550     /**
12551      * Determines whether a node is an ArrayBindingOrAssignmentPattern
12552      */
12553     /* @internal */
12554     function isArrayBindingOrAssignmentPattern(node) {
12555         switch (node.kind) {
12556             case 197 /* ArrayBindingPattern */:
12557             case 199 /* ArrayLiteralExpression */:
12558                 return true;
12559         }
12560         return false;
12561     }
12562     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
12563     /* @internal */
12564     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
12565         var kind = node.kind;
12566         return kind === 201 /* PropertyAccessExpression */
12567             || kind === 157 /* QualifiedName */
12568             || kind === 195 /* ImportType */;
12569     }
12570     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
12571     // Expression
12572     function isPropertyAccessOrQualifiedName(node) {
12573         var kind = node.kind;
12574         return kind === 201 /* PropertyAccessExpression */
12575             || kind === 157 /* QualifiedName */;
12576     }
12577     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
12578     function isCallLikeExpression(node) {
12579         switch (node.kind) {
12580             case 275 /* JsxOpeningElement */:
12581             case 274 /* JsxSelfClosingElement */:
12582             case 203 /* CallExpression */:
12583             case 204 /* NewExpression */:
12584             case 205 /* TaggedTemplateExpression */:
12585             case 161 /* Decorator */:
12586                 return true;
12587             default:
12588                 return false;
12589         }
12590     }
12591     ts.isCallLikeExpression = isCallLikeExpression;
12592     function isCallOrNewExpression(node) {
12593         return node.kind === 203 /* CallExpression */ || node.kind === 204 /* NewExpression */;
12594     }
12595     ts.isCallOrNewExpression = isCallOrNewExpression;
12596     function isTemplateLiteral(node) {
12597         var kind = node.kind;
12598         return kind === 218 /* TemplateExpression */
12599             || kind === 14 /* NoSubstitutionTemplateLiteral */;
12600     }
12601     ts.isTemplateLiteral = isTemplateLiteral;
12602     /* @internal */
12603     function isLeftHandSideExpression(node) {
12604         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12605     }
12606     ts.isLeftHandSideExpression = isLeftHandSideExpression;
12607     function isLeftHandSideExpressionKind(kind) {
12608         switch (kind) {
12609             case 201 /* PropertyAccessExpression */:
12610             case 202 /* ElementAccessExpression */:
12611             case 204 /* NewExpression */:
12612             case 203 /* CallExpression */:
12613             case 273 /* JsxElement */:
12614             case 274 /* JsxSelfClosingElement */:
12615             case 277 /* JsxFragment */:
12616             case 205 /* TaggedTemplateExpression */:
12617             case 199 /* ArrayLiteralExpression */:
12618             case 207 /* ParenthesizedExpression */:
12619             case 200 /* ObjectLiteralExpression */:
12620             case 221 /* ClassExpression */:
12621             case 208 /* FunctionExpression */:
12622             case 78 /* Identifier */:
12623             case 13 /* RegularExpressionLiteral */:
12624             case 8 /* NumericLiteral */:
12625             case 9 /* BigIntLiteral */:
12626             case 10 /* StringLiteral */:
12627             case 14 /* NoSubstitutionTemplateLiteral */:
12628             case 218 /* TemplateExpression */:
12629             case 94 /* FalseKeyword */:
12630             case 103 /* NullKeyword */:
12631             case 107 /* ThisKeyword */:
12632             case 109 /* TrueKeyword */:
12633             case 105 /* SuperKeyword */:
12634             case 225 /* NonNullExpression */:
12635             case 226 /* MetaProperty */:
12636             case 99 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12637                 return true;
12638             default:
12639                 return false;
12640         }
12641     }
12642     /* @internal */
12643     function isUnaryExpression(node) {
12644         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12645     }
12646     ts.isUnaryExpression = isUnaryExpression;
12647     function isUnaryExpressionKind(kind) {
12648         switch (kind) {
12649             case 214 /* PrefixUnaryExpression */:
12650             case 215 /* PostfixUnaryExpression */:
12651             case 210 /* DeleteExpression */:
12652             case 211 /* TypeOfExpression */:
12653             case 212 /* VoidExpression */:
12654             case 213 /* AwaitExpression */:
12655             case 206 /* TypeAssertionExpression */:
12656                 return true;
12657             default:
12658                 return isLeftHandSideExpressionKind(kind);
12659         }
12660     }
12661     /* @internal */
12662     function isUnaryExpressionWithWrite(expr) {
12663         switch (expr.kind) {
12664             case 215 /* PostfixUnaryExpression */:
12665                 return true;
12666             case 214 /* PrefixUnaryExpression */:
12667                 return expr.operator === 45 /* PlusPlusToken */ ||
12668                     expr.operator === 46 /* MinusMinusToken */;
12669             default:
12670                 return false;
12671         }
12672     }
12673     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12674     /* @internal */
12675     /**
12676      * Determines whether a node is an expression based only on its kind.
12677      * Use `isExpressionNode` if not in transforms.
12678      */
12679     function isExpression(node) {
12680         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12681     }
12682     ts.isExpression = isExpression;
12683     function isExpressionKind(kind) {
12684         switch (kind) {
12685             case 217 /* ConditionalExpression */:
12686             case 219 /* YieldExpression */:
12687             case 209 /* ArrowFunction */:
12688             case 216 /* BinaryExpression */:
12689             case 220 /* SpreadElement */:
12690             case 224 /* AsExpression */:
12691             case 222 /* OmittedExpression */:
12692             case 337 /* CommaListExpression */:
12693             case 336 /* PartiallyEmittedExpression */:
12694                 return true;
12695             default:
12696                 return isUnaryExpressionKind(kind);
12697         }
12698     }
12699     function isAssertionExpression(node) {
12700         var kind = node.kind;
12701         return kind === 206 /* TypeAssertionExpression */
12702             || kind === 224 /* AsExpression */;
12703     }
12704     ts.isAssertionExpression = isAssertionExpression;
12705     /* @internal */
12706     function isNotEmittedOrPartiallyEmittedNode(node) {
12707         return ts.isNotEmittedStatement(node)
12708             || ts.isPartiallyEmittedExpression(node);
12709     }
12710     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12711     function isIterationStatement(node, lookInLabeledStatements) {
12712         switch (node.kind) {
12713             case 237 /* ForStatement */:
12714             case 238 /* ForInStatement */:
12715             case 239 /* ForOfStatement */:
12716             case 235 /* DoStatement */:
12717             case 236 /* WhileStatement */:
12718                 return true;
12719             case 245 /* LabeledStatement */:
12720                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12721         }
12722         return false;
12723     }
12724     ts.isIterationStatement = isIterationStatement;
12725     /* @internal */
12726     function isScopeMarker(node) {
12727         return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
12728     }
12729     ts.isScopeMarker = isScopeMarker;
12730     /* @internal */
12731     function hasScopeMarker(statements) {
12732         return ts.some(statements, isScopeMarker);
12733     }
12734     ts.hasScopeMarker = hasScopeMarker;
12735     /* @internal */
12736     function needsScopeMarker(result) {
12737         return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasSyntacticModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12738     }
12739     ts.needsScopeMarker = needsScopeMarker;
12740     /* @internal */
12741     function isExternalModuleIndicator(result) {
12742         // Exported top-level member indicates moduleness
12743         return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasSyntacticModifier(result, 1 /* Export */);
12744     }
12745     ts.isExternalModuleIndicator = isExternalModuleIndicator;
12746     /* @internal */
12747     function isForInOrOfStatement(node) {
12748         return node.kind === 238 /* ForInStatement */ || node.kind === 239 /* ForOfStatement */;
12749     }
12750     ts.isForInOrOfStatement = isForInOrOfStatement;
12751     // Element
12752     /* @internal */
12753     function isConciseBody(node) {
12754         return ts.isBlock(node)
12755             || isExpression(node);
12756     }
12757     ts.isConciseBody = isConciseBody;
12758     /* @internal */
12759     function isFunctionBody(node) {
12760         return ts.isBlock(node);
12761     }
12762     ts.isFunctionBody = isFunctionBody;
12763     /* @internal */
12764     function isForInitializer(node) {
12765         return ts.isVariableDeclarationList(node)
12766             || isExpression(node);
12767     }
12768     ts.isForInitializer = isForInitializer;
12769     /* @internal */
12770     function isModuleBody(node) {
12771         var kind = node.kind;
12772         return kind === 257 /* ModuleBlock */
12773             || kind === 256 /* ModuleDeclaration */
12774             || kind === 78 /* Identifier */;
12775     }
12776     ts.isModuleBody = isModuleBody;
12777     /* @internal */
12778     function isNamespaceBody(node) {
12779         var kind = node.kind;
12780         return kind === 257 /* ModuleBlock */
12781             || kind === 256 /* ModuleDeclaration */;
12782     }
12783     ts.isNamespaceBody = isNamespaceBody;
12784     /* @internal */
12785     function isJSDocNamespaceBody(node) {
12786         var kind = node.kind;
12787         return kind === 78 /* Identifier */
12788             || kind === 256 /* ModuleDeclaration */;
12789     }
12790     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12791     /* @internal */
12792     function isNamedImportBindings(node) {
12793         var kind = node.kind;
12794         return kind === 264 /* NamedImports */
12795             || kind === 263 /* NamespaceImport */;
12796     }
12797     ts.isNamedImportBindings = isNamedImportBindings;
12798     /* @internal */
12799     function isModuleOrEnumDeclaration(node) {
12800         return node.kind === 256 /* ModuleDeclaration */ || node.kind === 255 /* EnumDeclaration */;
12801     }
12802     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12803     function isDeclarationKind(kind) {
12804         return kind === 209 /* ArrowFunction */
12805             || kind === 198 /* BindingElement */
12806             || kind === 252 /* ClassDeclaration */
12807             || kind === 221 /* ClassExpression */
12808             || kind === 166 /* Constructor */
12809             || kind === 255 /* EnumDeclaration */
12810             || kind === 291 /* EnumMember */
12811             || kind === 270 /* ExportSpecifier */
12812             || kind === 251 /* FunctionDeclaration */
12813             || kind === 208 /* FunctionExpression */
12814             || kind === 167 /* GetAccessor */
12815             || kind === 262 /* ImportClause */
12816             || kind === 260 /* ImportEqualsDeclaration */
12817             || kind === 265 /* ImportSpecifier */
12818             || kind === 253 /* InterfaceDeclaration */
12819             || kind === 280 /* JsxAttribute */
12820             || kind === 165 /* MethodDeclaration */
12821             || kind === 164 /* MethodSignature */
12822             || kind === 256 /* ModuleDeclaration */
12823             || kind === 259 /* NamespaceExportDeclaration */
12824             || kind === 263 /* NamespaceImport */
12825             || kind === 269 /* NamespaceExport */
12826             || kind === 160 /* Parameter */
12827             || kind === 288 /* PropertyAssignment */
12828             || kind === 163 /* PropertyDeclaration */
12829             || kind === 162 /* PropertySignature */
12830             || kind === 168 /* SetAccessor */
12831             || kind === 289 /* ShorthandPropertyAssignment */
12832             || kind === 254 /* TypeAliasDeclaration */
12833             || kind === 159 /* TypeParameter */
12834             || kind === 249 /* VariableDeclaration */
12835             || kind === 331 /* JSDocTypedefTag */
12836             || kind === 324 /* JSDocCallbackTag */
12837             || kind === 333 /* JSDocPropertyTag */;
12838     }
12839     function isDeclarationStatementKind(kind) {
12840         return kind === 251 /* FunctionDeclaration */
12841             || kind === 271 /* MissingDeclaration */
12842             || kind === 252 /* ClassDeclaration */
12843             || kind === 253 /* InterfaceDeclaration */
12844             || kind === 254 /* TypeAliasDeclaration */
12845             || kind === 255 /* EnumDeclaration */
12846             || kind === 256 /* ModuleDeclaration */
12847             || kind === 261 /* ImportDeclaration */
12848             || kind === 260 /* ImportEqualsDeclaration */
12849             || kind === 267 /* ExportDeclaration */
12850             || kind === 266 /* ExportAssignment */
12851             || kind === 259 /* NamespaceExportDeclaration */;
12852     }
12853     function isStatementKindButNotDeclarationKind(kind) {
12854         return kind === 241 /* BreakStatement */
12855             || kind === 240 /* ContinueStatement */
12856             || kind === 248 /* DebuggerStatement */
12857             || kind === 235 /* DoStatement */
12858             || kind === 233 /* ExpressionStatement */
12859             || kind === 231 /* EmptyStatement */
12860             || kind === 238 /* ForInStatement */
12861             || kind === 239 /* ForOfStatement */
12862             || kind === 237 /* ForStatement */
12863             || kind === 234 /* IfStatement */
12864             || kind === 245 /* LabeledStatement */
12865             || kind === 242 /* ReturnStatement */
12866             || kind === 244 /* SwitchStatement */
12867             || kind === 246 /* ThrowStatement */
12868             || kind === 247 /* TryStatement */
12869             || kind === 232 /* VariableStatement */
12870             || kind === 236 /* WhileStatement */
12871             || kind === 243 /* WithStatement */
12872             || kind === 335 /* NotEmittedStatement */
12873             || kind === 339 /* EndOfDeclarationMarker */
12874             || kind === 338 /* MergeDeclarationMarker */;
12875     }
12876     /* @internal */
12877     function isDeclaration(node) {
12878         if (node.kind === 159 /* TypeParameter */) {
12879             return (node.parent && node.parent.kind !== 330 /* JSDocTemplateTag */) || ts.isInJSFile(node);
12880         }
12881         return isDeclarationKind(node.kind);
12882     }
12883     ts.isDeclaration = isDeclaration;
12884     /* @internal */
12885     function isDeclarationStatement(node) {
12886         return isDeclarationStatementKind(node.kind);
12887     }
12888     ts.isDeclarationStatement = isDeclarationStatement;
12889     /**
12890      * Determines whether the node is a statement that is not also a declaration
12891      */
12892     /* @internal */
12893     function isStatementButNotDeclaration(node) {
12894         return isStatementKindButNotDeclarationKind(node.kind);
12895     }
12896     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
12897     /* @internal */
12898     function isStatement(node) {
12899         var kind = node.kind;
12900         return isStatementKindButNotDeclarationKind(kind)
12901             || isDeclarationStatementKind(kind)
12902             || isBlockStatement(node);
12903     }
12904     ts.isStatement = isStatement;
12905     function isBlockStatement(node) {
12906         if (node.kind !== 230 /* Block */)
12907             return false;
12908         if (node.parent !== undefined) {
12909             if (node.parent.kind === 247 /* TryStatement */ || node.parent.kind === 287 /* CatchClause */) {
12910                 return false;
12911             }
12912         }
12913         return !ts.isFunctionBlock(node);
12914     }
12915     /**
12916      * NOTE: This is similar to `isStatement` but does not access parent pointers.
12917      */
12918     /* @internal */
12919     function isStatementOrBlock(node) {
12920         var kind = node.kind;
12921         return isStatementKindButNotDeclarationKind(kind)
12922             || isDeclarationStatementKind(kind)
12923             || kind === 230 /* Block */;
12924     }
12925     ts.isStatementOrBlock = isStatementOrBlock;
12926     // Module references
12927     /* @internal */
12928     function isModuleReference(node) {
12929         var kind = node.kind;
12930         return kind === 272 /* ExternalModuleReference */
12931             || kind === 157 /* QualifiedName */
12932             || kind === 78 /* Identifier */;
12933     }
12934     ts.isModuleReference = isModuleReference;
12935     // JSX
12936     /* @internal */
12937     function isJsxTagNameExpression(node) {
12938         var kind = node.kind;
12939         return kind === 107 /* ThisKeyword */
12940             || kind === 78 /* Identifier */
12941             || kind === 201 /* PropertyAccessExpression */;
12942     }
12943     ts.isJsxTagNameExpression = isJsxTagNameExpression;
12944     /* @internal */
12945     function isJsxChild(node) {
12946         var kind = node.kind;
12947         return kind === 273 /* JsxElement */
12948             || kind === 283 /* JsxExpression */
12949             || kind === 274 /* JsxSelfClosingElement */
12950             || kind === 11 /* JsxText */
12951             || kind === 277 /* JsxFragment */;
12952     }
12953     ts.isJsxChild = isJsxChild;
12954     /* @internal */
12955     function isJsxAttributeLike(node) {
12956         var kind = node.kind;
12957         return kind === 280 /* JsxAttribute */
12958             || kind === 282 /* JsxSpreadAttribute */;
12959     }
12960     ts.isJsxAttributeLike = isJsxAttributeLike;
12961     /* @internal */
12962     function isStringLiteralOrJsxExpression(node) {
12963         var kind = node.kind;
12964         return kind === 10 /* StringLiteral */
12965             || kind === 283 /* JsxExpression */;
12966     }
12967     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
12968     function isJsxOpeningLikeElement(node) {
12969         var kind = node.kind;
12970         return kind === 275 /* JsxOpeningElement */
12971             || kind === 274 /* JsxSelfClosingElement */;
12972     }
12973     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
12974     // Clauses
12975     function isCaseOrDefaultClause(node) {
12976         var kind = node.kind;
12977         return kind === 284 /* CaseClause */
12978             || kind === 285 /* DefaultClause */;
12979     }
12980     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
12981     // JSDoc
12982     /** True if node is of some JSDoc syntax kind. */
12983     /* @internal */
12984     function isJSDocNode(node) {
12985         return node.kind >= 301 /* FirstJSDocNode */ && node.kind <= 333 /* LastJSDocNode */;
12986     }
12987     ts.isJSDocNode = isJSDocNode;
12988     /** True if node is of a kind that may contain comment text. */
12989     function isJSDocCommentContainingNode(node) {
12990         return node.kind === 311 /* JSDocComment */ || node.kind === 310 /* JSDocNamepathType */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
12991     }
12992     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
12993     // TODO: determine what this does before making it public.
12994     /* @internal */
12995     function isJSDocTag(node) {
12996         return node.kind >= 314 /* FirstJSDocTagNode */ && node.kind <= 333 /* LastJSDocTagNode */;
12997     }
12998     ts.isJSDocTag = isJSDocTag;
12999     function isSetAccessor(node) {
13000         return node.kind === 168 /* SetAccessor */;
13001     }
13002     ts.isSetAccessor = isSetAccessor;
13003     function isGetAccessor(node) {
13004         return node.kind === 167 /* GetAccessor */;
13005     }
13006     ts.isGetAccessor = isGetAccessor;
13007     /** True if has jsdoc nodes attached to it. */
13008     /* @internal */
13009     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
13010     function hasJSDocNodes(node) {
13011         var jsDoc = node.jsDoc;
13012         return !!jsDoc && jsDoc.length > 0;
13013     }
13014     ts.hasJSDocNodes = hasJSDocNodes;
13015     /** True if has type node attached to it. */
13016     /* @internal */
13017     function hasType(node) {
13018         return !!node.type;
13019     }
13020     ts.hasType = hasType;
13021     /** True if has initializer node attached to it. */
13022     /* @internal */
13023     function hasInitializer(node) {
13024         return !!node.initializer;
13025     }
13026     ts.hasInitializer = hasInitializer;
13027     /** True if has initializer node attached to it. */
13028     function hasOnlyExpressionInitializer(node) {
13029         switch (node.kind) {
13030             case 249 /* VariableDeclaration */:
13031             case 160 /* Parameter */:
13032             case 198 /* BindingElement */:
13033             case 162 /* PropertySignature */:
13034             case 163 /* PropertyDeclaration */:
13035             case 288 /* PropertyAssignment */:
13036             case 291 /* EnumMember */:
13037                 return true;
13038             default:
13039                 return false;
13040         }
13041     }
13042     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
13043     function isObjectLiteralElement(node) {
13044         return node.kind === 280 /* JsxAttribute */ || node.kind === 282 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
13045     }
13046     ts.isObjectLiteralElement = isObjectLiteralElement;
13047     /* @internal */
13048     function isTypeReferenceType(node) {
13049         return node.kind === 173 /* TypeReference */ || node.kind === 223 /* ExpressionWithTypeArguments */;
13050     }
13051     ts.isTypeReferenceType = isTypeReferenceType;
13052     var MAX_SMI_X86 = 1073741823;
13053     /* @internal */
13054     function guessIndentation(lines) {
13055         var indentation = MAX_SMI_X86;
13056         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
13057             var line = lines_1[_i];
13058             if (!line.length) {
13059                 continue;
13060             }
13061             var i = 0;
13062             for (; i < line.length && i < indentation; i++) {
13063                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
13064                     break;
13065                 }
13066             }
13067             if (i < indentation) {
13068                 indentation = i;
13069             }
13070             if (indentation === 0) {
13071                 return 0;
13072             }
13073         }
13074         return indentation === MAX_SMI_X86 ? undefined : indentation;
13075     }
13076     ts.guessIndentation = guessIndentation;
13077     function isStringLiteralLike(node) {
13078         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
13079     }
13080     ts.isStringLiteralLike = isStringLiteralLike;
13081     // #endregion
13082 })(ts || (ts = {}));
13083 /* @internal */
13084 var ts;
13085 (function (ts) {
13086     ts.resolvingEmptyArray = [];
13087     ts.externalHelpersModuleNameText = "tslib";
13088     ts.defaultMaximumTruncationLength = 160;
13089     ts.noTruncationMaximumTruncationLength = 1000000;
13090     function getDeclarationOfKind(symbol, kind) {
13091         var declarations = symbol.declarations;
13092         if (declarations) {
13093             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
13094                 var declaration = declarations_1[_i];
13095                 if (declaration.kind === kind) {
13096                     return declaration;
13097                 }
13098             }
13099         }
13100         return undefined;
13101     }
13102     ts.getDeclarationOfKind = getDeclarationOfKind;
13103     /**
13104      * Create a new escaped identifier map.
13105      * @deprecated Use `new Map<__String, T>()` instead.
13106      */
13107     function createUnderscoreEscapedMap() {
13108         return new ts.Map();
13109     }
13110     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
13111     /**
13112      * @deprecated Use `!!map?.size` instead
13113      */
13114     function hasEntries(map) {
13115         return !!map && !!map.size;
13116     }
13117     ts.hasEntries = hasEntries;
13118     function createSymbolTable(symbols) {
13119         var result = new ts.Map();
13120         if (symbols) {
13121             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
13122                 var symbol = symbols_1[_i];
13123                 result.set(symbol.escapedName, symbol);
13124             }
13125         }
13126         return result;
13127     }
13128     ts.createSymbolTable = createSymbolTable;
13129     function isTransientSymbol(symbol) {
13130         return (symbol.flags & 33554432 /* Transient */) !== 0;
13131     }
13132     ts.isTransientSymbol = isTransientSymbol;
13133     var stringWriter = createSingleLineStringWriter();
13134     function createSingleLineStringWriter() {
13135         var str = "";
13136         var writeText = function (text) { return str += text; };
13137         return {
13138             getText: function () { return str; },
13139             write: writeText,
13140             rawWrite: writeText,
13141             writeKeyword: writeText,
13142             writeOperator: writeText,
13143             writePunctuation: writeText,
13144             writeSpace: writeText,
13145             writeStringLiteral: writeText,
13146             writeLiteral: writeText,
13147             writeParameter: writeText,
13148             writeProperty: writeText,
13149             writeSymbol: function (s, _) { return writeText(s); },
13150             writeTrailingSemicolon: writeText,
13151             writeComment: writeText,
13152             getTextPos: function () { return str.length; },
13153             getLine: function () { return 0; },
13154             getColumn: function () { return 0; },
13155             getIndent: function () { return 0; },
13156             isAtStartOfLine: function () { return false; },
13157             hasTrailingComment: function () { return false; },
13158             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
13159             // Completely ignore indentation for string writers.  And map newlines to
13160             // a single space.
13161             writeLine: function () { return str += " "; },
13162             increaseIndent: ts.noop,
13163             decreaseIndent: ts.noop,
13164             clear: function () { return str = ""; },
13165             trackSymbol: ts.noop,
13166             reportInaccessibleThisError: ts.noop,
13167             reportInaccessibleUniqueSymbolError: ts.noop,
13168             reportPrivateInBaseOfClassExpression: ts.noop,
13169         };
13170     }
13171     function changesAffectModuleResolution(oldOptions, newOptions) {
13172         return oldOptions.configFilePath !== newOptions.configFilePath ||
13173             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
13174     }
13175     ts.changesAffectModuleResolution = changesAffectModuleResolution;
13176     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
13177         return ts.moduleResolutionOptionDeclarations.some(function (o) {
13178             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
13179         });
13180     }
13181     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
13182     function forEachAncestor(node, callback) {
13183         while (true) {
13184             var res = callback(node);
13185             if (res === "quit")
13186                 return undefined;
13187             if (res !== undefined)
13188                 return res;
13189             if (ts.isSourceFile(node))
13190                 return undefined;
13191             node = node.parent;
13192         }
13193     }
13194     ts.forEachAncestor = forEachAncestor;
13195     /**
13196      * Calls `callback` for each entry in the map, returning the first truthy result.
13197      * Use `map.forEach` instead for normal iteration.
13198      */
13199     function forEachEntry(map, callback) {
13200         var iterator = map.entries();
13201         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
13202             var _a = iterResult.value, key = _a[0], value = _a[1];
13203             var result = callback(value, key);
13204             if (result) {
13205                 return result;
13206             }
13207         }
13208         return undefined;
13209     }
13210     ts.forEachEntry = forEachEntry;
13211     /** `forEachEntry` for just keys. */
13212     function forEachKey(map, callback) {
13213         var iterator = map.keys();
13214         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
13215             var result = callback(iterResult.value);
13216             if (result) {
13217                 return result;
13218             }
13219         }
13220         return undefined;
13221     }
13222     ts.forEachKey = forEachKey;
13223     /** Copy entries from `source` to `target`. */
13224     function copyEntries(source, target) {
13225         source.forEach(function (value, key) {
13226             target.set(key, value);
13227         });
13228     }
13229     ts.copyEntries = copyEntries;
13230     function usingSingleLineStringWriter(action) {
13231         var oldString = stringWriter.getText();
13232         try {
13233             action(stringWriter);
13234             return stringWriter.getText();
13235         }
13236         finally {
13237             stringWriter.clear();
13238             stringWriter.writeKeyword(oldString);
13239         }
13240     }
13241     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
13242     function getFullWidth(node) {
13243         return node.end - node.pos;
13244     }
13245     ts.getFullWidth = getFullWidth;
13246     function getResolvedModule(sourceFile, moduleNameText) {
13247         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
13248     }
13249     ts.getResolvedModule = getResolvedModule;
13250     function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
13251         if (!sourceFile.resolvedModules) {
13252             sourceFile.resolvedModules = new ts.Map();
13253         }
13254         sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
13255     }
13256     ts.setResolvedModule = setResolvedModule;
13257     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
13258         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
13259             sourceFile.resolvedTypeReferenceDirectiveNames = new ts.Map();
13260         }
13261         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
13262     }
13263     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
13264     function projectReferenceIsEqualTo(oldRef, newRef) {
13265         return oldRef.path === newRef.path &&
13266             !oldRef.prepend === !newRef.prepend &&
13267             !oldRef.circular === !newRef.circular;
13268     }
13269     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
13270     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
13271         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
13272             oldResolution.extension === newResolution.extension &&
13273             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
13274             oldResolution.originalPath === newResolution.originalPath &&
13275             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
13276     }
13277     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
13278     function packageIdIsEqual(a, b) {
13279         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
13280     }
13281     function packageIdToString(_a) {
13282         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
13283         var fullName = subModuleName ? name + "/" + subModuleName : name;
13284         return fullName + "@" + version;
13285     }
13286     ts.packageIdToString = packageIdToString;
13287     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
13288         return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
13289     }
13290     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
13291     function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
13292         ts.Debug.assert(names.length === newResolutions.length);
13293         for (var i = 0; i < names.length; i++) {
13294             var newResolution = newResolutions[i];
13295             var oldResolution = oldResolutions && oldResolutions.get(names[i]);
13296             var changed = oldResolution
13297                 ? !newResolution || !comparer(oldResolution, newResolution)
13298                 : newResolution;
13299             if (changed) {
13300                 return true;
13301             }
13302         }
13303         return false;
13304     }
13305     ts.hasChangesInResolutions = hasChangesInResolutions;
13306     // Returns true if this node contains a parse error anywhere underneath it.
13307     function containsParseError(node) {
13308         aggregateChildData(node);
13309         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
13310     }
13311     ts.containsParseError = containsParseError;
13312     function aggregateChildData(node) {
13313         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
13314             // A node is considered to contain a parse error if:
13315             //  a) the parser explicitly marked that it had an error
13316             //  b) any of it's children reported that it had an error.
13317             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
13318                 ts.forEachChild(node, containsParseError);
13319             // If so, mark ourselves accordingly.
13320             if (thisNodeOrAnySubNodesHasError) {
13321                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
13322             }
13323             // Also mark that we've propagated the child information to this node.  This way we can
13324             // always consult the bit directly on this node without needing to check its children
13325             // again.
13326             node.flags |= 524288 /* HasAggregatedChildData */;
13327         }
13328     }
13329     function getSourceFileOfNode(node) {
13330         while (node && node.kind !== 297 /* SourceFile */) {
13331             node = node.parent;
13332         }
13333         return node;
13334     }
13335     ts.getSourceFileOfNode = getSourceFileOfNode;
13336     function isStatementWithLocals(node) {
13337         switch (node.kind) {
13338             case 230 /* Block */:
13339             case 258 /* CaseBlock */:
13340             case 237 /* ForStatement */:
13341             case 238 /* ForInStatement */:
13342             case 239 /* ForOfStatement */:
13343                 return true;
13344         }
13345         return false;
13346     }
13347     ts.isStatementWithLocals = isStatementWithLocals;
13348     function getStartPositionOfLine(line, sourceFile) {
13349         ts.Debug.assert(line >= 0);
13350         return ts.getLineStarts(sourceFile)[line];
13351     }
13352     ts.getStartPositionOfLine = getStartPositionOfLine;
13353     // This is a useful function for debugging purposes.
13354     function nodePosToString(node) {
13355         var file = getSourceFileOfNode(node);
13356         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
13357         return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
13358     }
13359     ts.nodePosToString = nodePosToString;
13360     function getEndLinePosition(line, sourceFile) {
13361         ts.Debug.assert(line >= 0);
13362         var lineStarts = ts.getLineStarts(sourceFile);
13363         var lineIndex = line;
13364         var sourceText = sourceFile.text;
13365         if (lineIndex + 1 === lineStarts.length) {
13366             // last line - return EOF
13367             return sourceText.length - 1;
13368         }
13369         else {
13370             // current line start
13371             var start = lineStarts[lineIndex];
13372             // take the start position of the next line - 1 = it should be some line break
13373             var pos = lineStarts[lineIndex + 1] - 1;
13374             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
13375             // walk backwards skipping line breaks, stop the the beginning of current line.
13376             // i.e:
13377             // <some text>
13378             // $ <- end of line for this position should match the start position
13379             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
13380                 pos--;
13381             }
13382             return pos;
13383         }
13384     }
13385     ts.getEndLinePosition = getEndLinePosition;
13386     /**
13387      * Returns a value indicating whether a name is unique globally or within the current file.
13388      * 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`.
13389      */
13390     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
13391         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
13392     }
13393     ts.isFileLevelUniqueName = isFileLevelUniqueName;
13394     // Returns true if this node is missing from the actual source code. A 'missing' node is different
13395     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
13396     // in the tree), it is definitely missing. However, a node may be defined, but still be
13397     // missing.  This happens whenever the parser knows it needs to parse something, but can't
13398     // get anything in the source code that it expects at that location. For example:
13399     //
13400     //          let a: ;
13401     //
13402     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
13403     // code). So the parser will attempt to parse out a type, and will create an actual node.
13404     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
13405     // contained within it.
13406     function nodeIsMissing(node) {
13407         if (node === undefined) {
13408             return true;
13409         }
13410         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
13411     }
13412     ts.nodeIsMissing = nodeIsMissing;
13413     function nodeIsPresent(node) {
13414         return !nodeIsMissing(node);
13415     }
13416     ts.nodeIsPresent = nodeIsPresent;
13417     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
13418         if (from === undefined || from.length === 0)
13419             return to;
13420         var statementIndex = 0;
13421         // skip all prologue directives to insert at the correct position
13422         for (; statementIndex < to.length; ++statementIndex) {
13423             if (!isPrologueDirective(to[statementIndex])) {
13424                 break;
13425             }
13426         }
13427         to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
13428         return to;
13429     }
13430     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
13431         if (statement === undefined)
13432             return to;
13433         var statementIndex = 0;
13434         // skip all prologue directives to insert at the correct position
13435         for (; statementIndex < to.length; ++statementIndex) {
13436             if (!isPrologueDirective(to[statementIndex])) {
13437                 break;
13438             }
13439         }
13440         to.splice(statementIndex, 0, statement);
13441         return to;
13442     }
13443     function isAnyPrologueDirective(node) {
13444         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13445     }
13446     /**
13447      * Prepends statements to an array while taking care of prologue directives.
13448      */
13449     function insertStatementsAfterStandardPrologue(to, from) {
13450         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
13451     }
13452     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
13453     function insertStatementsAfterCustomPrologue(to, from) {
13454         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
13455     }
13456     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
13457     /**
13458      * Prepends statements to an array while taking care of prologue directives.
13459      */
13460     function insertStatementAfterStandardPrologue(to, statement) {
13461         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
13462     }
13463     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
13464     function insertStatementAfterCustomPrologue(to, statement) {
13465         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
13466     }
13467     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
13468     /**
13469      * Determine if the given comment is a triple-slash
13470      *
13471      * @return true if the comment is a triple-slash comment else false
13472      */
13473     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
13474         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
13475         // so that we don't end up computing comment string and doing match for all // comments
13476         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
13477             commentPos + 2 < commentEnd &&
13478             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
13479             var textSubStr = text.substring(commentPos, commentEnd);
13480             return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
13481                 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
13482                 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
13483                 textSubStr.match(defaultLibReferenceRegEx) ?
13484                 true : false;
13485         }
13486         return false;
13487     }
13488     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
13489     function isPinnedComment(text, start) {
13490         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
13491             text.charCodeAt(start + 2) === 33 /* exclamation */;
13492     }
13493     ts.isPinnedComment = isPinnedComment;
13494     function createCommentDirectivesMap(sourceFile, commentDirectives) {
13495         var directivesByLine = new ts.Map(commentDirectives.map(function (commentDirective) { return ([
13496             "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
13497             commentDirective,
13498         ]); }));
13499         var usedLines = new ts.Map();
13500         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
13501         function getUnusedExpectations() {
13502             return ts.arrayFrom(directivesByLine.entries())
13503                 .filter(function (_a) {
13504                 var line = _a[0], directive = _a[1];
13505                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
13506             })
13507                 .map(function (_a) {
13508                 var _ = _a[0], directive = _a[1];
13509                 return directive;
13510             });
13511         }
13512         function markUsed(line) {
13513             if (!directivesByLine.has("" + line)) {
13514                 return false;
13515             }
13516             usedLines.set("" + line, true);
13517             return true;
13518         }
13519     }
13520     ts.createCommentDirectivesMap = createCommentDirectivesMap;
13521     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
13522         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
13523         // want to skip trivia because this will launch us forward to the next token.
13524         if (nodeIsMissing(node)) {
13525             return node.pos;
13526         }
13527         if (ts.isJSDocNode(node) || node.kind === 11 /* JsxText */) {
13528             // JsxText cannot actually contain comments, even though the scanner will think it sees comments
13529             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
13530         }
13531         if (includeJsDoc && ts.hasJSDocNodes(node)) {
13532             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
13533         }
13534         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
13535         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
13536         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
13537         // first child to determine the actual position of its first token.
13538         if (node.kind === 334 /* SyntaxList */ && node._children.length > 0) {
13539             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
13540         }
13541         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
13542     }
13543     ts.getTokenPosOfNode = getTokenPosOfNode;
13544     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
13545         if (nodeIsMissing(node) || !node.decorators) {
13546             return getTokenPosOfNode(node, sourceFile);
13547         }
13548         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
13549     }
13550     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
13551     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
13552         if (includeTrivia === void 0) { includeTrivia = false; }
13553         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
13554     }
13555     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
13556     function isJSDocTypeExpressionOrChild(node) {
13557         return !!ts.findAncestor(node, ts.isJSDocTypeExpression);
13558     }
13559     function isExportNamespaceAsDefaultDeclaration(node) {
13560         return !!(ts.isExportDeclaration(node) && node.exportClause && ts.isNamespaceExport(node.exportClause) && node.exportClause.name.escapedText === "default");
13561     }
13562     ts.isExportNamespaceAsDefaultDeclaration = isExportNamespaceAsDefaultDeclaration;
13563     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
13564         if (includeTrivia === void 0) { includeTrivia = false; }
13565         if (nodeIsMissing(node)) {
13566             return "";
13567         }
13568         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
13569         if (isJSDocTypeExpressionOrChild(node)) {
13570             // strip space + asterisk at line start
13571             text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
13572         }
13573         return text;
13574     }
13575     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
13576     function getTextOfNode(node, includeTrivia) {
13577         if (includeTrivia === void 0) { includeTrivia = false; }
13578         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
13579     }
13580     ts.getTextOfNode = getTextOfNode;
13581     function getPos(range) {
13582         return range.pos;
13583     }
13584     /**
13585      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13586      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13587      */
13588     function indexOfNode(nodeArray, node) {
13589         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13590     }
13591     ts.indexOfNode = indexOfNode;
13592     /**
13593      * Gets flags that control emit behavior of a node.
13594      */
13595     function getEmitFlags(node) {
13596         var emitNode = node.emitNode;
13597         return emitNode && emitNode.flags || 0;
13598     }
13599     ts.getEmitFlags = getEmitFlags;
13600     ;
13601     function getScriptTargetFeatures() {
13602         return {
13603             es2015: {
13604                 Array: ["find", "findIndex", "fill", "copyWithin", "entries", "keys", "values"],
13605                 RegExp: ["flags", "sticky", "unicode"],
13606                 Reflect: ["apply", "construct", "defineProperty", "deleteProperty", "get", " getOwnPropertyDescriptor", "getPrototypeOf", "has", "isExtensible", "ownKeys", "preventExtensions", "set", "setPrototypeOf"],
13607                 ArrayConstructor: ["from", "of"],
13608                 ObjectConstructor: ["assign", "getOwnPropertySymbols", "keys", "is", "setPrototypeOf"],
13609                 NumberConstructor: ["isFinite", "isInteger", "isNaN", "isSafeInteger", "parseFloat", "parseInt"],
13610                 Math: ["clz32", "imul", "sign", "log10", "log2", "log1p", "expm1", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "hypot", "trunc", "fround", "cbrt"],
13611                 Map: ["entries", "keys", "values"],
13612                 Set: ["entries", "keys", "values"],
13613                 Promise: ts.emptyArray,
13614                 PromiseConstructor: ["all", "race", "reject", "resolve"],
13615                 Symbol: ["for", "keyFor"],
13616                 WeakMap: ["entries", "keys", "values"],
13617                 WeakSet: ["entries", "keys", "values"],
13618                 Iterator: ts.emptyArray,
13619                 AsyncIterator: ts.emptyArray,
13620                 String: ["codePointAt", "includes", "endsWith", "normalize", "repeat", "startsWith", "anchor", "big", "blink", "bold", "fixed", "fontcolor", "fontsize", "italics", "link", "small", "strike", "sub", "sup"],
13621                 StringConstructor: ["fromCodePoint", "raw"]
13622             },
13623             es2016: {
13624                 Array: ["includes"]
13625             },
13626             es2017: {
13627                 Atomics: ts.emptyArray,
13628                 SharedArrayBuffer: ts.emptyArray,
13629                 String: ["padStart", "padEnd"],
13630                 ObjectConstructor: ["values", "entries", "getOwnPropertyDescriptors"],
13631                 DateTimeFormat: ["formatToParts"]
13632             },
13633             es2018: {
13634                 Promise: ["finally"],
13635                 RegExpMatchArray: ["groups"],
13636                 RegExpExecArray: ["groups"],
13637                 RegExp: ["dotAll"],
13638                 Intl: ["PluralRules"],
13639                 AsyncIterable: ts.emptyArray,
13640                 AsyncIterableIterator: ts.emptyArray,
13641                 AsyncGenerator: ts.emptyArray,
13642                 AsyncGeneratorFunction: ts.emptyArray,
13643             },
13644             es2019: {
13645                 Array: ["flat", "flatMap"],
13646                 ObjectConstructor: ["fromEntries"],
13647                 String: ["trimStart", "trimEnd", "trimLeft", "trimRight"],
13648                 Symbol: ["description"]
13649             },
13650             es2020: {
13651                 BigInt: ts.emptyArray,
13652                 BigInt64Array: ts.emptyArray,
13653                 BigUint64Array: ts.emptyArray,
13654                 PromiseConstructor: ["allSettled"],
13655                 SymbolConstructor: ["matchAll"],
13656                 String: ["matchAll"],
13657                 DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"],
13658                 RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"]
13659             },
13660             esnext: {
13661                 PromiseConstructor: ["any"],
13662                 String: ["replaceAll"],
13663                 NumberFormat: ["formatToParts"]
13664             }
13665         };
13666     }
13667     ts.getScriptTargetFeatures = getScriptTargetFeatures;
13668     var GetLiteralTextFlags;
13669     (function (GetLiteralTextFlags) {
13670         GetLiteralTextFlags[GetLiteralTextFlags["None"] = 0] = "None";
13671         GetLiteralTextFlags[GetLiteralTextFlags["NeverAsciiEscape"] = 1] = "NeverAsciiEscape";
13672         GetLiteralTextFlags[GetLiteralTextFlags["JsxAttributeEscape"] = 2] = "JsxAttributeEscape";
13673         GetLiteralTextFlags[GetLiteralTextFlags["TerminateUnterminatedLiterals"] = 4] = "TerminateUnterminatedLiterals";
13674     })(GetLiteralTextFlags = ts.GetLiteralTextFlags || (ts.GetLiteralTextFlags = {}));
13675     function getLiteralText(node, sourceFile, flags) {
13676         // If we don't need to downlevel and we can reach the original source text using
13677         // the node's parent reference, then simply get the text as it was originally written.
13678         if (!nodeIsSynthesized(node) && node.parent && !(flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
13679             ts.isBigIntLiteral(node))) {
13680             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13681         }
13682         // If we can't reach the original source text, use the canonical form if it's a number,
13683         // or a (possibly escaped) quoted form of the original text if it's string-like.
13684         switch (node.kind) {
13685             case 10 /* StringLiteral */: {
13686                 var escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString :
13687                     flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13688                         escapeNonAsciiString;
13689                 if (node.singleQuote) {
13690                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13691                 }
13692                 else {
13693                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13694                 }
13695             }
13696             case 14 /* NoSubstitutionTemplateLiteral */:
13697             case 15 /* TemplateHead */:
13698             case 16 /* TemplateMiddle */:
13699             case 17 /* TemplateTail */: {
13700                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13701                 // had to include a backslash: `not \${a} substitution`.
13702                 var escapeText = flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13703                     escapeNonAsciiString;
13704                 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13705                 switch (node.kind) {
13706                     case 14 /* NoSubstitutionTemplateLiteral */:
13707                         return "`" + rawText + "`";
13708                     case 15 /* TemplateHead */:
13709                         return "`" + rawText + "${";
13710                     case 16 /* TemplateMiddle */:
13711                         return "}" + rawText + "${";
13712                     case 17 /* TemplateTail */:
13713                         return "}" + rawText + "`";
13714                 }
13715                 break;
13716             }
13717             case 8 /* NumericLiteral */:
13718             case 9 /* BigIntLiteral */:
13719                 return node.text;
13720             case 13 /* RegularExpressionLiteral */:
13721                 if (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) {
13722                     return node.text + (node.text.charCodeAt(node.text.length - 1) === 92 /* backslash */ ? " /" : "/");
13723                 }
13724                 return node.text;
13725         }
13726         return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13727     }
13728     ts.getLiteralText = getLiteralText;
13729     function getTextOfConstantValue(value) {
13730         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13731     }
13732     ts.getTextOfConstantValue = getTextOfConstantValue;
13733     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13734     // all non-alphanumeric characters with underscores
13735     function makeIdentifierFromModuleName(moduleName) {
13736         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13737     }
13738     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13739     function isBlockOrCatchScoped(declaration) {
13740         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13741             isCatchClauseVariableDeclarationOrBindingElement(declaration);
13742     }
13743     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13744     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13745         var node = getRootDeclaration(declaration);
13746         return node.kind === 249 /* VariableDeclaration */ && node.parent.kind === 287 /* CatchClause */;
13747     }
13748     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13749     function isAmbientModule(node) {
13750         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13751     }
13752     ts.isAmbientModule = isAmbientModule;
13753     function isModuleWithStringLiteralName(node) {
13754         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13755     }
13756     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13757     function isNonGlobalAmbientModule(node) {
13758         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13759     }
13760     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13761     /**
13762      * An effective module (namespace) declaration is either
13763      * 1. An actual declaration: namespace X { ... }
13764      * 2. A Javascript declaration, which is:
13765      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13766      */
13767     function isEffectiveModuleDeclaration(node) {
13768         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13769     }
13770     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13771     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13772     function isShorthandAmbientModuleSymbol(moduleSymbol) {
13773         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13774     }
13775     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13776     function isShorthandAmbientModule(node) {
13777         // The only kind of module that can be missing a body is a shorthand ambient module.
13778         return node && node.kind === 256 /* ModuleDeclaration */ && (!node.body);
13779     }
13780     function isBlockScopedContainerTopLevel(node) {
13781         return node.kind === 297 /* SourceFile */ ||
13782             node.kind === 256 /* ModuleDeclaration */ ||
13783             ts.isFunctionLike(node);
13784     }
13785     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13786     function isGlobalScopeAugmentation(module) {
13787         return !!(module.flags & 1024 /* GlobalAugmentation */);
13788     }
13789     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13790     function isExternalModuleAugmentation(node) {
13791         return isAmbientModule(node) && isModuleAugmentationExternal(node);
13792     }
13793     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13794     function isModuleAugmentationExternal(node) {
13795         // external module augmentation is a ambient module declaration that is either:
13796         // - defined in the top level scope and source file is an external module
13797         // - defined inside ambient module declaration located in the top level scope and source file not an external module
13798         switch (node.parent.kind) {
13799             case 297 /* SourceFile */:
13800                 return ts.isExternalModule(node.parent);
13801             case 257 /* ModuleBlock */:
13802                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
13803         }
13804         return false;
13805     }
13806     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
13807     function getNonAugmentationDeclaration(symbol) {
13808         return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
13809     }
13810     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
13811     function isEffectiveExternalModule(node, compilerOptions) {
13812         return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
13813     }
13814     ts.isEffectiveExternalModule = isEffectiveExternalModule;
13815     /**
13816      * Returns whether the source file will be treated as if it were in strict mode at runtime.
13817      */
13818     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
13819         // We can only verify strict mode for JS/TS files
13820         switch (node.scriptKind) {
13821             case 1 /* JS */:
13822             case 3 /* TS */:
13823             case 2 /* JSX */:
13824             case 4 /* TSX */:
13825                 break;
13826             default:
13827                 return false;
13828         }
13829         // Strict mode does not matter for declaration files.
13830         if (node.isDeclarationFile) {
13831             return false;
13832         }
13833         // If `alwaysStrict` is set, then treat the file as strict.
13834         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
13835             return true;
13836         }
13837         // Starting with a "use strict" directive indicates the file is strict.
13838         if (ts.startsWithUseStrict(node.statements)) {
13839             return true;
13840         }
13841         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
13842             // ECMAScript Modules are always strict.
13843             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
13844                 return true;
13845             }
13846             // Other modules are strict unless otherwise specified.
13847             return !compilerOptions.noImplicitUseStrict;
13848         }
13849         return false;
13850     }
13851     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
13852     function isBlockScope(node, parentNode) {
13853         switch (node.kind) {
13854             case 297 /* SourceFile */:
13855             case 258 /* CaseBlock */:
13856             case 287 /* CatchClause */:
13857             case 256 /* ModuleDeclaration */:
13858             case 237 /* ForStatement */:
13859             case 238 /* ForInStatement */:
13860             case 239 /* ForOfStatement */:
13861             case 166 /* Constructor */:
13862             case 165 /* MethodDeclaration */:
13863             case 167 /* GetAccessor */:
13864             case 168 /* SetAccessor */:
13865             case 251 /* FunctionDeclaration */:
13866             case 208 /* FunctionExpression */:
13867             case 209 /* ArrowFunction */:
13868                 return true;
13869             case 230 /* Block */:
13870                 // function block is not considered block-scope container
13871                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
13872                 return !ts.isFunctionLike(parentNode);
13873         }
13874         return false;
13875     }
13876     ts.isBlockScope = isBlockScope;
13877     function isDeclarationWithTypeParameters(node) {
13878         switch (node.kind) {
13879             case 324 /* JSDocCallbackTag */:
13880             case 331 /* JSDocTypedefTag */:
13881             case 313 /* JSDocSignature */:
13882                 return true;
13883             default:
13884                 ts.assertType(node);
13885                 return isDeclarationWithTypeParameterChildren(node);
13886         }
13887     }
13888     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
13889     function isDeclarationWithTypeParameterChildren(node) {
13890         switch (node.kind) {
13891             case 169 /* CallSignature */:
13892             case 170 /* ConstructSignature */:
13893             case 164 /* MethodSignature */:
13894             case 171 /* IndexSignature */:
13895             case 174 /* FunctionType */:
13896             case 175 /* ConstructorType */:
13897             case 308 /* JSDocFunctionType */:
13898             case 252 /* ClassDeclaration */:
13899             case 221 /* ClassExpression */:
13900             case 253 /* InterfaceDeclaration */:
13901             case 254 /* TypeAliasDeclaration */:
13902             case 330 /* JSDocTemplateTag */:
13903             case 251 /* FunctionDeclaration */:
13904             case 165 /* MethodDeclaration */:
13905             case 166 /* Constructor */:
13906             case 167 /* GetAccessor */:
13907             case 168 /* SetAccessor */:
13908             case 208 /* FunctionExpression */:
13909             case 209 /* ArrowFunction */:
13910                 return true;
13911             default:
13912                 ts.assertType(node);
13913                 return false;
13914         }
13915     }
13916     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
13917     function isAnyImportSyntax(node) {
13918         switch (node.kind) {
13919             case 261 /* ImportDeclaration */:
13920             case 260 /* ImportEqualsDeclaration */:
13921                 return true;
13922             default:
13923                 return false;
13924         }
13925     }
13926     ts.isAnyImportSyntax = isAnyImportSyntax;
13927     function isLateVisibilityPaintedStatement(node) {
13928         switch (node.kind) {
13929             case 261 /* ImportDeclaration */:
13930             case 260 /* ImportEqualsDeclaration */:
13931             case 232 /* VariableStatement */:
13932             case 252 /* ClassDeclaration */:
13933             case 251 /* FunctionDeclaration */:
13934             case 256 /* ModuleDeclaration */:
13935             case 254 /* TypeAliasDeclaration */:
13936             case 253 /* InterfaceDeclaration */:
13937             case 255 /* EnumDeclaration */:
13938                 return true;
13939             default:
13940                 return false;
13941         }
13942     }
13943     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
13944     function isAnyImportOrReExport(node) {
13945         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
13946     }
13947     ts.isAnyImportOrReExport = isAnyImportOrReExport;
13948     // Gets the nearest enclosing block scope container that has the provided node
13949     // as a descendant, that is not the provided node.
13950     function getEnclosingBlockScopeContainer(node) {
13951         return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
13952     }
13953     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
13954     // Return display name of an identifier
13955     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
13956     // text of the expression in the computed property.
13957     function declarationNameToString(name) {
13958         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
13959     }
13960     ts.declarationNameToString = declarationNameToString;
13961     function getNameFromIndexInfo(info) {
13962         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
13963     }
13964     ts.getNameFromIndexInfo = getNameFromIndexInfo;
13965     function isComputedNonLiteralName(name) {
13966         return name.kind === 158 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
13967     }
13968     ts.isComputedNonLiteralName = isComputedNonLiteralName;
13969     function getTextOfPropertyName(name) {
13970         switch (name.kind) {
13971             case 78 /* Identifier */:
13972             case 79 /* PrivateIdentifier */:
13973                 return name.escapedText;
13974             case 10 /* StringLiteral */:
13975             case 8 /* NumericLiteral */:
13976             case 14 /* NoSubstitutionTemplateLiteral */:
13977                 return ts.escapeLeadingUnderscores(name.text);
13978             case 158 /* ComputedPropertyName */:
13979                 if (isStringOrNumericLiteralLike(name.expression))
13980                     return ts.escapeLeadingUnderscores(name.expression.text);
13981                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
13982             default:
13983                 return ts.Debug.assertNever(name);
13984         }
13985     }
13986     ts.getTextOfPropertyName = getTextOfPropertyName;
13987     function entityNameToString(name) {
13988         switch (name.kind) {
13989             case 107 /* ThisKeyword */:
13990                 return "this";
13991             case 79 /* PrivateIdentifier */:
13992             case 78 /* Identifier */:
13993                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
13994             case 157 /* QualifiedName */:
13995                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
13996             case 201 /* PropertyAccessExpression */:
13997                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
13998                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
13999                 }
14000                 else {
14001                     return ts.Debug.assertNever(name.name);
14002                 }
14003             default:
14004                 return ts.Debug.assertNever(name);
14005         }
14006     }
14007     ts.entityNameToString = entityNameToString;
14008     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
14009         var sourceFile = getSourceFileOfNode(node);
14010         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
14011     }
14012     ts.createDiagnosticForNode = createDiagnosticForNode;
14013     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
14014         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
14015         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
14016     }
14017     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
14018     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
14019         var span = getErrorSpanForNode(sourceFile, node);
14020         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
14021     }
14022     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
14023     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
14024         var sourceFile = getSourceFileOfNode(node);
14025         var span = getErrorSpanForNode(sourceFile, node);
14026         return {
14027             file: sourceFile,
14028             start: span.start,
14029             length: span.length,
14030             code: messageChain.code,
14031             category: messageChain.category,
14032             messageText: messageChain.next ? messageChain : messageChain.messageText,
14033             relatedInformation: relatedInformation
14034         };
14035     }
14036     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
14037     function createDiagnosticForFileFromMessageChain(sourceFile, messageChain, relatedInformation) {
14038         return {
14039             file: sourceFile,
14040             start: 0,
14041             length: 0,
14042             code: messageChain.code,
14043             category: messageChain.category,
14044             messageText: messageChain.next ? messageChain : messageChain.messageText,
14045             relatedInformation: relatedInformation
14046         };
14047     }
14048     ts.createDiagnosticForFileFromMessageChain = createDiagnosticForFileFromMessageChain;
14049     function createDiagnosticForRange(sourceFile, range, message) {
14050         return {
14051             file: sourceFile,
14052             start: range.pos,
14053             length: range.end - range.pos,
14054             code: message.code,
14055             category: message.category,
14056             messageText: message.message,
14057         };
14058     }
14059     ts.createDiagnosticForRange = createDiagnosticForRange;
14060     function getSpanOfTokenAtPosition(sourceFile, pos) {
14061         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
14062         scanner.scan();
14063         var start = scanner.getTokenPos();
14064         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
14065     }
14066     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
14067     function getErrorSpanForArrowFunction(sourceFile, node) {
14068         var pos = ts.skipTrivia(sourceFile.text, node.pos);
14069         if (node.body && node.body.kind === 230 /* Block */) {
14070             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
14071             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
14072             if (startLine < endLine) {
14073                 // The arrow function spans multiple lines,
14074                 // make the error span be the first line, inclusive.
14075                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
14076             }
14077         }
14078         return ts.createTextSpanFromBounds(pos, node.end);
14079     }
14080     function getErrorSpanForNode(sourceFile, node) {
14081         var errorNode = node;
14082         switch (node.kind) {
14083             case 297 /* SourceFile */:
14084                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
14085                 if (pos_1 === sourceFile.text.length) {
14086                     // file is empty - return span for the beginning of the file
14087                     return ts.createTextSpan(0, 0);
14088                 }
14089                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
14090             // This list is a work in progress. Add missing node kinds to improve their error
14091             // spans.
14092             case 249 /* VariableDeclaration */:
14093             case 198 /* BindingElement */:
14094             case 252 /* ClassDeclaration */:
14095             case 221 /* ClassExpression */:
14096             case 253 /* InterfaceDeclaration */:
14097             case 256 /* ModuleDeclaration */:
14098             case 255 /* EnumDeclaration */:
14099             case 291 /* EnumMember */:
14100             case 251 /* FunctionDeclaration */:
14101             case 208 /* FunctionExpression */:
14102             case 165 /* MethodDeclaration */:
14103             case 167 /* GetAccessor */:
14104             case 168 /* SetAccessor */:
14105             case 254 /* TypeAliasDeclaration */:
14106             case 163 /* PropertyDeclaration */:
14107             case 162 /* PropertySignature */:
14108                 errorNode = node.name;
14109                 break;
14110             case 209 /* ArrowFunction */:
14111                 return getErrorSpanForArrowFunction(sourceFile, node);
14112             case 284 /* CaseClause */:
14113             case 285 /* DefaultClause */:
14114                 var start = ts.skipTrivia(sourceFile.text, node.pos);
14115                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
14116                 return ts.createTextSpanFromBounds(start, end);
14117         }
14118         if (errorNode === undefined) {
14119             // If we don't have a better node, then just set the error on the first token of
14120             // construct.
14121             return getSpanOfTokenAtPosition(sourceFile, node.pos);
14122         }
14123         ts.Debug.assert(!ts.isJSDoc(errorNode));
14124         var isMissing = nodeIsMissing(errorNode);
14125         var pos = isMissing || ts.isJsxText(node)
14126             ? errorNode.pos
14127             : ts.skipTrivia(sourceFile.text, errorNode.pos);
14128         // These asserts should all be satisfied for a properly constructed `errorNode`.
14129         if (isMissing) {
14130             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14131             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14132         }
14133         else {
14134             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14135             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14136         }
14137         return ts.createTextSpanFromBounds(pos, errorNode.end);
14138     }
14139     ts.getErrorSpanForNode = getErrorSpanForNode;
14140     function isExternalOrCommonJsModule(file) {
14141         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
14142     }
14143     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
14144     function isJsonSourceFile(file) {
14145         return file.scriptKind === 6 /* JSON */;
14146     }
14147     ts.isJsonSourceFile = isJsonSourceFile;
14148     function isEnumConst(node) {
14149         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
14150     }
14151     ts.isEnumConst = isEnumConst;
14152     function isDeclarationReadonly(declaration) {
14153         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
14154     }
14155     ts.isDeclarationReadonly = isDeclarationReadonly;
14156     function isVarConst(node) {
14157         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
14158     }
14159     ts.isVarConst = isVarConst;
14160     function isLet(node) {
14161         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
14162     }
14163     ts.isLet = isLet;
14164     function isSuperCall(n) {
14165         return n.kind === 203 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */;
14166     }
14167     ts.isSuperCall = isSuperCall;
14168     function isImportCall(n) {
14169         return n.kind === 203 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */;
14170     }
14171     ts.isImportCall = isImportCall;
14172     function isImportMeta(n) {
14173         return ts.isMetaProperty(n)
14174             && n.keywordToken === 99 /* ImportKeyword */
14175             && n.name.escapedText === "meta";
14176     }
14177     ts.isImportMeta = isImportMeta;
14178     function isLiteralImportTypeNode(n) {
14179         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
14180     }
14181     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
14182     function isPrologueDirective(node) {
14183         return node.kind === 233 /* ExpressionStatement */
14184             && node.expression.kind === 10 /* StringLiteral */;
14185     }
14186     ts.isPrologueDirective = isPrologueDirective;
14187     function isCustomPrologue(node) {
14188         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
14189     }
14190     ts.isCustomPrologue = isCustomPrologue;
14191     function isHoistedFunction(node) {
14192         return isCustomPrologue(node)
14193             && ts.isFunctionDeclaration(node);
14194     }
14195     ts.isHoistedFunction = isHoistedFunction;
14196     function isHoistedVariable(node) {
14197         return ts.isIdentifier(node.name)
14198             && !node.initializer;
14199     }
14200     function isHoistedVariableStatement(node) {
14201         return isCustomPrologue(node)
14202             && ts.isVariableStatement(node)
14203             && ts.every(node.declarationList.declarations, isHoistedVariable);
14204     }
14205     ts.isHoistedVariableStatement = isHoistedVariableStatement;
14206     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
14207         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
14208     }
14209     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
14210     function getJSDocCommentRanges(node, text) {
14211         var commentRanges = (node.kind === 160 /* Parameter */ ||
14212             node.kind === 159 /* TypeParameter */ ||
14213             node.kind === 208 /* FunctionExpression */ ||
14214             node.kind === 209 /* ArrowFunction */ ||
14215             node.kind === 207 /* ParenthesizedExpression */) ?
14216             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
14217             ts.getLeadingCommentRanges(text, node.pos);
14218         // True if the comment starts with '/**' but not if it is '/**/'
14219         return ts.filter(commentRanges, function (comment) {
14220             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
14221                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
14222                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
14223         });
14224     }
14225     ts.getJSDocCommentRanges = getJSDocCommentRanges;
14226     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
14227     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
14228     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
14229     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
14230     function isPartOfTypeNode(node) {
14231         if (172 /* FirstTypeNode */ <= node.kind && node.kind <= 195 /* LastTypeNode */) {
14232             return true;
14233         }
14234         switch (node.kind) {
14235             case 128 /* AnyKeyword */:
14236             case 152 /* UnknownKeyword */:
14237             case 144 /* NumberKeyword */:
14238             case 155 /* BigIntKeyword */:
14239             case 147 /* StringKeyword */:
14240             case 131 /* BooleanKeyword */:
14241             case 148 /* SymbolKeyword */:
14242             case 145 /* ObjectKeyword */:
14243             case 150 /* UndefinedKeyword */:
14244             case 141 /* NeverKeyword */:
14245                 return true;
14246             case 113 /* VoidKeyword */:
14247                 return node.parent.kind !== 212 /* VoidExpression */;
14248             case 223 /* ExpressionWithTypeArguments */:
14249                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
14250             case 159 /* TypeParameter */:
14251                 return node.parent.kind === 190 /* MappedType */ || node.parent.kind === 185 /* InferType */;
14252             // Identifiers and qualified names may be type nodes, depending on their context. Climb
14253             // above them to find the lowest container
14254             case 78 /* Identifier */:
14255                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
14256                 if (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) {
14257                     node = node.parent;
14258                 }
14259                 else if (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node) {
14260                     node = node.parent;
14261                 }
14262                 // At this point, node is either a qualified name or an identifier
14263                 ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */ || node.kind === 201 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
14264             // falls through
14265             case 157 /* QualifiedName */:
14266             case 201 /* PropertyAccessExpression */:
14267             case 107 /* ThisKeyword */: {
14268                 var parent = node.parent;
14269                 if (parent.kind === 176 /* TypeQuery */) {
14270                     return false;
14271                 }
14272                 if (parent.kind === 195 /* ImportType */) {
14273                     return !parent.isTypeOf;
14274                 }
14275                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
14276                 //
14277                 //     let a: A.B.C;
14278                 //
14279                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
14280                 // Only C and A.B.C are type nodes.
14281                 if (172 /* FirstTypeNode */ <= parent.kind && parent.kind <= 195 /* LastTypeNode */) {
14282                     return true;
14283                 }
14284                 switch (parent.kind) {
14285                     case 223 /* ExpressionWithTypeArguments */:
14286                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14287                     case 159 /* TypeParameter */:
14288                         return node === parent.constraint;
14289                     case 330 /* JSDocTemplateTag */:
14290                         return node === parent.constraint;
14291                     case 163 /* PropertyDeclaration */:
14292                     case 162 /* PropertySignature */:
14293                     case 160 /* Parameter */:
14294                     case 249 /* VariableDeclaration */:
14295                         return node === parent.type;
14296                     case 251 /* FunctionDeclaration */:
14297                     case 208 /* FunctionExpression */:
14298                     case 209 /* ArrowFunction */:
14299                     case 166 /* Constructor */:
14300                     case 165 /* MethodDeclaration */:
14301                     case 164 /* MethodSignature */:
14302                     case 167 /* GetAccessor */:
14303                     case 168 /* SetAccessor */:
14304                         return node === parent.type;
14305                     case 169 /* CallSignature */:
14306                     case 170 /* ConstructSignature */:
14307                     case 171 /* IndexSignature */:
14308                         return node === parent.type;
14309                     case 206 /* TypeAssertionExpression */:
14310                         return node === parent.type;
14311                     case 203 /* CallExpression */:
14312                     case 204 /* NewExpression */:
14313                         return ts.contains(parent.typeArguments, node);
14314                     case 205 /* TaggedTemplateExpression */:
14315                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
14316                         return false;
14317                 }
14318             }
14319         }
14320         return false;
14321     }
14322     ts.isPartOfTypeNode = isPartOfTypeNode;
14323     function isChildOfNodeWithKind(node, kind) {
14324         while (node) {
14325             if (node.kind === kind) {
14326                 return true;
14327             }
14328             node = node.parent;
14329         }
14330         return false;
14331     }
14332     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
14333     // Warning: This has the same semantics as the forEach family of functions,
14334     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
14335     function forEachReturnStatement(body, visitor) {
14336         return traverse(body);
14337         function traverse(node) {
14338             switch (node.kind) {
14339                 case 242 /* ReturnStatement */:
14340                     return visitor(node);
14341                 case 258 /* CaseBlock */:
14342                 case 230 /* Block */:
14343                 case 234 /* IfStatement */:
14344                 case 235 /* DoStatement */:
14345                 case 236 /* WhileStatement */:
14346                 case 237 /* ForStatement */:
14347                 case 238 /* ForInStatement */:
14348                 case 239 /* ForOfStatement */:
14349                 case 243 /* WithStatement */:
14350                 case 244 /* SwitchStatement */:
14351                 case 284 /* CaseClause */:
14352                 case 285 /* DefaultClause */:
14353                 case 245 /* LabeledStatement */:
14354                 case 247 /* TryStatement */:
14355                 case 287 /* CatchClause */:
14356                     return ts.forEachChild(node, traverse);
14357             }
14358         }
14359     }
14360     ts.forEachReturnStatement = forEachReturnStatement;
14361     function forEachYieldExpression(body, visitor) {
14362         return traverse(body);
14363         function traverse(node) {
14364             switch (node.kind) {
14365                 case 219 /* YieldExpression */:
14366                     visitor(node);
14367                     var operand = node.expression;
14368                     if (operand) {
14369                         traverse(operand);
14370                     }
14371                     return;
14372                 case 255 /* EnumDeclaration */:
14373                 case 253 /* InterfaceDeclaration */:
14374                 case 256 /* ModuleDeclaration */:
14375                 case 254 /* TypeAliasDeclaration */:
14376                     // These are not allowed inside a generator now, but eventually they may be allowed
14377                     // as local types. Regardless, skip them to avoid the work.
14378                     return;
14379                 default:
14380                     if (ts.isFunctionLike(node)) {
14381                         if (node.name && node.name.kind === 158 /* ComputedPropertyName */) {
14382                             // Note that we will not include methods/accessors of a class because they would require
14383                             // first descending into the class. This is by design.
14384                             traverse(node.name.expression);
14385                             return;
14386                         }
14387                     }
14388                     else if (!isPartOfTypeNode(node)) {
14389                         // This is the general case, which should include mostly expressions and statements.
14390                         // Also includes NodeArrays.
14391                         ts.forEachChild(node, traverse);
14392                     }
14393             }
14394         }
14395     }
14396     ts.forEachYieldExpression = forEachYieldExpression;
14397     /**
14398      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
14399      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
14400      *
14401      * @param node The type node.
14402      */
14403     function getRestParameterElementType(node) {
14404         if (node && node.kind === 178 /* ArrayType */) {
14405             return node.elementType;
14406         }
14407         else if (node && node.kind === 173 /* TypeReference */) {
14408             return ts.singleOrUndefined(node.typeArguments);
14409         }
14410         else {
14411             return undefined;
14412         }
14413     }
14414     ts.getRestParameterElementType = getRestParameterElementType;
14415     function getMembersOfDeclaration(node) {
14416         switch (node.kind) {
14417             case 253 /* InterfaceDeclaration */:
14418             case 252 /* ClassDeclaration */:
14419             case 221 /* ClassExpression */:
14420             case 177 /* TypeLiteral */:
14421                 return node.members;
14422             case 200 /* ObjectLiteralExpression */:
14423                 return node.properties;
14424         }
14425     }
14426     ts.getMembersOfDeclaration = getMembersOfDeclaration;
14427     function isVariableLike(node) {
14428         if (node) {
14429             switch (node.kind) {
14430                 case 198 /* BindingElement */:
14431                 case 291 /* EnumMember */:
14432                 case 160 /* Parameter */:
14433                 case 288 /* PropertyAssignment */:
14434                 case 163 /* PropertyDeclaration */:
14435                 case 162 /* PropertySignature */:
14436                 case 289 /* ShorthandPropertyAssignment */:
14437                 case 249 /* VariableDeclaration */:
14438                     return true;
14439             }
14440         }
14441         return false;
14442     }
14443     ts.isVariableLike = isVariableLike;
14444     function isVariableLikeOrAccessor(node) {
14445         return isVariableLike(node) || ts.isAccessor(node);
14446     }
14447     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
14448     function isVariableDeclarationInVariableStatement(node) {
14449         return node.parent.kind === 250 /* VariableDeclarationList */
14450             && node.parent.parent.kind === 232 /* VariableStatement */;
14451     }
14452     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
14453     function isValidESSymbolDeclaration(node) {
14454         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
14455             ts.isPropertyDeclaration(node) ? hasEffectiveReadonlyModifier(node) && hasStaticModifier(node) :
14456                 ts.isPropertySignature(node) && hasEffectiveReadonlyModifier(node);
14457     }
14458     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
14459     function introducesArgumentsExoticObject(node) {
14460         switch (node.kind) {
14461             case 165 /* MethodDeclaration */:
14462             case 164 /* MethodSignature */:
14463             case 166 /* Constructor */:
14464             case 167 /* GetAccessor */:
14465             case 168 /* SetAccessor */:
14466             case 251 /* FunctionDeclaration */:
14467             case 208 /* FunctionExpression */:
14468                 return true;
14469         }
14470         return false;
14471     }
14472     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
14473     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
14474         while (true) {
14475             if (beforeUnwrapLabelCallback) {
14476                 beforeUnwrapLabelCallback(node);
14477             }
14478             if (node.statement.kind !== 245 /* LabeledStatement */) {
14479                 return node.statement;
14480             }
14481             node = node.statement;
14482         }
14483     }
14484     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
14485     function isFunctionBlock(node) {
14486         return node && node.kind === 230 /* Block */ && ts.isFunctionLike(node.parent);
14487     }
14488     ts.isFunctionBlock = isFunctionBlock;
14489     function isObjectLiteralMethod(node) {
14490         return node && node.kind === 165 /* MethodDeclaration */ && node.parent.kind === 200 /* ObjectLiteralExpression */;
14491     }
14492     ts.isObjectLiteralMethod = isObjectLiteralMethod;
14493     function isObjectLiteralOrClassExpressionMethod(node) {
14494         return node.kind === 165 /* MethodDeclaration */ &&
14495             (node.parent.kind === 200 /* ObjectLiteralExpression */ ||
14496                 node.parent.kind === 221 /* ClassExpression */);
14497     }
14498     ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
14499     function isIdentifierTypePredicate(predicate) {
14500         return predicate && predicate.kind === 1 /* Identifier */;
14501     }
14502     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
14503     function isThisTypePredicate(predicate) {
14504         return predicate && predicate.kind === 0 /* This */;
14505     }
14506     ts.isThisTypePredicate = isThisTypePredicate;
14507     function getPropertyAssignment(objectLiteral, key, key2) {
14508         return objectLiteral.properties.filter(function (property) {
14509             if (property.kind === 288 /* PropertyAssignment */) {
14510                 var propName = getTextOfPropertyName(property.name);
14511                 return key === propName || (!!key2 && key2 === propName);
14512             }
14513             return false;
14514         });
14515     }
14516     ts.getPropertyAssignment = getPropertyAssignment;
14517     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
14518         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
14519             var expression = tsConfigSourceFile.statements[0].expression;
14520             return ts.tryCast(expression, ts.isObjectLiteralExpression);
14521         }
14522     }
14523     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
14524     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
14525         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
14526             return ts.isArrayLiteralExpression(property.initializer) ?
14527                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14528                 undefined;
14529         });
14530     }
14531     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
14532     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
14533         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
14534         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
14535     }
14536     ts.getTsConfigPropArray = getTsConfigPropArray;
14537     function getContainingFunction(node) {
14538         return ts.findAncestor(node.parent, ts.isFunctionLike);
14539     }
14540     ts.getContainingFunction = getContainingFunction;
14541     function getContainingFunctionDeclaration(node) {
14542         return ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration);
14543     }
14544     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
14545     function getContainingClass(node) {
14546         return ts.findAncestor(node.parent, ts.isClassLike);
14547     }
14548     ts.getContainingClass = getContainingClass;
14549     function getThisContainer(node, includeArrowFunctions) {
14550         ts.Debug.assert(node.kind !== 297 /* SourceFile */);
14551         while (true) {
14552             node = node.parent;
14553             if (!node) {
14554                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
14555             }
14556             switch (node.kind) {
14557                 case 158 /* ComputedPropertyName */:
14558                     // If the grandparent node is an object literal (as opposed to a class),
14559                     // then the computed property is not a 'this' container.
14560                     // A computed property name in a class needs to be a this container
14561                     // so that we can error on it.
14562                     if (ts.isClassLike(node.parent.parent)) {
14563                         return node;
14564                     }
14565                     // If this is a computed property, then the parent should not
14566                     // make it a this container. The parent might be a property
14567                     // in an object literal, like a method or accessor. But in order for
14568                     // such a parent to be a this container, the reference must be in
14569                     // the *body* of the container.
14570                     node = node.parent;
14571                     break;
14572                 case 161 /* Decorator */:
14573                     // Decorators are always applied outside of the body of a class or method.
14574                     if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14575                         // If the decorator's parent is a Parameter, we resolve the this container from
14576                         // the grandparent class declaration.
14577                         node = node.parent.parent;
14578                     }
14579                     else if (ts.isClassElement(node.parent)) {
14580                         // If the decorator's parent is a class element, we resolve the 'this' container
14581                         // from the parent class declaration.
14582                         node = node.parent;
14583                     }
14584                     break;
14585                 case 209 /* ArrowFunction */:
14586                     if (!includeArrowFunctions) {
14587                         continue;
14588                     }
14589                 // falls through
14590                 case 251 /* FunctionDeclaration */:
14591                 case 208 /* FunctionExpression */:
14592                 case 256 /* ModuleDeclaration */:
14593                 case 163 /* PropertyDeclaration */:
14594                 case 162 /* PropertySignature */:
14595                 case 165 /* MethodDeclaration */:
14596                 case 164 /* MethodSignature */:
14597                 case 166 /* Constructor */:
14598                 case 167 /* GetAccessor */:
14599                 case 168 /* SetAccessor */:
14600                 case 169 /* CallSignature */:
14601                 case 170 /* ConstructSignature */:
14602                 case 171 /* IndexSignature */:
14603                 case 255 /* EnumDeclaration */:
14604                 case 297 /* SourceFile */:
14605                     return node;
14606             }
14607         }
14608     }
14609     ts.getThisContainer = getThisContainer;
14610     function isInTopLevelContext(node) {
14611         // The name of a class or function declaration is a BindingIdentifier in its surrounding scope.
14612         if (ts.isIdentifier(node) && (ts.isClassDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) && node.parent.name === node) {
14613             node = node.parent;
14614         }
14615         var container = getThisContainer(node, /*includeArrowFunctions*/ true);
14616         return ts.isSourceFile(container);
14617     }
14618     ts.isInTopLevelContext = isInTopLevelContext;
14619     function getNewTargetContainer(node) {
14620         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
14621         if (container) {
14622             switch (container.kind) {
14623                 case 166 /* Constructor */:
14624                 case 251 /* FunctionDeclaration */:
14625                 case 208 /* FunctionExpression */:
14626                     return container;
14627             }
14628         }
14629         return undefined;
14630     }
14631     ts.getNewTargetContainer = getNewTargetContainer;
14632     /**
14633      * Given an super call/property node, returns the closest node where
14634      * - a super call/property access is legal in the node and not legal in the parent node the node.
14635      *   i.e. super call is legal in constructor but not legal in the class body.
14636      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
14637      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
14638      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
14639      */
14640     function getSuperContainer(node, stopOnFunctions) {
14641         while (true) {
14642             node = node.parent;
14643             if (!node) {
14644                 return node;
14645             }
14646             switch (node.kind) {
14647                 case 158 /* ComputedPropertyName */:
14648                     node = node.parent;
14649                     break;
14650                 case 251 /* FunctionDeclaration */:
14651                 case 208 /* FunctionExpression */:
14652                 case 209 /* ArrowFunction */:
14653                     if (!stopOnFunctions) {
14654                         continue;
14655                     }
14656                 // falls through
14657                 case 163 /* PropertyDeclaration */:
14658                 case 162 /* PropertySignature */:
14659                 case 165 /* MethodDeclaration */:
14660                 case 164 /* MethodSignature */:
14661                 case 166 /* Constructor */:
14662                 case 167 /* GetAccessor */:
14663                 case 168 /* SetAccessor */:
14664                     return node;
14665                 case 161 /* Decorator */:
14666                     // Decorators are always applied outside of the body of a class or method.
14667                     if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14668                         // If the decorator's parent is a Parameter, we resolve the this container from
14669                         // the grandparent class declaration.
14670                         node = node.parent.parent;
14671                     }
14672                     else if (ts.isClassElement(node.parent)) {
14673                         // If the decorator's parent is a class element, we resolve the 'this' container
14674                         // from the parent class declaration.
14675                         node = node.parent;
14676                     }
14677                     break;
14678             }
14679         }
14680     }
14681     ts.getSuperContainer = getSuperContainer;
14682     function getImmediatelyInvokedFunctionExpression(func) {
14683         if (func.kind === 208 /* FunctionExpression */ || func.kind === 209 /* ArrowFunction */) {
14684             var prev = func;
14685             var parent = func.parent;
14686             while (parent.kind === 207 /* ParenthesizedExpression */) {
14687                 prev = parent;
14688                 parent = parent.parent;
14689             }
14690             if (parent.kind === 203 /* CallExpression */ && parent.expression === prev) {
14691                 return parent;
14692             }
14693         }
14694     }
14695     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14696     function isSuperOrSuperProperty(node) {
14697         return node.kind === 105 /* SuperKeyword */
14698             || isSuperProperty(node);
14699     }
14700     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14701     /**
14702      * Determines whether a node is a property or element access expression for `super`.
14703      */
14704     function isSuperProperty(node) {
14705         var kind = node.kind;
14706         return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */)
14707             && node.expression.kind === 105 /* SuperKeyword */;
14708     }
14709     ts.isSuperProperty = isSuperProperty;
14710     /**
14711      * Determines whether a node is a property or element access expression for `this`.
14712      */
14713     function isThisProperty(node) {
14714         var kind = node.kind;
14715         return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */)
14716             && node.expression.kind === 107 /* ThisKeyword */;
14717     }
14718     ts.isThisProperty = isThisProperty;
14719     function isThisInitializedDeclaration(node) {
14720         var _a;
14721         return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 107 /* ThisKeyword */;
14722     }
14723     ts.isThisInitializedDeclaration = isThisInitializedDeclaration;
14724     function getEntityNameFromTypeNode(node) {
14725         switch (node.kind) {
14726             case 173 /* TypeReference */:
14727                 return node.typeName;
14728             case 223 /* ExpressionWithTypeArguments */:
14729                 return isEntityNameExpression(node.expression)
14730                     ? node.expression
14731                     : undefined;
14732             // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s.
14733             case 78 /* Identifier */:
14734             case 157 /* QualifiedName */:
14735                 return node;
14736         }
14737         return undefined;
14738     }
14739     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14740     function getInvokedExpression(node) {
14741         switch (node.kind) {
14742             case 205 /* TaggedTemplateExpression */:
14743                 return node.tag;
14744             case 275 /* JsxOpeningElement */:
14745             case 274 /* JsxSelfClosingElement */:
14746                 return node.tagName;
14747             default:
14748                 return node.expression;
14749         }
14750     }
14751     ts.getInvokedExpression = getInvokedExpression;
14752     function nodeCanBeDecorated(node, parent, grandparent) {
14753         // private names cannot be used with decorators yet
14754         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14755             return false;
14756         }
14757         switch (node.kind) {
14758             case 252 /* ClassDeclaration */:
14759                 // classes are valid targets
14760                 return true;
14761             case 163 /* PropertyDeclaration */:
14762                 // property declarations are valid if their parent is a class declaration.
14763                 return parent.kind === 252 /* ClassDeclaration */;
14764             case 167 /* GetAccessor */:
14765             case 168 /* SetAccessor */:
14766             case 165 /* MethodDeclaration */:
14767                 // if this method has a body and its parent is a class declaration, this is a valid target.
14768                 return node.body !== undefined
14769                     && parent.kind === 252 /* ClassDeclaration */;
14770             case 160 /* Parameter */:
14771                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14772                 return parent.body !== undefined
14773                     && (parent.kind === 166 /* Constructor */
14774                         || parent.kind === 165 /* MethodDeclaration */
14775                         || parent.kind === 168 /* SetAccessor */)
14776                     && grandparent.kind === 252 /* ClassDeclaration */;
14777         }
14778         return false;
14779     }
14780     ts.nodeCanBeDecorated = nodeCanBeDecorated;
14781     function nodeIsDecorated(node, parent, grandparent) {
14782         return node.decorators !== undefined
14783             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
14784     }
14785     ts.nodeIsDecorated = nodeIsDecorated;
14786     function nodeOrChildIsDecorated(node, parent, grandparent) {
14787         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
14788     }
14789     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
14790     function childIsDecorated(node, parent) {
14791         switch (node.kind) {
14792             case 252 /* ClassDeclaration */:
14793                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
14794             case 165 /* MethodDeclaration */:
14795             case 168 /* SetAccessor */:
14796                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
14797             default:
14798                 return false;
14799         }
14800     }
14801     ts.childIsDecorated = childIsDecorated;
14802     function isJSXTagName(node) {
14803         var parent = node.parent;
14804         if (parent.kind === 275 /* JsxOpeningElement */ ||
14805             parent.kind === 274 /* JsxSelfClosingElement */ ||
14806             parent.kind === 276 /* JsxClosingElement */) {
14807             return parent.tagName === node;
14808         }
14809         return false;
14810     }
14811     ts.isJSXTagName = isJSXTagName;
14812     function isExpressionNode(node) {
14813         switch (node.kind) {
14814             case 105 /* SuperKeyword */:
14815             case 103 /* NullKeyword */:
14816             case 109 /* TrueKeyword */:
14817             case 94 /* FalseKeyword */:
14818             case 13 /* RegularExpressionLiteral */:
14819             case 199 /* ArrayLiteralExpression */:
14820             case 200 /* ObjectLiteralExpression */:
14821             case 201 /* PropertyAccessExpression */:
14822             case 202 /* ElementAccessExpression */:
14823             case 203 /* CallExpression */:
14824             case 204 /* NewExpression */:
14825             case 205 /* TaggedTemplateExpression */:
14826             case 224 /* AsExpression */:
14827             case 206 /* TypeAssertionExpression */:
14828             case 225 /* NonNullExpression */:
14829             case 207 /* ParenthesizedExpression */:
14830             case 208 /* FunctionExpression */:
14831             case 221 /* ClassExpression */:
14832             case 209 /* ArrowFunction */:
14833             case 212 /* VoidExpression */:
14834             case 210 /* DeleteExpression */:
14835             case 211 /* TypeOfExpression */:
14836             case 214 /* PrefixUnaryExpression */:
14837             case 215 /* PostfixUnaryExpression */:
14838             case 216 /* BinaryExpression */:
14839             case 217 /* ConditionalExpression */:
14840             case 220 /* SpreadElement */:
14841             case 218 /* TemplateExpression */:
14842             case 222 /* OmittedExpression */:
14843             case 273 /* JsxElement */:
14844             case 274 /* JsxSelfClosingElement */:
14845             case 277 /* JsxFragment */:
14846             case 219 /* YieldExpression */:
14847             case 213 /* AwaitExpression */:
14848             case 226 /* MetaProperty */:
14849                 return true;
14850             case 157 /* QualifiedName */:
14851                 while (node.parent.kind === 157 /* QualifiedName */) {
14852                     node = node.parent;
14853                 }
14854                 return node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node);
14855             case 78 /* Identifier */:
14856                 if (node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node)) {
14857                     return true;
14858                 }
14859             // falls through
14860             case 8 /* NumericLiteral */:
14861             case 9 /* BigIntLiteral */:
14862             case 10 /* StringLiteral */:
14863             case 14 /* NoSubstitutionTemplateLiteral */:
14864             case 107 /* ThisKeyword */:
14865                 return isInExpressionContext(node);
14866             default:
14867                 return false;
14868         }
14869     }
14870     ts.isExpressionNode = isExpressionNode;
14871     function isInExpressionContext(node) {
14872         var parent = node.parent;
14873         switch (parent.kind) {
14874             case 249 /* VariableDeclaration */:
14875             case 160 /* Parameter */:
14876             case 163 /* PropertyDeclaration */:
14877             case 162 /* PropertySignature */:
14878             case 291 /* EnumMember */:
14879             case 288 /* PropertyAssignment */:
14880             case 198 /* BindingElement */:
14881                 return parent.initializer === node;
14882             case 233 /* ExpressionStatement */:
14883             case 234 /* IfStatement */:
14884             case 235 /* DoStatement */:
14885             case 236 /* WhileStatement */:
14886             case 242 /* ReturnStatement */:
14887             case 243 /* WithStatement */:
14888             case 244 /* SwitchStatement */:
14889             case 284 /* CaseClause */:
14890             case 246 /* ThrowStatement */:
14891                 return parent.expression === node;
14892             case 237 /* ForStatement */:
14893                 var forStatement = parent;
14894                 return (forStatement.initializer === node && forStatement.initializer.kind !== 250 /* VariableDeclarationList */) ||
14895                     forStatement.condition === node ||
14896                     forStatement.incrementor === node;
14897             case 238 /* ForInStatement */:
14898             case 239 /* ForOfStatement */:
14899                 var forInStatement = parent;
14900                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 250 /* VariableDeclarationList */) ||
14901                     forInStatement.expression === node;
14902             case 206 /* TypeAssertionExpression */:
14903             case 224 /* AsExpression */:
14904                 return node === parent.expression;
14905             case 228 /* TemplateSpan */:
14906                 return node === parent.expression;
14907             case 158 /* ComputedPropertyName */:
14908                 return node === parent.expression;
14909             case 161 /* Decorator */:
14910             case 283 /* JsxExpression */:
14911             case 282 /* JsxSpreadAttribute */:
14912             case 290 /* SpreadAssignment */:
14913                 return true;
14914             case 223 /* ExpressionWithTypeArguments */:
14915                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14916             case 289 /* ShorthandPropertyAssignment */:
14917                 return parent.objectAssignmentInitializer === node;
14918             default:
14919                 return isExpressionNode(parent);
14920         }
14921     }
14922     ts.isInExpressionContext = isInExpressionContext;
14923     function isPartOfTypeQuery(node) {
14924         while (node.kind === 157 /* QualifiedName */ || node.kind === 78 /* Identifier */) {
14925             node = node.parent;
14926         }
14927         return node.kind === 176 /* TypeQuery */;
14928     }
14929     ts.isPartOfTypeQuery = isPartOfTypeQuery;
14930     function isExternalModuleImportEqualsDeclaration(node) {
14931         return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 272 /* ExternalModuleReference */;
14932     }
14933     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
14934     function getExternalModuleImportEqualsDeclarationExpression(node) {
14935         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
14936         return node.moduleReference.expression;
14937     }
14938     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
14939     function getExternalModuleRequireArgument(node) {
14940         return isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)
14941             && getLeftmostAccessExpression(node.initializer).arguments[0];
14942     }
14943     ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument;
14944     function isInternalModuleImportEqualsDeclaration(node) {
14945         return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 272 /* ExternalModuleReference */;
14946     }
14947     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
14948     function isSourceFileJS(file) {
14949         return isInJSFile(file);
14950     }
14951     ts.isSourceFileJS = isSourceFileJS;
14952     function isSourceFileNotJS(file) {
14953         return !isInJSFile(file);
14954     }
14955     ts.isSourceFileNotJS = isSourceFileNotJS;
14956     function isInJSFile(node) {
14957         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
14958     }
14959     ts.isInJSFile = isInJSFile;
14960     function isInJsonFile(node) {
14961         return !!node && !!(node.flags & 33554432 /* JsonFile */);
14962     }
14963     ts.isInJsonFile = isInJsonFile;
14964     function isSourceFileNotJson(file) {
14965         return !isJsonSourceFile(file);
14966     }
14967     ts.isSourceFileNotJson = isSourceFileNotJson;
14968     function isInJSDoc(node) {
14969         return !!node && !!(node.flags & 4194304 /* JSDoc */);
14970     }
14971     ts.isInJSDoc = isInJSDoc;
14972     function isJSDocIndexSignature(node) {
14973         return ts.isTypeReferenceNode(node) &&
14974             ts.isIdentifier(node.typeName) &&
14975             node.typeName.escapedText === "Object" &&
14976             node.typeArguments && node.typeArguments.length === 2 &&
14977             (node.typeArguments[0].kind === 147 /* StringKeyword */ || node.typeArguments[0].kind === 144 /* NumberKeyword */);
14978     }
14979     ts.isJSDocIndexSignature = isJSDocIndexSignature;
14980     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
14981         if (callExpression.kind !== 203 /* CallExpression */) {
14982             return false;
14983         }
14984         var _a = callExpression, expression = _a.expression, args = _a.arguments;
14985         if (expression.kind !== 78 /* Identifier */ || expression.escapedText !== "require") {
14986             return false;
14987         }
14988         if (args.length !== 1) {
14989             return false;
14990         }
14991         var arg = args[0];
14992         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
14993     }
14994     ts.isRequireCall = isRequireCall;
14995     function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
14996         if (node.kind === 198 /* BindingElement */) {
14997             node = node.parent.parent;
14998         }
14999         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument);
15000     }
15001     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
15002     function isRequireVariableStatement(node, requireStringLiteralLikeArgument) {
15003         if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
15004         return ts.isVariableStatement(node)
15005             && node.declarationList.declarations.length > 0
15006             && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
15007     }
15008     ts.isRequireVariableStatement = isRequireVariableStatement;
15009     function isSingleOrDoubleQuote(charCode) {
15010         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
15011     }
15012     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
15013     function isStringDoubleQuoted(str, sourceFile) {
15014         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
15015     }
15016     ts.isStringDoubleQuoted = isStringDoubleQuoted;
15017     function isAssignmentDeclaration(decl) {
15018         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
15019     }
15020     ts.isAssignmentDeclaration = isAssignmentDeclaration;
15021     /** Get the initializer, taking into account defaulted Javascript initializers */
15022     function getEffectiveInitializer(node) {
15023         if (isInJSFile(node) && node.initializer &&
15024             ts.isBinaryExpression(node.initializer) &&
15025             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
15026             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
15027             return node.initializer.right;
15028         }
15029         return node.initializer;
15030     }
15031     ts.getEffectiveInitializer = getEffectiveInitializer;
15032     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
15033     function getDeclaredExpandoInitializer(node) {
15034         var init = getEffectiveInitializer(node);
15035         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
15036     }
15037     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
15038     function hasExpandoValueProperty(node, isPrototypeAssignment) {
15039         return ts.forEach(node.properties, function (p) {
15040             return ts.isPropertyAssignment(p) &&
15041                 ts.isIdentifier(p.name) &&
15042                 p.name.escapedText === "value" &&
15043                 p.initializer &&
15044                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
15045         });
15046     }
15047     /**
15048      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
15049      * We treat the right hand side of assignments with container-like initializers as declarations.
15050      */
15051     function getAssignedExpandoInitializer(node) {
15052         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
15053             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
15054             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
15055                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
15056         }
15057         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
15058             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
15059             if (result) {
15060                 return result;
15061             }
15062         }
15063     }
15064     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
15065     /**
15066      * Recognized expando initializers are:
15067      * 1. (function() {})() -- IIFEs
15068      * 2. function() { } -- Function expressions
15069      * 3. class { } -- Class expressions
15070      * 4. {} -- Empty object literals
15071      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
15072      *
15073      * This function returns the provided initializer, or undefined if it is not valid.
15074      */
15075     function getExpandoInitializer(initializer, isPrototypeAssignment) {
15076         if (ts.isCallExpression(initializer)) {
15077             var e = skipParentheses(initializer.expression);
15078             return e.kind === 208 /* FunctionExpression */ || e.kind === 209 /* ArrowFunction */ ? initializer : undefined;
15079         }
15080         if (initializer.kind === 208 /* FunctionExpression */ ||
15081             initializer.kind === 221 /* ClassExpression */ ||
15082             initializer.kind === 209 /* ArrowFunction */) {
15083             return initializer;
15084         }
15085         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
15086             return initializer;
15087         }
15088     }
15089     ts.getExpandoInitializer = getExpandoInitializer;
15090     /**
15091      * A defaulted expando initializer matches the pattern
15092      * `Lhs = Lhs || ExpandoInitializer`
15093      * or `var Lhs = Lhs || ExpandoInitializer`
15094      *
15095      * The second Lhs is required to be the same as the first except that it may be prefixed with
15096      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
15097      */
15098     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
15099         var e = ts.isBinaryExpression(initializer)
15100             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
15101             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
15102         if (e && isSameEntityName(name, initializer.left)) {
15103             return e;
15104         }
15105     }
15106     function isDefaultedExpandoInitializer(node) {
15107         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
15108             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
15109                 undefined;
15110         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
15111     }
15112     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
15113     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
15114     function getNameOfExpando(node) {
15115         if (ts.isBinaryExpression(node.parent)) {
15116             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
15117             if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
15118                 return parent.left;
15119             }
15120         }
15121         else if (ts.isVariableDeclaration(node.parent)) {
15122             return node.parent.name;
15123         }
15124     }
15125     ts.getNameOfExpando = getNameOfExpando;
15126     /**
15127      * Is the 'declared' name the same as the one in the initializer?
15128      * @return true for identical entity names, as well as ones where the initializer is prefixed with
15129      * 'window', 'self' or 'global'. For example:
15130      *
15131      * var my = my || {}
15132      * var min = window.min || {}
15133      * my.app = self.my.app || class { }
15134      */
15135     function isSameEntityName(name, initializer) {
15136         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
15137             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(initializer);
15138         }
15139         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
15140             (initializer.expression.kind === 107 /* ThisKeyword */ ||
15141                 ts.isIdentifier(initializer.expression) &&
15142                     (initializer.expression.escapedText === "window" ||
15143                         initializer.expression.escapedText === "self" ||
15144                         initializer.expression.escapedText === "global"))) {
15145             var nameOrArgument = getNameOrArgument(initializer);
15146             if (ts.isPrivateIdentifier(nameOrArgument)) {
15147                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
15148             }
15149             return isSameEntityName(name, nameOrArgument);
15150         }
15151         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
15152             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
15153                 && isSameEntityName(name.expression, initializer.expression);
15154         }
15155         return false;
15156     }
15157     ts.isSameEntityName = isSameEntityName;
15158     function getRightMostAssignedExpression(node) {
15159         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
15160             node = node.right;
15161         }
15162         return node;
15163     }
15164     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
15165     function isExportsIdentifier(node) {
15166         return ts.isIdentifier(node) && node.escapedText === "exports";
15167     }
15168     ts.isExportsIdentifier = isExportsIdentifier;
15169     function isModuleIdentifier(node) {
15170         return ts.isIdentifier(node) && node.escapedText === "module";
15171     }
15172     ts.isModuleIdentifier = isModuleIdentifier;
15173     function isModuleExportsAccessExpression(node) {
15174         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
15175             && isModuleIdentifier(node.expression)
15176             && getElementOrPropertyAccessName(node) === "exports";
15177     }
15178     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
15179     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
15180     /// assignments we treat as special in the binder
15181     function getAssignmentDeclarationKind(expr) {
15182         var special = getAssignmentDeclarationKindWorker(expr);
15183         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
15184     }
15185     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
15186     function isBindableObjectDefinePropertyCall(expr) {
15187         return ts.length(expr.arguments) === 3 &&
15188             ts.isPropertyAccessExpression(expr.expression) &&
15189             ts.isIdentifier(expr.expression.expression) &&
15190             ts.idText(expr.expression.expression) === "Object" &&
15191             ts.idText(expr.expression.name) === "defineProperty" &&
15192             isStringOrNumericLiteralLike(expr.arguments[1]) &&
15193             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
15194     }
15195     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
15196     /** x.y OR x[0] */
15197     function isLiteralLikeAccess(node) {
15198         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
15199     }
15200     ts.isLiteralLikeAccess = isLiteralLikeAccess;
15201     /** x[0] OR x['a'] OR x[Symbol.y] */
15202     function isLiteralLikeElementAccess(node) {
15203         return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
15204             isWellKnownSymbolSyntactically(node.argumentExpression));
15205     }
15206     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
15207     /** Any series of property and element accesses. */
15208     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
15209         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 107 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
15210             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
15211     }
15212     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
15213     /** Any series of property and element accesses, ending in a literal element access */
15214     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
15215         return isLiteralLikeElementAccess(node)
15216             && ((!excludeThisKeyword && node.expression.kind === 107 /* ThisKeyword */) ||
15217                 isEntityNameExpression(node.expression) ||
15218                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
15219     }
15220     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
15221     function isBindableStaticNameExpression(node, excludeThisKeyword) {
15222         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
15223     }
15224     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
15225     function getNameOrArgument(expr) {
15226         if (ts.isPropertyAccessExpression(expr)) {
15227             return expr.name;
15228         }
15229         return expr.argumentExpression;
15230     }
15231     ts.getNameOrArgument = getNameOrArgument;
15232     function getAssignmentDeclarationKindWorker(expr) {
15233         if (ts.isCallExpression(expr)) {
15234             if (!isBindableObjectDefinePropertyCall(expr)) {
15235                 return 0 /* None */;
15236             }
15237             var entityName = expr.arguments[0];
15238             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
15239                 return 8 /* ObjectDefinePropertyExports */;
15240             }
15241             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
15242                 return 9 /* ObjectDefinePrototypeProperty */;
15243             }
15244             return 7 /* ObjectDefinePropertyValue */;
15245         }
15246         if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) {
15247             return 0 /* None */;
15248         }
15249         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
15250             // F.prototype = { ... }
15251             return 6 /* Prototype */;
15252         }
15253         return getAssignmentDeclarationPropertyAccessKind(expr.left);
15254     }
15255     function isVoidZero(node) {
15256         return ts.isVoidExpression(node) && ts.isNumericLiteral(node.expression) && node.expression.text === "0";
15257     }
15258     /**
15259      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
15260      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
15261      */
15262     /* @internal */
15263     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
15264         if (ts.isPropertyAccessExpression(node)) {
15265             return node.name;
15266         }
15267         var arg = skipParentheses(node.argumentExpression);
15268         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
15269             return arg;
15270         }
15271         return node;
15272     }
15273     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
15274     function getElementOrPropertyAccessName(node) {
15275         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
15276         if (name) {
15277             if (ts.isIdentifier(name)) {
15278                 return name.escapedText;
15279             }
15280             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
15281                 return ts.escapeLeadingUnderscores(name.text);
15282             }
15283         }
15284         if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
15285             return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
15286         }
15287         return undefined;
15288     }
15289     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
15290     function getAssignmentDeclarationPropertyAccessKind(lhs) {
15291         if (lhs.expression.kind === 107 /* ThisKeyword */) {
15292             return 4 /* ThisProperty */;
15293         }
15294         else if (isModuleExportsAccessExpression(lhs)) {
15295             // module.exports = expr
15296             return 2 /* ModuleExports */;
15297         }
15298         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
15299             if (isPrototypeAccess(lhs.expression)) {
15300                 // F.G....prototype.x = expr
15301                 return 3 /* PrototypeProperty */;
15302             }
15303             var nextToLast = lhs;
15304             while (!ts.isIdentifier(nextToLast.expression)) {
15305                 nextToLast = nextToLast.expression;
15306             }
15307             var id = nextToLast.expression;
15308             if ((id.escapedText === "exports" ||
15309                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
15310                 // ExportsProperty does not support binding with computed names
15311                 isBindableStaticAccessExpression(lhs)) {
15312                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
15313                 return 1 /* ExportsProperty */;
15314             }
15315             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
15316                 // F.G...x = expr
15317                 return 5 /* Property */;
15318             }
15319         }
15320         return 0 /* None */;
15321     }
15322     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
15323     function getInitializerOfBinaryExpression(expr) {
15324         while (ts.isBinaryExpression(expr.right)) {
15325             expr = expr.right;
15326         }
15327         return expr.right;
15328     }
15329     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
15330     function isPrototypePropertyAssignment(node) {
15331         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
15332     }
15333     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
15334     function isSpecialPropertyDeclaration(expr) {
15335         return isInJSFile(expr) &&
15336             expr.parent && expr.parent.kind === 233 /* ExpressionStatement */ &&
15337             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
15338             !!ts.getJSDocTypeTag(expr.parent);
15339     }
15340     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
15341     function setValueDeclaration(symbol, node) {
15342         var valueDeclaration = symbol.valueDeclaration;
15343         if (!valueDeclaration ||
15344             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
15345                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
15346             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
15347             // other kinds of value declarations take precedence over modules and assignment declarations
15348             symbol.valueDeclaration = node;
15349         }
15350     }
15351     ts.setValueDeclaration = setValueDeclaration;
15352     function isFunctionSymbol(symbol) {
15353         if (!symbol || !symbol.valueDeclaration) {
15354             return false;
15355         }
15356         var decl = symbol.valueDeclaration;
15357         return decl.kind === 251 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
15358     }
15359     ts.isFunctionSymbol = isFunctionSymbol;
15360     function importFromModuleSpecifier(node) {
15361         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
15362     }
15363     ts.importFromModuleSpecifier = importFromModuleSpecifier;
15364     function tryGetImportFromModuleSpecifier(node) {
15365         switch (node.parent.kind) {
15366             case 261 /* ImportDeclaration */:
15367             case 267 /* ExportDeclaration */:
15368                 return node.parent;
15369             case 272 /* ExternalModuleReference */:
15370                 return node.parent.parent;
15371             case 203 /* CallExpression */:
15372                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
15373             case 191 /* LiteralType */:
15374                 ts.Debug.assert(ts.isStringLiteral(node));
15375                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
15376             default:
15377                 return undefined;
15378         }
15379     }
15380     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
15381     function getExternalModuleName(node) {
15382         switch (node.kind) {
15383             case 261 /* ImportDeclaration */:
15384             case 267 /* ExportDeclaration */:
15385                 return node.moduleSpecifier;
15386             case 260 /* ImportEqualsDeclaration */:
15387                 return node.moduleReference.kind === 272 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
15388             case 195 /* ImportType */:
15389                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
15390             default:
15391                 return ts.Debug.assertNever(node);
15392         }
15393     }
15394     ts.getExternalModuleName = getExternalModuleName;
15395     function getNamespaceDeclarationNode(node) {
15396         switch (node.kind) {
15397             case 261 /* ImportDeclaration */:
15398                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
15399             case 260 /* ImportEqualsDeclaration */:
15400                 return node;
15401             case 267 /* ExportDeclaration */:
15402                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
15403             default:
15404                 return ts.Debug.assertNever(node);
15405         }
15406     }
15407     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
15408     function isDefaultImport(node) {
15409         return node.kind === 261 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
15410     }
15411     ts.isDefaultImport = isDefaultImport;
15412     function forEachImportClauseDeclaration(node, action) {
15413         if (node.name) {
15414             var result = action(node);
15415             if (result)
15416                 return result;
15417         }
15418         if (node.namedBindings) {
15419             var result = ts.isNamespaceImport(node.namedBindings)
15420                 ? action(node.namedBindings)
15421                 : ts.forEach(node.namedBindings.elements, action);
15422             if (result)
15423                 return result;
15424         }
15425     }
15426     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
15427     function hasQuestionToken(node) {
15428         if (node) {
15429             switch (node.kind) {
15430                 case 160 /* Parameter */:
15431                 case 165 /* MethodDeclaration */:
15432                 case 164 /* MethodSignature */:
15433                 case 289 /* ShorthandPropertyAssignment */:
15434                 case 288 /* PropertyAssignment */:
15435                 case 163 /* PropertyDeclaration */:
15436                 case 162 /* PropertySignature */:
15437                     return node.questionToken !== undefined;
15438             }
15439         }
15440         return false;
15441     }
15442     ts.hasQuestionToken = hasQuestionToken;
15443     function isJSDocConstructSignature(node) {
15444         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
15445         var name = ts.tryCast(param && param.name, ts.isIdentifier);
15446         return !!name && name.escapedText === "new";
15447     }
15448     ts.isJSDocConstructSignature = isJSDocConstructSignature;
15449     function isJSDocTypeAlias(node) {
15450         return node.kind === 331 /* JSDocTypedefTag */ || node.kind === 324 /* JSDocCallbackTag */ || node.kind === 325 /* JSDocEnumTag */;
15451     }
15452     ts.isJSDocTypeAlias = isJSDocTypeAlias;
15453     function isTypeAlias(node) {
15454         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
15455     }
15456     ts.isTypeAlias = isTypeAlias;
15457     function getSourceOfAssignment(node) {
15458         return ts.isExpressionStatement(node) &&
15459             ts.isBinaryExpression(node.expression) &&
15460             node.expression.operatorToken.kind === 62 /* EqualsToken */
15461             ? getRightMostAssignedExpression(node.expression)
15462             : undefined;
15463     }
15464     function getSourceOfDefaultedAssignment(node) {
15465         return ts.isExpressionStatement(node) &&
15466             ts.isBinaryExpression(node.expression) &&
15467             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
15468             ts.isBinaryExpression(node.expression.right) &&
15469             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
15470             ? node.expression.right.right
15471             : undefined;
15472     }
15473     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
15474         switch (node.kind) {
15475             case 232 /* VariableStatement */:
15476                 var v = getSingleVariableOfVariableStatement(node);
15477                 return v && v.initializer;
15478             case 163 /* PropertyDeclaration */:
15479                 return node.initializer;
15480             case 288 /* PropertyAssignment */:
15481                 return node.initializer;
15482         }
15483     }
15484     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
15485     function getSingleVariableOfVariableStatement(node) {
15486         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
15487     }
15488     ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement;
15489     function getNestedModuleDeclaration(node) {
15490         return ts.isModuleDeclaration(node) &&
15491             node.body &&
15492             node.body.kind === 256 /* ModuleDeclaration */
15493             ? node.body
15494             : undefined;
15495     }
15496     function getJSDocCommentsAndTags(hostNode, noCache) {
15497         var result;
15498         // Pull parameter comments from declaring function as well
15499         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
15500             result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
15501         }
15502         var node = hostNode;
15503         while (node && node.parent) {
15504             if (ts.hasJSDocNodes(node)) {
15505                 result = ts.append(result, ts.last(node.jsDoc));
15506             }
15507             if (node.kind === 160 /* Parameter */) {
15508                 result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node));
15509                 break;
15510             }
15511             if (node.kind === 159 /* TypeParameter */) {
15512                 result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node));
15513                 break;
15514             }
15515             node = getNextJSDocCommentLocation(node);
15516         }
15517         return result || ts.emptyArray;
15518     }
15519     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
15520     function getNextJSDocCommentLocation(node) {
15521         var parent = node.parent;
15522         if (parent.kind === 288 /* PropertyAssignment */ ||
15523             parent.kind === 266 /* ExportAssignment */ ||
15524             parent.kind === 163 /* PropertyDeclaration */ ||
15525             parent.kind === 233 /* ExpressionStatement */ && node.kind === 201 /* PropertyAccessExpression */ ||
15526             getNestedModuleDeclaration(parent) ||
15527             ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
15528             return parent;
15529         }
15530         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
15531         // /**
15532         //   * @param {number} name
15533         //   * @returns {number}
15534         //   */
15535         // var x = function(name) { return name.length; }
15536         else if (parent.parent &&
15537             (getSingleVariableOfVariableStatement(parent.parent) === node ||
15538                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
15539             return parent.parent;
15540         }
15541         else if (parent.parent && parent.parent.parent &&
15542             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
15543                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
15544                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
15545             return parent.parent.parent;
15546         }
15547     }
15548     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
15549     function getParameterSymbolFromJSDoc(node) {
15550         if (node.symbol) {
15551             return node.symbol;
15552         }
15553         if (!ts.isIdentifier(node.name)) {
15554             return undefined;
15555         }
15556         var name = node.name.escapedText;
15557         var decl = getHostSignatureFromJSDoc(node);
15558         if (!decl) {
15559             return undefined;
15560         }
15561         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 78 /* Identifier */ && p.name.escapedText === name; });
15562         return parameter && parameter.symbol;
15563     }
15564     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
15565     function getHostSignatureFromJSDoc(node) {
15566         var host = getEffectiveJSDocHost(node);
15567         return host && ts.isFunctionLike(host) ? host : undefined;
15568     }
15569     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
15570     function getEffectiveJSDocHost(node) {
15571         var host = getJSDocHost(node);
15572         var decl = getSourceOfDefaultedAssignment(host) ||
15573             getSourceOfAssignment(host) ||
15574             getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
15575             getSingleVariableOfVariableStatement(host) ||
15576             getNestedModuleDeclaration(host) ||
15577             host;
15578         return decl;
15579     }
15580     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
15581     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments.  */
15582     function getJSDocHost(node) {
15583         return ts.Debug.checkDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
15584     }
15585     ts.getJSDocHost = getJSDocHost;
15586     function getTypeParameterFromJsDoc(node) {
15587         var name = node.name.escapedText;
15588         var typeParameters = node.parent.parent.parent.typeParameters;
15589         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
15590     }
15591     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
15592     function hasRestParameter(s) {
15593         var last = ts.lastOrUndefined(s.parameters);
15594         return !!last && isRestParameter(last);
15595     }
15596     ts.hasRestParameter = hasRestParameter;
15597     function isRestParameter(node) {
15598         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
15599         return node.dotDotDotToken !== undefined || !!type && type.kind === 309 /* JSDocVariadicType */;
15600     }
15601     ts.isRestParameter = isRestParameter;
15602     function hasTypeArguments(node) {
15603         return !!node.typeArguments;
15604     }
15605     ts.hasTypeArguments = hasTypeArguments;
15606     var AssignmentKind;
15607     (function (AssignmentKind) {
15608         AssignmentKind[AssignmentKind["None"] = 0] = "None";
15609         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
15610         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
15611     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
15612     function getAssignmentTargetKind(node) {
15613         var parent = node.parent;
15614         while (true) {
15615             switch (parent.kind) {
15616                 case 216 /* BinaryExpression */:
15617                     var binaryOperator = parent.operatorToken.kind;
15618                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
15619                         binaryOperator === 62 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ :
15620                         0 /* None */;
15621                 case 214 /* PrefixUnaryExpression */:
15622                 case 215 /* PostfixUnaryExpression */:
15623                     var unaryOperator = parent.operator;
15624                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
15625                 case 238 /* ForInStatement */:
15626                 case 239 /* ForOfStatement */:
15627                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
15628                 case 207 /* ParenthesizedExpression */:
15629                 case 199 /* ArrayLiteralExpression */:
15630                 case 220 /* SpreadElement */:
15631                 case 225 /* NonNullExpression */:
15632                     node = parent;
15633                     break;
15634                 case 289 /* ShorthandPropertyAssignment */:
15635                     if (parent.name !== node) {
15636                         return 0 /* None */;
15637                     }
15638                     node = parent.parent;
15639                     break;
15640                 case 288 /* PropertyAssignment */:
15641                     if (parent.name === node) {
15642                         return 0 /* None */;
15643                     }
15644                     node = parent.parent;
15645                     break;
15646                 default:
15647                     return 0 /* None */;
15648             }
15649             parent = node.parent;
15650         }
15651     }
15652     ts.getAssignmentTargetKind = getAssignmentTargetKind;
15653     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15654     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15655     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15656     // (Note that `p` is not a target in the above examples, only `a`.)
15657     function isAssignmentTarget(node) {
15658         return getAssignmentTargetKind(node) !== 0 /* None */;
15659     }
15660     ts.isAssignmentTarget = isAssignmentTarget;
15661     /**
15662      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15663      * the same `var` declaration scope as the node's parent.
15664      */
15665     function isNodeWithPossibleHoistedDeclaration(node) {
15666         switch (node.kind) {
15667             case 230 /* Block */:
15668             case 232 /* VariableStatement */:
15669             case 243 /* WithStatement */:
15670             case 234 /* IfStatement */:
15671             case 244 /* SwitchStatement */:
15672             case 258 /* CaseBlock */:
15673             case 284 /* CaseClause */:
15674             case 285 /* DefaultClause */:
15675             case 245 /* LabeledStatement */:
15676             case 237 /* ForStatement */:
15677             case 238 /* ForInStatement */:
15678             case 239 /* ForOfStatement */:
15679             case 235 /* DoStatement */:
15680             case 236 /* WhileStatement */:
15681             case 247 /* TryStatement */:
15682             case 287 /* CatchClause */:
15683                 return true;
15684         }
15685         return false;
15686     }
15687     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15688     function isValueSignatureDeclaration(node) {
15689         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15690     }
15691     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15692     function walkUp(node, kind) {
15693         while (node && node.kind === kind) {
15694             node = node.parent;
15695         }
15696         return node;
15697     }
15698     function walkUpParenthesizedTypes(node) {
15699         return walkUp(node, 186 /* ParenthesizedType */);
15700     }
15701     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15702     function walkUpParenthesizedExpressions(node) {
15703         return walkUp(node, 207 /* ParenthesizedExpression */);
15704     }
15705     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15706     /**
15707      * Walks up parenthesized types.
15708      * It returns both the outermost parenthesized type and its parent.
15709      * If given node is not a parenthesiezd type, undefined is return as the former.
15710      */
15711     function walkUpParenthesizedTypesAndGetParentAndChild(node) {
15712         var child;
15713         while (node && node.kind === 186 /* ParenthesizedType */) {
15714             child = node;
15715             node = node.parent;
15716         }
15717         return [child, node];
15718     }
15719     ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild;
15720     function skipParentheses(node) {
15721         return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15722     }
15723     ts.skipParentheses = skipParentheses;
15724     function skipParenthesesUp(node) {
15725         while (node.kind === 207 /* ParenthesizedExpression */) {
15726             node = node.parent;
15727         }
15728         return node;
15729     }
15730     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15731     function isDeleteTarget(node) {
15732         if (node.kind !== 201 /* PropertyAccessExpression */ && node.kind !== 202 /* ElementAccessExpression */) {
15733             return false;
15734         }
15735         node = walkUpParenthesizedExpressions(node.parent);
15736         return node && node.kind === 210 /* DeleteExpression */;
15737     }
15738     ts.isDeleteTarget = isDeleteTarget;
15739     function isNodeDescendantOf(node, ancestor) {
15740         while (node) {
15741             if (node === ancestor)
15742                 return true;
15743             node = node.parent;
15744         }
15745         return false;
15746     }
15747     ts.isNodeDescendantOf = isNodeDescendantOf;
15748     // True if `name` is the name of a declaration node
15749     function isDeclarationName(name) {
15750         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15751     }
15752     ts.isDeclarationName = isDeclarationName;
15753     // See GH#16030
15754     function getDeclarationFromName(name) {
15755         var parent = name.parent;
15756         switch (name.kind) {
15757             case 10 /* StringLiteral */:
15758             case 14 /* NoSubstitutionTemplateLiteral */:
15759             case 8 /* NumericLiteral */:
15760                 if (ts.isComputedPropertyName(parent))
15761                     return parent.parent;
15762             // falls through
15763             case 78 /* Identifier */:
15764                 if (ts.isDeclaration(parent)) {
15765                     return parent.name === name ? parent : undefined;
15766                 }
15767                 else if (ts.isQualifiedName(parent)) {
15768                     var tag = parent.parent;
15769                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
15770                 }
15771                 else {
15772                     var binExp = parent.parent;
15773                     return ts.isBinaryExpression(binExp) &&
15774                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
15775                         (binExp.left.symbol || binExp.symbol) &&
15776                         ts.getNameOfDeclaration(binExp) === name
15777                         ? binExp
15778                         : undefined;
15779                 }
15780             case 79 /* PrivateIdentifier */:
15781                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
15782             default:
15783                 return undefined;
15784         }
15785     }
15786     ts.getDeclarationFromName = getDeclarationFromName;
15787     function isLiteralComputedPropertyDeclarationName(node) {
15788         return isStringOrNumericLiteralLike(node) &&
15789             node.parent.kind === 158 /* ComputedPropertyName */ &&
15790             ts.isDeclaration(node.parent.parent);
15791     }
15792     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
15793     // Return true if the given identifier is classified as an IdentifierName
15794     function isIdentifierName(node) {
15795         var parent = node.parent;
15796         switch (parent.kind) {
15797             case 163 /* PropertyDeclaration */:
15798             case 162 /* PropertySignature */:
15799             case 165 /* MethodDeclaration */:
15800             case 164 /* MethodSignature */:
15801             case 167 /* GetAccessor */:
15802             case 168 /* SetAccessor */:
15803             case 291 /* EnumMember */:
15804             case 288 /* PropertyAssignment */:
15805             case 201 /* PropertyAccessExpression */:
15806                 // Name in member declaration or property name in property access
15807                 return parent.name === node;
15808             case 157 /* QualifiedName */:
15809                 // Name on right hand side of dot in a type query or type reference
15810                 return parent.right === node;
15811             case 198 /* BindingElement */:
15812             case 265 /* ImportSpecifier */:
15813                 // Property name in binding element or import specifier
15814                 return parent.propertyName === node;
15815             case 270 /* ExportSpecifier */:
15816             case 280 /* JsxAttribute */:
15817                 // Any name in an export specifier or JSX Attribute
15818                 return true;
15819         }
15820         return false;
15821     }
15822     ts.isIdentifierName = isIdentifierName;
15823     // An alias symbol is created by one of the following declarations:
15824     // import <symbol> = ...
15825     // import <symbol> from ...
15826     // import * as <symbol> from ...
15827     // import { x as <symbol> } from ...
15828     // export { x as <symbol> } from ...
15829     // export * as ns <symbol> from ...
15830     // export = <EntityNameExpression>
15831     // export default <EntityNameExpression>
15832     // module.exports = <EntityNameExpression>
15833     // {<Identifier>}
15834     // {name: <EntityNameExpression>}
15835     function isAliasSymbolDeclaration(node) {
15836         return node.kind === 260 /* ImportEqualsDeclaration */ ||
15837             node.kind === 259 /* NamespaceExportDeclaration */ ||
15838             node.kind === 262 /* ImportClause */ && !!node.name ||
15839             node.kind === 263 /* NamespaceImport */ ||
15840             node.kind === 269 /* NamespaceExport */ ||
15841             node.kind === 265 /* ImportSpecifier */ ||
15842             node.kind === 270 /* ExportSpecifier */ ||
15843             node.kind === 266 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
15844             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
15845             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
15846             node.kind === 289 /* ShorthandPropertyAssignment */ ||
15847             node.kind === 288 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
15848     }
15849     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
15850     function getAliasDeclarationFromName(node) {
15851         switch (node.parent.kind) {
15852             case 262 /* ImportClause */:
15853             case 265 /* ImportSpecifier */:
15854             case 263 /* NamespaceImport */:
15855             case 270 /* ExportSpecifier */:
15856             case 266 /* ExportAssignment */:
15857             case 260 /* ImportEqualsDeclaration */:
15858                 return node.parent;
15859             case 157 /* QualifiedName */:
15860                 do {
15861                     node = node.parent;
15862                 } while (node.parent.kind === 157 /* QualifiedName */);
15863                 return getAliasDeclarationFromName(node);
15864         }
15865     }
15866     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
15867     function isAliasableExpression(e) {
15868         return isEntityNameExpression(e) || ts.isClassExpression(e);
15869     }
15870     ts.isAliasableExpression = isAliasableExpression;
15871     function exportAssignmentIsAlias(node) {
15872         var e = getExportAssignmentExpression(node);
15873         return isAliasableExpression(e);
15874     }
15875     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
15876     function getExportAssignmentExpression(node) {
15877         return ts.isExportAssignment(node) ? node.expression : node.right;
15878     }
15879     ts.getExportAssignmentExpression = getExportAssignmentExpression;
15880     function getPropertyAssignmentAliasLikeExpression(node) {
15881         return node.kind === 289 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 288 /* PropertyAssignment */ ? node.initializer :
15882             node.parent.right;
15883     }
15884     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
15885     function getEffectiveBaseTypeNode(node) {
15886         var baseType = getClassExtendsHeritageElement(node);
15887         if (baseType && isInJSFile(node)) {
15888             // Prefer an @augments tag because it may have type parameters.
15889             var tag = ts.getJSDocAugmentsTag(node);
15890             if (tag) {
15891                 return tag.class;
15892             }
15893         }
15894         return baseType;
15895     }
15896     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
15897     function getClassExtendsHeritageElement(node) {
15898         var heritageClause = getHeritageClause(node.heritageClauses, 93 /* ExtendsKeyword */);
15899         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
15900     }
15901     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
15902     function getEffectiveImplementsTypeNodes(node) {
15903         if (isInJSFile(node)) {
15904             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
15905         }
15906         else {
15907             var heritageClause = getHeritageClause(node.heritageClauses, 116 /* ImplementsKeyword */);
15908             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
15909         }
15910     }
15911     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
15912     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
15913     function getAllSuperTypeNodes(node) {
15914         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
15915             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
15916                 ts.emptyArray;
15917     }
15918     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
15919     function getInterfaceBaseTypeNodes(node) {
15920         var heritageClause = getHeritageClause(node.heritageClauses, 93 /* ExtendsKeyword */);
15921         return heritageClause ? heritageClause.types : undefined;
15922     }
15923     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
15924     function getHeritageClause(clauses, kind) {
15925         if (clauses) {
15926             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
15927                 var clause = clauses_1[_i];
15928                 if (clause.token === kind) {
15929                     return clause;
15930                 }
15931             }
15932         }
15933         return undefined;
15934     }
15935     ts.getHeritageClause = getHeritageClause;
15936     function getAncestor(node, kind) {
15937         while (node) {
15938             if (node.kind === kind) {
15939                 return node;
15940             }
15941             node = node.parent;
15942         }
15943         return undefined;
15944     }
15945     ts.getAncestor = getAncestor;
15946     function isKeyword(token) {
15947         return 80 /* FirstKeyword */ <= token && token <= 156 /* LastKeyword */;
15948     }
15949     ts.isKeyword = isKeyword;
15950     function isContextualKeyword(token) {
15951         return 125 /* FirstContextualKeyword */ <= token && token <= 156 /* LastContextualKeyword */;
15952     }
15953     ts.isContextualKeyword = isContextualKeyword;
15954     function isNonContextualKeyword(token) {
15955         return isKeyword(token) && !isContextualKeyword(token);
15956     }
15957     ts.isNonContextualKeyword = isNonContextualKeyword;
15958     function isFutureReservedKeyword(token) {
15959         return 116 /* FirstFutureReservedWord */ <= token && token <= 124 /* LastFutureReservedWord */;
15960     }
15961     ts.isFutureReservedKeyword = isFutureReservedKeyword;
15962     function isStringANonContextualKeyword(name) {
15963         var token = ts.stringToToken(name);
15964         return token !== undefined && isNonContextualKeyword(token);
15965     }
15966     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
15967     function isStringAKeyword(name) {
15968         var token = ts.stringToToken(name);
15969         return token !== undefined && isKeyword(token);
15970     }
15971     ts.isStringAKeyword = isStringAKeyword;
15972     function isIdentifierANonContextualKeyword(_a) {
15973         var originalKeywordKind = _a.originalKeywordKind;
15974         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
15975     }
15976     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
15977     function isTrivia(token) {
15978         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
15979     }
15980     ts.isTrivia = isTrivia;
15981     var FunctionFlags;
15982     (function (FunctionFlags) {
15983         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
15984         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
15985         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
15986         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
15987         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
15988     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
15989     function getFunctionFlags(node) {
15990         if (!node) {
15991             return 4 /* Invalid */;
15992         }
15993         var flags = 0 /* Normal */;
15994         switch (node.kind) {
15995             case 251 /* FunctionDeclaration */:
15996             case 208 /* FunctionExpression */:
15997             case 165 /* MethodDeclaration */:
15998                 if (node.asteriskToken) {
15999                     flags |= 1 /* Generator */;
16000                 }
16001             // falls through
16002             case 209 /* ArrowFunction */:
16003                 if (hasSyntacticModifier(node, 256 /* Async */)) {
16004                     flags |= 2 /* Async */;
16005                 }
16006                 break;
16007         }
16008         if (!node.body) {
16009             flags |= 4 /* Invalid */;
16010         }
16011         return flags;
16012     }
16013     ts.getFunctionFlags = getFunctionFlags;
16014     function isAsyncFunction(node) {
16015         switch (node.kind) {
16016             case 251 /* FunctionDeclaration */:
16017             case 208 /* FunctionExpression */:
16018             case 209 /* ArrowFunction */:
16019             case 165 /* MethodDeclaration */:
16020                 return node.body !== undefined
16021                     && node.asteriskToken === undefined
16022                     && hasSyntacticModifier(node, 256 /* Async */);
16023         }
16024         return false;
16025     }
16026     ts.isAsyncFunction = isAsyncFunction;
16027     function isStringOrNumericLiteralLike(node) {
16028         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
16029     }
16030     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
16031     function isSignedNumericLiteral(node) {
16032         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
16033     }
16034     ts.isSignedNumericLiteral = isSignedNumericLiteral;
16035     /**
16036      * A declaration has a dynamic name if all of the following are true:
16037      *   1. The declaration has a computed property name.
16038      *   2. The computed name is *not* expressed as a StringLiteral.
16039      *   3. The computed name is *not* expressed as a NumericLiteral.
16040      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
16041      *      immediately followed by a NumericLiteral.
16042      *   5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
16043      *      is a property of the Symbol constructor that denotes a built-in
16044      *      Symbol.
16045      */
16046     function hasDynamicName(declaration) {
16047         var name = ts.getNameOfDeclaration(declaration);
16048         return !!name && isDynamicName(name);
16049     }
16050     ts.hasDynamicName = hasDynamicName;
16051     function isDynamicName(name) {
16052         if (!(name.kind === 158 /* ComputedPropertyName */ || name.kind === 202 /* ElementAccessExpression */)) {
16053             return false;
16054         }
16055         var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
16056         return !isStringOrNumericLiteralLike(expr) &&
16057             !isSignedNumericLiteral(expr) &&
16058             !isWellKnownSymbolSyntactically(expr);
16059     }
16060     ts.isDynamicName = isDynamicName;
16061     /**
16062      * Checks if the expression is of the form:
16063      *    Symbol.name
16064      * where Symbol is literally the word "Symbol", and name is any identifierName
16065      */
16066     function isWellKnownSymbolSyntactically(node) {
16067         return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
16068     }
16069     ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
16070     function getPropertyNameForPropertyNameNode(name) {
16071         switch (name.kind) {
16072             case 78 /* Identifier */:
16073             case 79 /* PrivateIdentifier */:
16074                 return name.escapedText;
16075             case 10 /* StringLiteral */:
16076             case 8 /* NumericLiteral */:
16077                 return ts.escapeLeadingUnderscores(name.text);
16078             case 158 /* ComputedPropertyName */:
16079                 var nameExpression = name.expression;
16080                 if (isWellKnownSymbolSyntactically(nameExpression)) {
16081                     return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
16082                 }
16083                 else if (isStringOrNumericLiteralLike(nameExpression)) {
16084                     return ts.escapeLeadingUnderscores(nameExpression.text);
16085                 }
16086                 else if (isSignedNumericLiteral(nameExpression)) {
16087                     if (nameExpression.operator === 40 /* MinusToken */) {
16088                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
16089                     }
16090                     return nameExpression.operand.text;
16091                 }
16092                 return undefined;
16093             default:
16094                 return ts.Debug.assertNever(name);
16095         }
16096     }
16097     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
16098     function isPropertyNameLiteral(node) {
16099         switch (node.kind) {
16100             case 78 /* Identifier */:
16101             case 10 /* StringLiteral */:
16102             case 14 /* NoSubstitutionTemplateLiteral */:
16103             case 8 /* NumericLiteral */:
16104                 return true;
16105             default:
16106                 return false;
16107         }
16108     }
16109     ts.isPropertyNameLiteral = isPropertyNameLiteral;
16110     function getTextOfIdentifierOrLiteral(node) {
16111         return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
16112     }
16113     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
16114     function getEscapedTextOfIdentifierOrLiteral(node) {
16115         return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
16116     }
16117     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
16118     function getPropertyNameForUniqueESSymbol(symbol) {
16119         return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
16120     }
16121     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
16122     function getPropertyNameForKnownSymbolName(symbolName) {
16123         return "__@" + symbolName;
16124     }
16125     ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
16126     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
16127         return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
16128     }
16129     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
16130     function isKnownSymbol(symbol) {
16131         return ts.startsWith(symbol.escapedName, "__@");
16132     }
16133     ts.isKnownSymbol = isKnownSymbol;
16134     /**
16135      * Includes the word "Symbol" with unicode escapes
16136      */
16137     function isESSymbolIdentifier(node) {
16138         return node.kind === 78 /* Identifier */ && node.escapedText === "Symbol";
16139     }
16140     ts.isESSymbolIdentifier = isESSymbolIdentifier;
16141     function isPushOrUnshiftIdentifier(node) {
16142         return node.escapedText === "push" || node.escapedText === "unshift";
16143     }
16144     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
16145     function isParameterDeclaration(node) {
16146         var root = getRootDeclaration(node);
16147         return root.kind === 160 /* Parameter */;
16148     }
16149     ts.isParameterDeclaration = isParameterDeclaration;
16150     function getRootDeclaration(node) {
16151         while (node.kind === 198 /* BindingElement */) {
16152             node = node.parent.parent;
16153         }
16154         return node;
16155     }
16156     ts.getRootDeclaration = getRootDeclaration;
16157     function nodeStartsNewLexicalEnvironment(node) {
16158         var kind = node.kind;
16159         return kind === 166 /* Constructor */
16160             || kind === 208 /* FunctionExpression */
16161             || kind === 251 /* FunctionDeclaration */
16162             || kind === 209 /* ArrowFunction */
16163             || kind === 165 /* MethodDeclaration */
16164             || kind === 167 /* GetAccessor */
16165             || kind === 168 /* SetAccessor */
16166             || kind === 256 /* ModuleDeclaration */
16167             || kind === 297 /* SourceFile */;
16168     }
16169     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
16170     function nodeIsSynthesized(range) {
16171         return positionIsSynthesized(range.pos)
16172             || positionIsSynthesized(range.end);
16173     }
16174     ts.nodeIsSynthesized = nodeIsSynthesized;
16175     function getOriginalSourceFile(sourceFile) {
16176         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
16177     }
16178     ts.getOriginalSourceFile = getOriginalSourceFile;
16179     var Associativity;
16180     (function (Associativity) {
16181         Associativity[Associativity["Left"] = 0] = "Left";
16182         Associativity[Associativity["Right"] = 1] = "Right";
16183     })(Associativity = ts.Associativity || (ts.Associativity = {}));
16184     function getExpressionAssociativity(expression) {
16185         var operator = getOperator(expression);
16186         var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined;
16187         return getOperatorAssociativity(expression.kind, operator, hasArguments);
16188     }
16189     ts.getExpressionAssociativity = getExpressionAssociativity;
16190     function getOperatorAssociativity(kind, operator, hasArguments) {
16191         switch (kind) {
16192             case 204 /* NewExpression */:
16193                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
16194             case 214 /* PrefixUnaryExpression */:
16195             case 211 /* TypeOfExpression */:
16196             case 212 /* VoidExpression */:
16197             case 210 /* DeleteExpression */:
16198             case 213 /* AwaitExpression */:
16199             case 217 /* ConditionalExpression */:
16200             case 219 /* YieldExpression */:
16201                 return 1 /* Right */;
16202             case 216 /* BinaryExpression */:
16203                 switch (operator) {
16204                     case 42 /* AsteriskAsteriskToken */:
16205                     case 62 /* EqualsToken */:
16206                     case 63 /* PlusEqualsToken */:
16207                     case 64 /* MinusEqualsToken */:
16208                     case 66 /* AsteriskAsteriskEqualsToken */:
16209                     case 65 /* AsteriskEqualsToken */:
16210                     case 67 /* SlashEqualsToken */:
16211                     case 68 /* PercentEqualsToken */:
16212                     case 69 /* LessThanLessThanEqualsToken */:
16213                     case 70 /* GreaterThanGreaterThanEqualsToken */:
16214                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
16215                     case 72 /* AmpersandEqualsToken */:
16216                     case 77 /* CaretEqualsToken */:
16217                     case 73 /* BarEqualsToken */:
16218                     case 74 /* BarBarEqualsToken */:
16219                     case 75 /* AmpersandAmpersandEqualsToken */:
16220                     case 76 /* QuestionQuestionEqualsToken */:
16221                         return 1 /* Right */;
16222                 }
16223         }
16224         return 0 /* Left */;
16225     }
16226     ts.getOperatorAssociativity = getOperatorAssociativity;
16227     function getExpressionPrecedence(expression) {
16228         var operator = getOperator(expression);
16229         var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined;
16230         return getOperatorPrecedence(expression.kind, operator, hasArguments);
16231     }
16232     ts.getExpressionPrecedence = getExpressionPrecedence;
16233     function getOperator(expression) {
16234         if (expression.kind === 216 /* BinaryExpression */) {
16235             return expression.operatorToken.kind;
16236         }
16237         else if (expression.kind === 214 /* PrefixUnaryExpression */ || expression.kind === 215 /* PostfixUnaryExpression */) {
16238             return expression.operator;
16239         }
16240         else {
16241             return expression.kind;
16242         }
16243     }
16244     ts.getOperator = getOperator;
16245     var OperatorPrecedence;
16246     (function (OperatorPrecedence) {
16247         // Expression:
16248         //     AssignmentExpression
16249         //     Expression `,` AssignmentExpression
16250         OperatorPrecedence[OperatorPrecedence["Comma"] = 0] = "Comma";
16251         // NOTE: `Spread` is higher than `Comma` due to how it is parsed in |ElementList|
16252         // SpreadElement:
16253         //     `...` AssignmentExpression
16254         OperatorPrecedence[OperatorPrecedence["Spread"] = 1] = "Spread";
16255         // AssignmentExpression:
16256         //     ConditionalExpression
16257         //     YieldExpression
16258         //     ArrowFunction
16259         //     AsyncArrowFunction
16260         //     LeftHandSideExpression `=` AssignmentExpression
16261         //     LeftHandSideExpression AssignmentOperator AssignmentExpression
16262         //
16263         // NOTE: AssignmentExpression is broken down into several precedences due to the requirements
16264         //       of the parenthesizer rules.
16265         // AssignmentExpression: YieldExpression
16266         // YieldExpression:
16267         //     `yield`
16268         //     `yield` AssignmentExpression
16269         //     `yield` `*` AssignmentExpression
16270         OperatorPrecedence[OperatorPrecedence["Yield"] = 2] = "Yield";
16271         // AssignmentExpression: LeftHandSideExpression `=` AssignmentExpression
16272         // AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression
16273         // AssignmentOperator: one of
16274         //     `*=` `/=` `%=` `+=` `-=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` `**=`
16275         OperatorPrecedence[OperatorPrecedence["Assignment"] = 3] = "Assignment";
16276         // NOTE: `Conditional` is considered higher than `Assignment` here, but in reality they have
16277         //       the same precedence.
16278         // AssignmentExpression: ConditionalExpression
16279         // ConditionalExpression:
16280         //     ShortCircuitExpression
16281         //     ShortCircuitExpression `?` AssignmentExpression `:` AssignmentExpression
16282         // ShortCircuitExpression:
16283         //     LogicalORExpression
16284         //     CoalesceExpression
16285         OperatorPrecedence[OperatorPrecedence["Conditional"] = 4] = "Conditional";
16286         // CoalesceExpression:
16287         //     CoalesceExpressionHead `??` BitwiseORExpression
16288         // CoalesceExpressionHead:
16289         //     CoalesceExpression
16290         //     BitwiseORExpression
16291         OperatorPrecedence[OperatorPrecedence["Coalesce"] = 4] = "Coalesce";
16292         // LogicalORExpression:
16293         //     LogicalANDExpression
16294         //     LogicalORExpression `||` LogicalANDExpression
16295         OperatorPrecedence[OperatorPrecedence["LogicalOR"] = 5] = "LogicalOR";
16296         // LogicalANDExpression:
16297         //     BitwiseORExpression
16298         //     LogicalANDExprerssion `&&` BitwiseORExpression
16299         OperatorPrecedence[OperatorPrecedence["LogicalAND"] = 6] = "LogicalAND";
16300         // BitwiseORExpression:
16301         //     BitwiseXORExpression
16302         //     BitwiseORExpression `^` BitwiseXORExpression
16303         OperatorPrecedence[OperatorPrecedence["BitwiseOR"] = 7] = "BitwiseOR";
16304         // BitwiseXORExpression:
16305         //     BitwiseANDExpression
16306         //     BitwiseXORExpression `^` BitwiseANDExpression
16307         OperatorPrecedence[OperatorPrecedence["BitwiseXOR"] = 8] = "BitwiseXOR";
16308         // BitwiseANDExpression:
16309         //     EqualityExpression
16310         //     BitwiseANDExpression `^` EqualityExpression
16311         OperatorPrecedence[OperatorPrecedence["BitwiseAND"] = 9] = "BitwiseAND";
16312         // EqualityExpression:
16313         //     RelationalExpression
16314         //     EqualityExpression `==` RelationalExpression
16315         //     EqualityExpression `!=` RelationalExpression
16316         //     EqualityExpression `===` RelationalExpression
16317         //     EqualityExpression `!==` RelationalExpression
16318         OperatorPrecedence[OperatorPrecedence["Equality"] = 10] = "Equality";
16319         // RelationalExpression:
16320         //     ShiftExpression
16321         //     RelationalExpression `<` ShiftExpression
16322         //     RelationalExpression `>` ShiftExpression
16323         //     RelationalExpression `<=` ShiftExpression
16324         //     RelationalExpression `>=` ShiftExpression
16325         //     RelationalExpression `instanceof` ShiftExpression
16326         //     RelationalExpression `in` ShiftExpression
16327         //     [+TypeScript] RelationalExpression `as` Type
16328         OperatorPrecedence[OperatorPrecedence["Relational"] = 11] = "Relational";
16329         // ShiftExpression:
16330         //     AdditiveExpression
16331         //     ShiftExpression `<<` AdditiveExpression
16332         //     ShiftExpression `>>` AdditiveExpression
16333         //     ShiftExpression `>>>` AdditiveExpression
16334         OperatorPrecedence[OperatorPrecedence["Shift"] = 12] = "Shift";
16335         // AdditiveExpression:
16336         //     MultiplicativeExpression
16337         //     AdditiveExpression `+` MultiplicativeExpression
16338         //     AdditiveExpression `-` MultiplicativeExpression
16339         OperatorPrecedence[OperatorPrecedence["Additive"] = 13] = "Additive";
16340         // MultiplicativeExpression:
16341         //     ExponentiationExpression
16342         //     MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
16343         // MultiplicativeOperator: one of `*`, `/`, `%`
16344         OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 14] = "Multiplicative";
16345         // ExponentiationExpression:
16346         //     UnaryExpression
16347         //     UpdateExpression `**` ExponentiationExpression
16348         OperatorPrecedence[OperatorPrecedence["Exponentiation"] = 15] = "Exponentiation";
16349         // UnaryExpression:
16350         //     UpdateExpression
16351         //     `delete` UnaryExpression
16352         //     `void` UnaryExpression
16353         //     `typeof` UnaryExpression
16354         //     `+` UnaryExpression
16355         //     `-` UnaryExpression
16356         //     `~` UnaryExpression
16357         //     `!` UnaryExpression
16358         //     AwaitExpression
16359         // UpdateExpression:            // TODO: Do we need to investigate the precedence here?
16360         //     `++` UnaryExpression
16361         //     `--` UnaryExpression
16362         OperatorPrecedence[OperatorPrecedence["Unary"] = 16] = "Unary";
16363         // UpdateExpression:
16364         //     LeftHandSideExpression
16365         //     LeftHandSideExpression `++`
16366         //     LeftHandSideExpression `--`
16367         OperatorPrecedence[OperatorPrecedence["Update"] = 17] = "Update";
16368         // LeftHandSideExpression:
16369         //     NewExpression
16370         //     CallExpression
16371         // NewExpression:
16372         //     MemberExpression
16373         //     `new` NewExpression
16374         OperatorPrecedence[OperatorPrecedence["LeftHandSide"] = 18] = "LeftHandSide";
16375         // CallExpression:
16376         //     CoverCallExpressionAndAsyncArrowHead
16377         //     SuperCall
16378         //     ImportCall
16379         //     CallExpression Arguments
16380         //     CallExpression `[` Expression `]`
16381         //     CallExpression `.` IdentifierName
16382         //     CallExpression TemplateLiteral
16383         // MemberExpression:
16384         //     PrimaryExpression
16385         //     MemberExpression `[` Expression `]`
16386         //     MemberExpression `.` IdentifierName
16387         //     MemberExpression TemplateLiteral
16388         //     SuperProperty
16389         //     MetaProperty
16390         //     `new` MemberExpression Arguments
16391         OperatorPrecedence[OperatorPrecedence["Member"] = 19] = "Member";
16392         // TODO: JSXElement?
16393         // PrimaryExpression:
16394         //     `this`
16395         //     IdentifierReference
16396         //     Literal
16397         //     ArrayLiteral
16398         //     ObjectLiteral
16399         //     FunctionExpression
16400         //     ClassExpression
16401         //     GeneratorExpression
16402         //     AsyncFunctionExpression
16403         //     AsyncGeneratorExpression
16404         //     RegularExpressionLiteral
16405         //     TemplateLiteral
16406         //     CoverParenthesizedExpressionAndArrowParameterList
16407         OperatorPrecedence[OperatorPrecedence["Primary"] = 20] = "Primary";
16408         OperatorPrecedence[OperatorPrecedence["Highest"] = 20] = "Highest";
16409         OperatorPrecedence[OperatorPrecedence["Lowest"] = 0] = "Lowest";
16410         // -1 is lower than all other precedences. Returning it will cause binary expression
16411         // parsing to stop.
16412         OperatorPrecedence[OperatorPrecedence["Invalid"] = -1] = "Invalid";
16413     })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {}));
16414     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
16415         switch (nodeKind) {
16416             case 337 /* CommaListExpression */:
16417                 return 0 /* Comma */;
16418             case 220 /* SpreadElement */:
16419                 return 1 /* Spread */;
16420             case 219 /* YieldExpression */:
16421                 return 2 /* Yield */;
16422             case 217 /* ConditionalExpression */:
16423                 return 4 /* Conditional */;
16424             case 216 /* BinaryExpression */:
16425                 switch (operatorKind) {
16426                     case 27 /* CommaToken */:
16427                         return 0 /* Comma */;
16428                     case 62 /* EqualsToken */:
16429                     case 63 /* PlusEqualsToken */:
16430                     case 64 /* MinusEqualsToken */:
16431                     case 66 /* AsteriskAsteriskEqualsToken */:
16432                     case 65 /* AsteriskEqualsToken */:
16433                     case 67 /* SlashEqualsToken */:
16434                     case 68 /* PercentEqualsToken */:
16435                     case 69 /* LessThanLessThanEqualsToken */:
16436                     case 70 /* GreaterThanGreaterThanEqualsToken */:
16437                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
16438                     case 72 /* AmpersandEqualsToken */:
16439                     case 77 /* CaretEqualsToken */:
16440                     case 73 /* BarEqualsToken */:
16441                     case 74 /* BarBarEqualsToken */:
16442                     case 75 /* AmpersandAmpersandEqualsToken */:
16443                     case 76 /* QuestionQuestionEqualsToken */:
16444                         return 3 /* Assignment */;
16445                     default:
16446                         return getBinaryOperatorPrecedence(operatorKind);
16447                 }
16448             // TODO: Should prefix `++` and `--` be moved to the `Update` precedence?
16449             // TODO: We are missing `TypeAssertionExpression`
16450             case 214 /* PrefixUnaryExpression */:
16451             case 211 /* TypeOfExpression */:
16452             case 212 /* VoidExpression */:
16453             case 210 /* DeleteExpression */:
16454             case 213 /* AwaitExpression */:
16455                 return 16 /* Unary */;
16456             case 215 /* PostfixUnaryExpression */:
16457                 return 17 /* Update */;
16458             case 203 /* CallExpression */:
16459                 return 18 /* LeftHandSide */;
16460             case 204 /* NewExpression */:
16461                 return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */;
16462             case 205 /* TaggedTemplateExpression */:
16463             case 201 /* PropertyAccessExpression */:
16464             case 202 /* ElementAccessExpression */:
16465                 return 19 /* Member */;
16466             case 107 /* ThisKeyword */:
16467             case 105 /* SuperKeyword */:
16468             case 78 /* Identifier */:
16469             case 103 /* NullKeyword */:
16470             case 109 /* TrueKeyword */:
16471             case 94 /* FalseKeyword */:
16472             case 8 /* NumericLiteral */:
16473             case 9 /* BigIntLiteral */:
16474             case 10 /* StringLiteral */:
16475             case 199 /* ArrayLiteralExpression */:
16476             case 200 /* ObjectLiteralExpression */:
16477             case 208 /* FunctionExpression */:
16478             case 209 /* ArrowFunction */:
16479             case 221 /* ClassExpression */:
16480             case 13 /* RegularExpressionLiteral */:
16481             case 14 /* NoSubstitutionTemplateLiteral */:
16482             case 218 /* TemplateExpression */:
16483             case 207 /* ParenthesizedExpression */:
16484             case 222 /* OmittedExpression */:
16485             case 273 /* JsxElement */:
16486             case 274 /* JsxSelfClosingElement */:
16487             case 277 /* JsxFragment */:
16488                 return 20 /* Primary */;
16489             default:
16490                 return -1 /* Invalid */;
16491         }
16492     }
16493     ts.getOperatorPrecedence = getOperatorPrecedence;
16494     function getBinaryOperatorPrecedence(kind) {
16495         switch (kind) {
16496             case 60 /* QuestionQuestionToken */:
16497                 return 4 /* Coalesce */;
16498             case 56 /* BarBarToken */:
16499                 return 5 /* LogicalOR */;
16500             case 55 /* AmpersandAmpersandToken */:
16501                 return 6 /* LogicalAND */;
16502             case 51 /* BarToken */:
16503                 return 7 /* BitwiseOR */;
16504             case 52 /* CaretToken */:
16505                 return 8 /* BitwiseXOR */;
16506             case 50 /* AmpersandToken */:
16507                 return 9 /* BitwiseAND */;
16508             case 34 /* EqualsEqualsToken */:
16509             case 35 /* ExclamationEqualsToken */:
16510             case 36 /* EqualsEqualsEqualsToken */:
16511             case 37 /* ExclamationEqualsEqualsToken */:
16512                 return 10 /* Equality */;
16513             case 29 /* LessThanToken */:
16514             case 31 /* GreaterThanToken */:
16515             case 32 /* LessThanEqualsToken */:
16516             case 33 /* GreaterThanEqualsToken */:
16517             case 101 /* InstanceOfKeyword */:
16518             case 100 /* InKeyword */:
16519             case 126 /* AsKeyword */:
16520                 return 11 /* Relational */;
16521             case 47 /* LessThanLessThanToken */:
16522             case 48 /* GreaterThanGreaterThanToken */:
16523             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
16524                 return 12 /* Shift */;
16525             case 39 /* PlusToken */:
16526             case 40 /* MinusToken */:
16527                 return 13 /* Additive */;
16528             case 41 /* AsteriskToken */:
16529             case 43 /* SlashToken */:
16530             case 44 /* PercentToken */:
16531                 return 14 /* Multiplicative */;
16532             case 42 /* AsteriskAsteriskToken */:
16533                 return 15 /* Exponentiation */;
16534         }
16535         // -1 is lower than all other precedences.  Returning it will cause binary expression
16536         // parsing to stop.
16537         return -1;
16538     }
16539     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
16540     function getSemanticJsxChildren(children) {
16541         return ts.filter(children, function (i) {
16542             switch (i.kind) {
16543                 case 283 /* JsxExpression */:
16544                     return !!i.expression;
16545                 case 11 /* JsxText */:
16546                     return !i.containsOnlyTriviaWhiteSpaces;
16547                 default:
16548                     return true;
16549             }
16550         });
16551     }
16552     ts.getSemanticJsxChildren = getSemanticJsxChildren;
16553     function createDiagnosticCollection() {
16554         var nonFileDiagnostics = []; // See GH#19873
16555         var filesWithDiagnostics = [];
16556         var fileDiagnostics = new ts.Map();
16557         var hasReadNonFileDiagnostics = false;
16558         return {
16559             add: add,
16560             lookup: lookup,
16561             getGlobalDiagnostics: getGlobalDiagnostics,
16562             getDiagnostics: getDiagnostics,
16563             reattachFileDiagnostics: reattachFileDiagnostics
16564         };
16565         function reattachFileDiagnostics(newFile) {
16566             ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
16567         }
16568         function lookup(diagnostic) {
16569             var diagnostics;
16570             if (diagnostic.file) {
16571                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16572             }
16573             else {
16574                 diagnostics = nonFileDiagnostics;
16575             }
16576             if (!diagnostics) {
16577                 return undefined;
16578             }
16579             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
16580             if (result >= 0) {
16581                 return diagnostics[result];
16582             }
16583             return undefined;
16584         }
16585         function add(diagnostic) {
16586             var diagnostics;
16587             if (diagnostic.file) {
16588                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16589                 if (!diagnostics) {
16590                     diagnostics = []; // See GH#19873
16591                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
16592                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
16593                 }
16594             }
16595             else {
16596                 // If we've already read the non-file diagnostics, do not modify the existing array.
16597                 if (hasReadNonFileDiagnostics) {
16598                     hasReadNonFileDiagnostics = false;
16599                     nonFileDiagnostics = nonFileDiagnostics.slice();
16600                 }
16601                 diagnostics = nonFileDiagnostics;
16602             }
16603             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
16604         }
16605         function getGlobalDiagnostics() {
16606             hasReadNonFileDiagnostics = true;
16607             return nonFileDiagnostics;
16608         }
16609         function getDiagnostics(fileName) {
16610             if (fileName) {
16611                 return fileDiagnostics.get(fileName) || [];
16612             }
16613             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
16614             if (!nonFileDiagnostics.length) {
16615                 return fileDiags;
16616             }
16617             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
16618             return fileDiags;
16619         }
16620     }
16621     ts.createDiagnosticCollection = createDiagnosticCollection;
16622     var templateSubstitutionRegExp = /\$\{/g;
16623     function escapeTemplateSubstitution(str) {
16624         return str.replace(templateSubstitutionRegExp, "\\${");
16625     }
16626     /** @internal */
16627     function hasInvalidEscape(template) {
16628         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
16629             ? template.templateFlags
16630             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
16631     }
16632     ts.hasInvalidEscape = hasInvalidEscape;
16633     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
16634     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16635     // the language service. These characters should be escaped when printing, and if any characters are added,
16636     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
16637     // There is no reason for this other than that JSON.stringify does not handle it either.
16638     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16639     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16640     // Template strings should be preserved as much as possible
16641     var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
16642     var escapedCharsMap = new ts.Map(ts.getEntries({
16643         "\t": "\\t",
16644         "\v": "\\v",
16645         "\f": "\\f",
16646         "\b": "\\b",
16647         "\r": "\\r",
16648         "\n": "\\n",
16649         "\\": "\\\\",
16650         "\"": "\\\"",
16651         "\'": "\\\'",
16652         "\`": "\\\`",
16653         "\u2028": "\\u2028",
16654         "\u2029": "\\u2029",
16655         "\u0085": "\\u0085" // nextLine
16656     }));
16657     function encodeUtf16EscapeSequence(charCode) {
16658         var hexCharCode = charCode.toString(16).toUpperCase();
16659         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
16660         return "\\u" + paddedHexCode;
16661     }
16662     function getReplacement(c, offset, input) {
16663         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16664             var lookAhead = input.charCodeAt(offset + c.length);
16665             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
16666                 // 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)
16667                 return "\\x00";
16668             }
16669             // Otherwise, keep printing a literal \0 for the null character
16670             return "\\0";
16671         }
16672         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16673     }
16674     /**
16675      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16676      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16677      * Note that this doesn't actually wrap the input in double quotes.
16678      */
16679     function escapeString(s, quoteChar) {
16680         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16681             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16682                 doubleQuoteEscapedCharsRegExp;
16683         return s.replace(escapedCharsRegExp, getReplacement);
16684     }
16685     ts.escapeString = escapeString;
16686     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16687     function escapeNonAsciiString(s, quoteChar) {
16688         s = escapeString(s, quoteChar);
16689         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16690         // Otherwise just return the original string.
16691         return nonAsciiCharacters.test(s) ?
16692             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16693             s;
16694     }
16695     ts.escapeNonAsciiString = escapeNonAsciiString;
16696     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16697     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16698     // the language service. These characters should be escaped when printing, and if any characters are added,
16699     // the map below must be updated.
16700     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16701     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16702     var jsxEscapedCharsMap = new ts.Map(ts.getEntries({
16703         "\"": "&quot;",
16704         "\'": "&apos;"
16705     }));
16706     function encodeJsxCharacterEntity(charCode) {
16707         var hexCharCode = charCode.toString(16).toUpperCase();
16708         return "&#x" + hexCharCode + ";";
16709     }
16710     function getJsxAttributeStringReplacement(c) {
16711         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16712             return "&#0;";
16713         }
16714         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16715     }
16716     function escapeJsxAttributeString(s, quoteChar) {
16717         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16718             jsxDoubleQuoteEscapedCharsRegExp;
16719         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16720     }
16721     ts.escapeJsxAttributeString = escapeJsxAttributeString;
16722     /**
16723      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16724      *
16725      * @return non-quoted string
16726      */
16727     function stripQuotes(name) {
16728         var length = name.length;
16729         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16730             return name.substring(1, length - 1);
16731         }
16732         return name;
16733     }
16734     ts.stripQuotes = stripQuotes;
16735     function isQuoteOrBacktick(charCode) {
16736         return charCode === 39 /* singleQuote */ ||
16737             charCode === 34 /* doubleQuote */ ||
16738             charCode === 96 /* backtick */;
16739     }
16740     function isIntrinsicJsxName(name) {
16741         var ch = name.charCodeAt(0);
16742         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
16743     }
16744     ts.isIntrinsicJsxName = isIntrinsicJsxName;
16745     var indentStrings = ["", "    "];
16746     function getIndentString(level) {
16747         // prepopulate cache
16748         var singleLevel = indentStrings[1];
16749         for (var current = indentStrings.length; current <= level; current++) {
16750             indentStrings.push(indentStrings[current - 1] + singleLevel);
16751         }
16752         return indentStrings[level];
16753     }
16754     ts.getIndentString = getIndentString;
16755     function getIndentSize() {
16756         return indentStrings[1].length;
16757     }
16758     ts.getIndentSize = getIndentSize;
16759     function createTextWriter(newLine) {
16760         var output;
16761         var indent;
16762         var lineStart;
16763         var lineCount;
16764         var linePos;
16765         var hasTrailingComment = false;
16766         function updateLineCountAndPosFor(s) {
16767             var lineStartsOfS = ts.computeLineStarts(s);
16768             if (lineStartsOfS.length > 1) {
16769                 lineCount = lineCount + lineStartsOfS.length - 1;
16770                 linePos = output.length - s.length + ts.last(lineStartsOfS);
16771                 lineStart = (linePos - output.length) === 0;
16772             }
16773             else {
16774                 lineStart = false;
16775             }
16776         }
16777         function writeText(s) {
16778             if (s && s.length) {
16779                 if (lineStart) {
16780                     s = getIndentString(indent) + s;
16781                     lineStart = false;
16782                 }
16783                 output += s;
16784                 updateLineCountAndPosFor(s);
16785             }
16786         }
16787         function write(s) {
16788             if (s)
16789                 hasTrailingComment = false;
16790             writeText(s);
16791         }
16792         function writeComment(s) {
16793             if (s)
16794                 hasTrailingComment = true;
16795             writeText(s);
16796         }
16797         function reset() {
16798             output = "";
16799             indent = 0;
16800             lineStart = true;
16801             lineCount = 0;
16802             linePos = 0;
16803             hasTrailingComment = false;
16804         }
16805         function rawWrite(s) {
16806             if (s !== undefined) {
16807                 output += s;
16808                 updateLineCountAndPosFor(s);
16809                 hasTrailingComment = false;
16810             }
16811         }
16812         function writeLiteral(s) {
16813             if (s && s.length) {
16814                 write(s);
16815             }
16816         }
16817         function writeLine(force) {
16818             if (!lineStart || force) {
16819                 output += newLine;
16820                 lineCount++;
16821                 linePos = output.length;
16822                 lineStart = true;
16823                 hasTrailingComment = false;
16824             }
16825         }
16826         function getTextPosWithWriteLine() {
16827             return lineStart ? output.length : (output.length + newLine.length);
16828         }
16829         reset();
16830         return {
16831             write: write,
16832             rawWrite: rawWrite,
16833             writeLiteral: writeLiteral,
16834             writeLine: writeLine,
16835             increaseIndent: function () { indent++; },
16836             decreaseIndent: function () { indent--; },
16837             getIndent: function () { return indent; },
16838             getTextPos: function () { return output.length; },
16839             getLine: function () { return lineCount; },
16840             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
16841             getText: function () { return output; },
16842             isAtStartOfLine: function () { return lineStart; },
16843             hasTrailingComment: function () { return hasTrailingComment; },
16844             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
16845             clear: reset,
16846             reportInaccessibleThisError: ts.noop,
16847             reportPrivateInBaseOfClassExpression: ts.noop,
16848             reportInaccessibleUniqueSymbolError: ts.noop,
16849             trackSymbol: ts.noop,
16850             writeKeyword: write,
16851             writeOperator: write,
16852             writeParameter: write,
16853             writeProperty: write,
16854             writePunctuation: write,
16855             writeSpace: write,
16856             writeStringLiteral: write,
16857             writeSymbol: function (s, _) { return write(s); },
16858             writeTrailingSemicolon: write,
16859             writeComment: writeComment,
16860             getTextPosWithWriteLine: getTextPosWithWriteLine
16861         };
16862     }
16863     ts.createTextWriter = createTextWriter;
16864     function getTrailingSemicolonDeferringWriter(writer) {
16865         var pendingTrailingSemicolon = false;
16866         function commitPendingTrailingSemicolon() {
16867             if (pendingTrailingSemicolon) {
16868                 writer.writeTrailingSemicolon(";");
16869                 pendingTrailingSemicolon = false;
16870             }
16871         }
16872         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
16873                 pendingTrailingSemicolon = true;
16874             },
16875             writeLiteral: function (s) {
16876                 commitPendingTrailingSemicolon();
16877                 writer.writeLiteral(s);
16878             },
16879             writeStringLiteral: function (s) {
16880                 commitPendingTrailingSemicolon();
16881                 writer.writeStringLiteral(s);
16882             },
16883             writeSymbol: function (s, sym) {
16884                 commitPendingTrailingSemicolon();
16885                 writer.writeSymbol(s, sym);
16886             },
16887             writePunctuation: function (s) {
16888                 commitPendingTrailingSemicolon();
16889                 writer.writePunctuation(s);
16890             },
16891             writeKeyword: function (s) {
16892                 commitPendingTrailingSemicolon();
16893                 writer.writeKeyword(s);
16894             },
16895             writeOperator: function (s) {
16896                 commitPendingTrailingSemicolon();
16897                 writer.writeOperator(s);
16898             },
16899             writeParameter: function (s) {
16900                 commitPendingTrailingSemicolon();
16901                 writer.writeParameter(s);
16902             },
16903             writeSpace: function (s) {
16904                 commitPendingTrailingSemicolon();
16905                 writer.writeSpace(s);
16906             },
16907             writeProperty: function (s) {
16908                 commitPendingTrailingSemicolon();
16909                 writer.writeProperty(s);
16910             },
16911             writeComment: function (s) {
16912                 commitPendingTrailingSemicolon();
16913                 writer.writeComment(s);
16914             },
16915             writeLine: function () {
16916                 commitPendingTrailingSemicolon();
16917                 writer.writeLine();
16918             },
16919             increaseIndent: function () {
16920                 commitPendingTrailingSemicolon();
16921                 writer.increaseIndent();
16922             },
16923             decreaseIndent: function () {
16924                 commitPendingTrailingSemicolon();
16925                 writer.decreaseIndent();
16926             } });
16927     }
16928     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
16929     function hostUsesCaseSensitiveFileNames(host) {
16930         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
16931     }
16932     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
16933     function hostGetCanonicalFileName(host) {
16934         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
16935     }
16936     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
16937     function getResolvedExternalModuleName(host, file, referenceFile) {
16938         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
16939     }
16940     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
16941     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
16942         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
16943         if (!file || file.isDeclarationFile) {
16944             return undefined;
16945         }
16946         return getResolvedExternalModuleName(host, file);
16947     }
16948     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
16949     /**
16950      * Resolves a local path to a path which is absolute to the base of the emit
16951      */
16952     function getExternalModuleNameFromPath(host, fileName, referencePath) {
16953         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
16954         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
16955         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
16956         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
16957         var extensionless = removeFileExtension(relativePath);
16958         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
16959     }
16960     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
16961     function getOwnEmitOutputFilePath(fileName, host, extension) {
16962         var compilerOptions = host.getCompilerOptions();
16963         var emitOutputFilePathWithoutExtension;
16964         if (compilerOptions.outDir) {
16965             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
16966         }
16967         else {
16968             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
16969         }
16970         return emitOutputFilePathWithoutExtension + extension;
16971     }
16972     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
16973     function getDeclarationEmitOutputFilePath(fileName, host) {
16974         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16975     }
16976     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
16977     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16978         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
16979         var path = outputDir
16980             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
16981             : fileName;
16982         return removeFileExtension(path) + ".d.ts" /* Dts */;
16983     }
16984     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
16985     function outFile(options) {
16986         return options.outFile || options.out;
16987     }
16988     ts.outFile = outFile;
16989     /** Returns 'undefined' if and only if 'options.paths' is undefined. */
16990     function getPathsBasePath(options, host) {
16991         var _a, _b;
16992         if (!options.paths)
16993             return undefined;
16994         return (_a = options.baseUrl) !== null && _a !== void 0 ? _a : ts.Debug.checkDefined(options.pathsBasePath || ((_b = host.getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(host)), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'.");
16995     }
16996     ts.getPathsBasePath = getPathsBasePath;
16997     /**
16998      * Gets the source files that are expected to have an emit output.
16999      *
17000      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
17001      * transformations.
17002      *
17003      * @param host An EmitHost.
17004      * @param targetSourceFile An optional target source file to emit.
17005      */
17006     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
17007         var options = host.getCompilerOptions();
17008         if (outFile(options)) {
17009             var moduleKind = getEmitModuleKind(options);
17010             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
17011             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
17012             return ts.filter(host.getSourceFiles(), function (sourceFile) {
17013                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
17014                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
17015             });
17016         }
17017         else {
17018             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
17019             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
17020         }
17021     }
17022     ts.getSourceFilesToEmit = getSourceFilesToEmit;
17023     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
17024     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
17025         var options = host.getCompilerOptions();
17026         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
17027             !sourceFile.isDeclarationFile &&
17028             !host.isSourceFileFromExternalLibrary(sourceFile) &&
17029             !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
17030             (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
17031     }
17032     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
17033     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
17034         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
17035     }
17036     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
17037     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
17038         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
17039         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
17040         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
17041         return ts.combinePaths(newDirPath, sourceFilePath);
17042     }
17043     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
17044     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
17045         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
17046             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
17047         }, sourceFiles);
17048     }
17049     ts.writeFile = writeFile;
17050     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
17051         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
17052             var parentDirectory = ts.getDirectoryPath(directoryPath);
17053             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
17054             createDirectory(directoryPath);
17055         }
17056     }
17057     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
17058         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
17059         // and fall back to creating it if the file write fails.
17060         try {
17061             writeFile(path, data, writeByteOrderMark);
17062         }
17063         catch (_a) {
17064             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
17065             writeFile(path, data, writeByteOrderMark);
17066         }
17067     }
17068     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
17069     function getLineOfLocalPosition(sourceFile, pos) {
17070         var lineStarts = ts.getLineStarts(sourceFile);
17071         return ts.computeLineOfPosition(lineStarts, pos);
17072     }
17073     ts.getLineOfLocalPosition = getLineOfLocalPosition;
17074     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
17075         return ts.computeLineOfPosition(lineMap, pos);
17076     }
17077     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
17078     function getFirstConstructorWithBody(node) {
17079         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
17080     }
17081     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
17082     function getSetAccessorValueParameter(accessor) {
17083         if (accessor && accessor.parameters.length > 0) {
17084             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
17085             return accessor.parameters[hasThis ? 1 : 0];
17086         }
17087     }
17088     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
17089     /** Get the type annotation for the value parameter. */
17090     function getSetAccessorTypeAnnotationNode(accessor) {
17091         var parameter = getSetAccessorValueParameter(accessor);
17092         return parameter && parameter.type;
17093     }
17094     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
17095     function getThisParameter(signature) {
17096         // callback tags do not currently support this parameters
17097         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
17098             var thisParameter = signature.parameters[0];
17099             if (parameterIsThisKeyword(thisParameter)) {
17100                 return thisParameter;
17101             }
17102         }
17103     }
17104     ts.getThisParameter = getThisParameter;
17105     function parameterIsThisKeyword(parameter) {
17106         return isThisIdentifier(parameter.name);
17107     }
17108     ts.parameterIsThisKeyword = parameterIsThisKeyword;
17109     function isThisIdentifier(node) {
17110         return !!node && node.kind === 78 /* Identifier */ && identifierIsThisKeyword(node);
17111     }
17112     ts.isThisIdentifier = isThisIdentifier;
17113     function identifierIsThisKeyword(id) {
17114         return id.originalKeywordKind === 107 /* ThisKeyword */;
17115     }
17116     ts.identifierIsThisKeyword = identifierIsThisKeyword;
17117     function getAllAccessorDeclarations(declarations, accessor) {
17118         // TODO: GH#18217
17119         var firstAccessor;
17120         var secondAccessor;
17121         var getAccessor;
17122         var setAccessor;
17123         if (hasDynamicName(accessor)) {
17124             firstAccessor = accessor;
17125             if (accessor.kind === 167 /* GetAccessor */) {
17126                 getAccessor = accessor;
17127             }
17128             else if (accessor.kind === 168 /* SetAccessor */) {
17129                 setAccessor = accessor;
17130             }
17131             else {
17132                 ts.Debug.fail("Accessor has wrong kind");
17133             }
17134         }
17135         else {
17136             ts.forEach(declarations, function (member) {
17137                 if (ts.isAccessor(member)
17138                     && hasSyntacticModifier(member, 32 /* Static */) === hasSyntacticModifier(accessor, 32 /* Static */)) {
17139                     var memberName = getPropertyNameForPropertyNameNode(member.name);
17140                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
17141                     if (memberName === accessorName) {
17142                         if (!firstAccessor) {
17143                             firstAccessor = member;
17144                         }
17145                         else if (!secondAccessor) {
17146                             secondAccessor = member;
17147                         }
17148                         if (member.kind === 167 /* GetAccessor */ && !getAccessor) {
17149                             getAccessor = member;
17150                         }
17151                         if (member.kind === 168 /* SetAccessor */ && !setAccessor) {
17152                             setAccessor = member;
17153                         }
17154                     }
17155                 }
17156             });
17157         }
17158         return {
17159             firstAccessor: firstAccessor,
17160             secondAccessor: secondAccessor,
17161             getAccessor: getAccessor,
17162             setAccessor: setAccessor
17163         };
17164     }
17165     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
17166     /**
17167      * Gets the effective type annotation of a variable, parameter, or property. If the node was
17168      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
17169      * functions only the JSDoc case.
17170      */
17171     function getEffectiveTypeAnnotationNode(node) {
17172         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
17173             return undefined;
17174         var type = node.type;
17175         if (type || !isInJSFile(node))
17176             return type;
17177         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
17178     }
17179     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
17180     function getTypeAnnotationNode(node) {
17181         return node.type;
17182     }
17183     ts.getTypeAnnotationNode = getTypeAnnotationNode;
17184     /**
17185      * Gets the effective return type annotation of a signature. If the node was parsed in a
17186      * JavaScript file, gets the return type annotation from JSDoc.
17187      */
17188     function getEffectiveReturnTypeNode(node) {
17189         return ts.isJSDocSignature(node) ?
17190             node.type && node.type.typeExpression && node.type.typeExpression.type :
17191             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
17192     }
17193     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
17194     function getJSDocTypeParameterDeclarations(node) {
17195         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
17196     }
17197     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
17198     /** template tags are only available when a typedef isn't already using them */
17199     function isNonTypeAliasTemplate(tag) {
17200         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 311 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
17201     }
17202     /**
17203      * Gets the effective type annotation of the value parameter of a set accessor. If the node
17204      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
17205      */
17206     function getEffectiveSetAccessorTypeAnnotationNode(node) {
17207         var parameter = getSetAccessorValueParameter(node);
17208         return parameter && getEffectiveTypeAnnotationNode(parameter);
17209     }
17210     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
17211     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
17212         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
17213     }
17214     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
17215     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
17216         // If the leading comments start on different line than the start of node, write new line
17217         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
17218             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
17219             writer.writeLine();
17220         }
17221     }
17222     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
17223     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
17224         // If the leading comments start on different line than the start of node, write new line
17225         if (pos !== commentPos &&
17226             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
17227             writer.writeLine();
17228         }
17229     }
17230     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
17231     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
17232         if (comments && comments.length > 0) {
17233             if (leadingSeparator) {
17234                 writer.writeSpace(" ");
17235             }
17236             var emitInterveningSeparator = false;
17237             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
17238                 var comment = comments_1[_i];
17239                 if (emitInterveningSeparator) {
17240                     writer.writeSpace(" ");
17241                     emitInterveningSeparator = false;
17242                 }
17243                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
17244                 if (comment.hasTrailingNewLine) {
17245                     writer.writeLine();
17246                 }
17247                 else {
17248                     emitInterveningSeparator = true;
17249                 }
17250             }
17251             if (emitInterveningSeparator && trailingSeparator) {
17252                 writer.writeSpace(" ");
17253             }
17254         }
17255     }
17256     ts.emitComments = emitComments;
17257     /**
17258      * Detached comment is a comment at the top of file or function body that is separated from
17259      * the next statement by space.
17260      */
17261     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
17262         var leadingComments;
17263         var currentDetachedCommentInfo;
17264         if (removeComments) {
17265             // removeComments is true, only reserve pinned comment at the top of file
17266             // For example:
17267             //      /*! Pinned Comment */
17268             //
17269             //      var x = 10;
17270             if (node.pos === 0) {
17271                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
17272             }
17273         }
17274         else {
17275             // removeComments is false, just get detached as normal and bypass the process to filter comment
17276             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
17277         }
17278         if (leadingComments) {
17279             var detachedComments = [];
17280             var lastComment = void 0;
17281             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
17282                 var comment = leadingComments_1[_i];
17283                 if (lastComment) {
17284                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
17285                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
17286                     if (commentLine >= lastCommentLine + 2) {
17287                         // There was a blank line between the last comment and this comment.  This
17288                         // comment is not part of the copyright comments.  Return what we have so
17289                         // far.
17290                         break;
17291                     }
17292                 }
17293                 detachedComments.push(comment);
17294                 lastComment = comment;
17295             }
17296             if (detachedComments.length) {
17297                 // All comments look like they could have been part of the copyright header.  Make
17298                 // sure there is at least one blank line between it and the node.  If not, it's not
17299                 // a copyright header.
17300                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
17301                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
17302                 if (nodeLine >= lastCommentLine + 2) {
17303                     // Valid detachedComments
17304                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
17305                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
17306                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
17307                 }
17308             }
17309         }
17310         return currentDetachedCommentInfo;
17311         function isPinnedCommentLocal(comment) {
17312             return isPinnedComment(text, comment.pos);
17313         }
17314     }
17315     ts.emitDetachedComments = emitDetachedComments;
17316     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
17317         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
17318             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
17319             var lineCount = lineMap.length;
17320             var firstCommentLineIndent = void 0;
17321             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
17322                 var nextLineStart = (currentLine + 1) === lineCount
17323                     ? text.length + 1
17324                     : lineMap[currentLine + 1];
17325                 if (pos !== commentPos) {
17326                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
17327                     if (firstCommentLineIndent === undefined) {
17328                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
17329                     }
17330                     // These are number of spaces writer is going to write at current indent
17331                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
17332                     // Number of spaces we want to be writing
17333                     // eg: Assume writer indent
17334                     // module m {
17335                     //         /* starts at character 9 this is line 1
17336                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
17337                     //   More left indented comment */                            --2  = 8 - 8 + 2
17338                     //     class c { }
17339                     // }
17340                     // module m {
17341                     //     /* this is line 1 -- Assume current writer indent 8
17342                     //      * line                                                --3 = 8 - 4 + 5
17343                     //            More right indented comment */                  --4 = 8 - 4 + 11
17344                     //     class c { }
17345                     // }
17346                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
17347                     if (spacesToEmit > 0) {
17348                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
17349                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
17350                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
17351                         writer.rawWrite(indentSizeSpaceString);
17352                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
17353                         while (numberOfSingleSpacesToEmit) {
17354                             writer.rawWrite(" ");
17355                             numberOfSingleSpacesToEmit--;
17356                         }
17357                     }
17358                     else {
17359                         // No spaces to emit write empty string
17360                         writer.rawWrite("");
17361                     }
17362                 }
17363                 // Write the comment line text
17364                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
17365                 pos = nextLineStart;
17366             }
17367         }
17368         else {
17369             // Single line comment of style //....
17370             writer.writeComment(text.substring(commentPos, commentEnd));
17371         }
17372     }
17373     ts.writeCommentRange = writeCommentRange;
17374     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
17375         var end = Math.min(commentEnd, nextLineStart - 1);
17376         var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
17377         if (currentLineText) {
17378             // trimmed forward and ending spaces text
17379             writer.writeComment(currentLineText);
17380             if (end !== commentEnd) {
17381                 writer.writeLine();
17382             }
17383         }
17384         else {
17385             // Empty string - make sure we write empty line
17386             writer.rawWrite(newLine);
17387         }
17388     }
17389     function calculateIndent(text, pos, end) {
17390         var currentLineIndent = 0;
17391         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
17392             if (text.charCodeAt(pos) === 9 /* tab */) {
17393                 // Tabs = TabSize = indent size and go to next tabStop
17394                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
17395             }
17396             else {
17397                 // Single space
17398                 currentLineIndent++;
17399             }
17400         }
17401         return currentLineIndent;
17402     }
17403     function hasEffectiveModifiers(node) {
17404         return getEffectiveModifierFlags(node) !== 0 /* None */;
17405     }
17406     ts.hasEffectiveModifiers = hasEffectiveModifiers;
17407     function hasSyntacticModifiers(node) {
17408         return getSyntacticModifierFlags(node) !== 0 /* None */;
17409     }
17410     ts.hasSyntacticModifiers = hasSyntacticModifiers;
17411     function hasEffectiveModifier(node, flags) {
17412         return !!getSelectedEffectiveModifierFlags(node, flags);
17413     }
17414     ts.hasEffectiveModifier = hasEffectiveModifier;
17415     function hasSyntacticModifier(node, flags) {
17416         return !!getSelectedSyntacticModifierFlags(node, flags);
17417     }
17418     ts.hasSyntacticModifier = hasSyntacticModifier;
17419     function hasStaticModifier(node) {
17420         return hasSyntacticModifier(node, 32 /* Static */);
17421     }
17422     ts.hasStaticModifier = hasStaticModifier;
17423     function hasEffectiveReadonlyModifier(node) {
17424         return hasEffectiveModifier(node, 64 /* Readonly */);
17425     }
17426     ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier;
17427     function getSelectedEffectiveModifierFlags(node, flags) {
17428         return getEffectiveModifierFlags(node) & flags;
17429     }
17430     ts.getSelectedEffectiveModifierFlags = getSelectedEffectiveModifierFlags;
17431     function getSelectedSyntacticModifierFlags(node, flags) {
17432         return getSyntacticModifierFlags(node) & flags;
17433     }
17434     ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags;
17435     function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) {
17436         if (node.kind >= 0 /* FirstToken */ && node.kind <= 156 /* LastToken */) {
17437             return 0 /* None */;
17438         }
17439         if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) {
17440             node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */;
17441         }
17442         if (includeJSDoc && !(node.modifierFlagsCache & 4096 /* HasComputedJSDocModifiers */) && (alwaysIncludeJSDoc || isInJSFile(node)) && node.parent) {
17443             node.modifierFlagsCache |= getJSDocModifierFlagsNoCache(node) | 4096 /* HasComputedJSDocModifiers */;
17444         }
17445         return node.modifierFlagsCache & ~(536870912 /* HasComputedFlags */ | 4096 /* HasComputedJSDocModifiers */);
17446     }
17447     /**
17448      * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifiers will be cached on the node to improve performance.
17449      *
17450      * NOTE: This function may use `parent` pointers.
17451      */
17452     function getEffectiveModifierFlags(node) {
17453         return getModifierFlagsWorker(node, /*includeJSDoc*/ true);
17454     }
17455     ts.getEffectiveModifierFlags = getEffectiveModifierFlags;
17456     function getEffectiveModifierFlagsAlwaysIncludeJSDoc(node) {
17457         return getModifierFlagsWorker(node, /*includeJSDOc*/ true, /*alwaysIncludeJSDOc*/ true);
17458     }
17459     ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc = getEffectiveModifierFlagsAlwaysIncludeJSDoc;
17460     /**
17461      * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifiers will be cached on the node to improve performance.
17462      *
17463      * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
17464      */
17465     function getSyntacticModifierFlags(node) {
17466         return getModifierFlagsWorker(node, /*includeJSDoc*/ false);
17467     }
17468     ts.getSyntacticModifierFlags = getSyntacticModifierFlags;
17469     function getJSDocModifierFlagsNoCache(node) {
17470         var flags = 0 /* None */;
17471         if (!!node.parent && !ts.isParameter(node)) {
17472             if (isInJSFile(node)) {
17473                 if (ts.getJSDocPublicTagNoCache(node))
17474                     flags |= 4 /* Public */;
17475                 if (ts.getJSDocPrivateTagNoCache(node))
17476                     flags |= 8 /* Private */;
17477                 if (ts.getJSDocProtectedTagNoCache(node))
17478                     flags |= 16 /* Protected */;
17479                 if (ts.getJSDocReadonlyTagNoCache(node))
17480                     flags |= 64 /* Readonly */;
17481             }
17482             if (ts.getJSDocDeprecatedTagNoCache(node))
17483                 flags |= 8192 /* Deprecated */;
17484         }
17485         return flags;
17486     }
17487     /**
17488      * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifier flags cache on the node is ignored.
17489      *
17490      * NOTE: This function may use `parent` pointers.
17491      */
17492     function getEffectiveModifierFlagsNoCache(node) {
17493         return getSyntacticModifierFlagsNoCache(node) | getJSDocModifierFlagsNoCache(node);
17494     }
17495     ts.getEffectiveModifierFlagsNoCache = getEffectiveModifierFlagsNoCache;
17496     /**
17497      * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifier flags cache on the node is ignored.
17498      *
17499      * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
17500      */
17501     function getSyntacticModifierFlagsNoCache(node) {
17502         var flags = modifiersToFlags(node.modifiers);
17503         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 78 /* Identifier */ && node.isInJSDocNamespace)) {
17504             flags |= 1 /* Export */;
17505         }
17506         return flags;
17507     }
17508     ts.getSyntacticModifierFlagsNoCache = getSyntacticModifierFlagsNoCache;
17509     function modifiersToFlags(modifiers) {
17510         var flags = 0 /* None */;
17511         if (modifiers) {
17512             for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
17513                 var modifier = modifiers_1[_i];
17514                 flags |= modifierToFlag(modifier.kind);
17515             }
17516         }
17517         return flags;
17518     }
17519     ts.modifiersToFlags = modifiersToFlags;
17520     function modifierToFlag(token) {
17521         switch (token) {
17522             case 123 /* StaticKeyword */: return 32 /* Static */;
17523             case 122 /* PublicKeyword */: return 4 /* Public */;
17524             case 121 /* ProtectedKeyword */: return 16 /* Protected */;
17525             case 120 /* PrivateKeyword */: return 8 /* Private */;
17526             case 125 /* AbstractKeyword */: return 128 /* Abstract */;
17527             case 92 /* ExportKeyword */: return 1 /* Export */;
17528             case 133 /* DeclareKeyword */: return 2 /* Ambient */;
17529             case 84 /* ConstKeyword */: return 2048 /* Const */;
17530             case 87 /* DefaultKeyword */: return 512 /* Default */;
17531             case 129 /* AsyncKeyword */: return 256 /* Async */;
17532             case 142 /* ReadonlyKeyword */: return 64 /* Readonly */;
17533         }
17534         return 0 /* None */;
17535     }
17536     ts.modifierToFlag = modifierToFlag;
17537     function isLogicalOperator(token) {
17538         return token === 56 /* BarBarToken */
17539             || token === 55 /* AmpersandAmpersandToken */
17540             || token === 53 /* ExclamationToken */;
17541     }
17542     ts.isLogicalOperator = isLogicalOperator;
17543     function isLogicalOrCoalescingAssignmentOperator(token) {
17544         return token === 74 /* BarBarEqualsToken */
17545             || token === 75 /* AmpersandAmpersandEqualsToken */
17546             || token === 76 /* QuestionQuestionEqualsToken */;
17547     }
17548     ts.isLogicalOrCoalescingAssignmentOperator = isLogicalOrCoalescingAssignmentOperator;
17549     function isLogicalOrCoalescingAssignmentExpression(expr) {
17550         return isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind);
17551     }
17552     ts.isLogicalOrCoalescingAssignmentExpression = isLogicalOrCoalescingAssignmentExpression;
17553     function isAssignmentOperator(token) {
17554         return token >= 62 /* FirstAssignment */ && token <= 77 /* LastAssignment */;
17555     }
17556     ts.isAssignmentOperator = isAssignmentOperator;
17557     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
17558     function tryGetClassExtendingExpressionWithTypeArguments(node) {
17559         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
17560         return cls && !cls.isImplements ? cls.class : undefined;
17561     }
17562     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
17563     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
17564         return ts.isExpressionWithTypeArguments(node)
17565             && ts.isHeritageClause(node.parent)
17566             && ts.isClassLike(node.parent.parent)
17567             ? { class: node.parent.parent, isImplements: node.parent.token === 116 /* ImplementsKeyword */ }
17568             : undefined;
17569     }
17570     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
17571     function isAssignmentExpression(node, excludeCompoundAssignment) {
17572         return ts.isBinaryExpression(node)
17573             && (excludeCompoundAssignment
17574                 ? node.operatorToken.kind === 62 /* EqualsToken */
17575                 : isAssignmentOperator(node.operatorToken.kind))
17576             && ts.isLeftHandSideExpression(node.left);
17577     }
17578     ts.isAssignmentExpression = isAssignmentExpression;
17579     function isDestructuringAssignment(node) {
17580         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
17581             var kind = node.left.kind;
17582             return kind === 200 /* ObjectLiteralExpression */
17583                 || kind === 199 /* ArrayLiteralExpression */;
17584         }
17585         return false;
17586     }
17587     ts.isDestructuringAssignment = isDestructuringAssignment;
17588     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
17589         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
17590     }
17591     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
17592     function isEntityNameExpression(node) {
17593         return node.kind === 78 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
17594     }
17595     ts.isEntityNameExpression = isEntityNameExpression;
17596     function getFirstIdentifier(node) {
17597         switch (node.kind) {
17598             case 78 /* Identifier */:
17599                 return node;
17600             case 157 /* QualifiedName */:
17601                 do {
17602                     node = node.left;
17603                 } while (node.kind !== 78 /* Identifier */);
17604                 return node;
17605             case 201 /* PropertyAccessExpression */:
17606                 do {
17607                     node = node.expression;
17608                 } while (node.kind !== 78 /* Identifier */);
17609                 return node;
17610         }
17611     }
17612     ts.getFirstIdentifier = getFirstIdentifier;
17613     function isDottedName(node) {
17614         return node.kind === 78 /* Identifier */ || node.kind === 107 /* ThisKeyword */ || node.kind === 105 /* SuperKeyword */ ||
17615             node.kind === 201 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
17616             node.kind === 207 /* ParenthesizedExpression */ && isDottedName(node.expression);
17617     }
17618     ts.isDottedName = isDottedName;
17619     function isPropertyAccessEntityNameExpression(node) {
17620         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
17621     }
17622     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
17623     function tryGetPropertyAccessOrIdentifierToString(expr) {
17624         if (ts.isPropertyAccessExpression(expr)) {
17625             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
17626             if (baseStr !== undefined) {
17627                 return baseStr + "." + entityNameToString(expr.name);
17628             }
17629         }
17630         else if (ts.isIdentifier(expr)) {
17631             return ts.unescapeLeadingUnderscores(expr.escapedText);
17632         }
17633         return undefined;
17634     }
17635     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
17636     function isPrototypeAccess(node) {
17637         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
17638     }
17639     ts.isPrototypeAccess = isPrototypeAccess;
17640     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
17641         return (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) ||
17642             (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node);
17643     }
17644     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
17645     function isEmptyObjectLiteral(expression) {
17646         return expression.kind === 200 /* ObjectLiteralExpression */ &&
17647             expression.properties.length === 0;
17648     }
17649     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
17650     function isEmptyArrayLiteral(expression) {
17651         return expression.kind === 199 /* ArrayLiteralExpression */ &&
17652             expression.elements.length === 0;
17653     }
17654     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
17655     function getLocalSymbolForExportDefault(symbol) {
17656         if (!isExportDefaultSymbol(symbol))
17657             return undefined;
17658         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
17659             var decl = _a[_i];
17660             if (decl.localSymbol)
17661                 return decl.localSymbol;
17662         }
17663         return undefined;
17664     }
17665     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
17666     function isExportDefaultSymbol(symbol) {
17667         return symbol && ts.length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 512 /* Default */);
17668     }
17669     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
17670     function tryExtractTSExtension(fileName) {
17671         return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
17672     }
17673     ts.tryExtractTSExtension = tryExtractTSExtension;
17674     /**
17675      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
17676      * representing the UTF-8 encoding of the character, and return the expanded char code list.
17677      */
17678     function getExpandedCharCodes(input) {
17679         var output = [];
17680         var length = input.length;
17681         for (var i = 0; i < length; i++) {
17682             var charCode = input.charCodeAt(i);
17683             // handle utf8
17684             if (charCode < 0x80) {
17685                 output.push(charCode);
17686             }
17687             else if (charCode < 0x800) {
17688                 output.push((charCode >> 6) | 192);
17689                 output.push((charCode & 63) | 128);
17690             }
17691             else if (charCode < 0x10000) {
17692                 output.push((charCode >> 12) | 224);
17693                 output.push(((charCode >> 6) & 63) | 128);
17694                 output.push((charCode & 63) | 128);
17695             }
17696             else if (charCode < 0x20000) {
17697                 output.push((charCode >> 18) | 240);
17698                 output.push(((charCode >> 12) & 63) | 128);
17699                 output.push(((charCode >> 6) & 63) | 128);
17700                 output.push((charCode & 63) | 128);
17701             }
17702             else {
17703                 ts.Debug.assert(false, "Unexpected code point");
17704             }
17705         }
17706         return output;
17707     }
17708     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17709     /**
17710      * Converts a string to a base-64 encoded ASCII string.
17711      */
17712     function convertToBase64(input) {
17713         var result = "";
17714         var charCodes = getExpandedCharCodes(input);
17715         var i = 0;
17716         var length = charCodes.length;
17717         var byte1, byte2, byte3, byte4;
17718         while (i < length) {
17719             // Convert every 6-bits in the input 3 character points
17720             // into a base64 digit
17721             byte1 = charCodes[i] >> 2;
17722             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17723             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17724             byte4 = charCodes[i + 2] & 63;
17725             // We are out of characters in the input, set the extra
17726             // digits to 64 (padding character).
17727             if (i + 1 >= length) {
17728                 byte3 = byte4 = 64;
17729             }
17730             else if (i + 2 >= length) {
17731                 byte4 = 64;
17732             }
17733             // Write to the output
17734             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17735             i += 3;
17736         }
17737         return result;
17738     }
17739     ts.convertToBase64 = convertToBase64;
17740     function getStringFromExpandedCharCodes(codes) {
17741         var output = "";
17742         var i = 0;
17743         var length = codes.length;
17744         while (i < length) {
17745             var charCode = codes[i];
17746             if (charCode < 0x80) {
17747                 output += String.fromCharCode(charCode);
17748                 i++;
17749             }
17750             else if ((charCode & 192) === 192) {
17751                 var value = charCode & 63;
17752                 i++;
17753                 var nextCode = codes[i];
17754                 while ((nextCode & 192) === 128) {
17755                     value = (value << 6) | (nextCode & 63);
17756                     i++;
17757                     nextCode = codes[i];
17758                 }
17759                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
17760                 output += String.fromCharCode(value);
17761             }
17762             else {
17763                 // We don't want to kill the process when decoding fails (due to a following char byte not
17764                 // following a leading char), so we just print the (bad) value
17765                 output += String.fromCharCode(charCode);
17766                 i++;
17767             }
17768         }
17769         return output;
17770     }
17771     function base64encode(host, input) {
17772         if (host && host.base64encode) {
17773             return host.base64encode(input);
17774         }
17775         return convertToBase64(input);
17776     }
17777     ts.base64encode = base64encode;
17778     function base64decode(host, input) {
17779         if (host && host.base64decode) {
17780             return host.base64decode(input);
17781         }
17782         var length = input.length;
17783         var expandedCharCodes = [];
17784         var i = 0;
17785         while (i < length) {
17786             // Stop decoding once padding characters are present
17787             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
17788                 break;
17789             }
17790             // convert 4 input digits into three characters, ignoring padding characters at the end
17791             var ch1 = base64Digits.indexOf(input[i]);
17792             var ch2 = base64Digits.indexOf(input[i + 1]);
17793             var ch3 = base64Digits.indexOf(input[i + 2]);
17794             var ch4 = base64Digits.indexOf(input[i + 3]);
17795             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
17796             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
17797             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
17798             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
17799                 expandedCharCodes.push(code1);
17800             }
17801             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
17802                 expandedCharCodes.push(code1, code2);
17803             }
17804             else {
17805                 expandedCharCodes.push(code1, code2, code3);
17806             }
17807             i += 4;
17808         }
17809         return getStringFromExpandedCharCodes(expandedCharCodes);
17810     }
17811     ts.base64decode = base64decode;
17812     function readJson(path, host) {
17813         try {
17814             var jsonText = host.readFile(path);
17815             if (!jsonText)
17816                 return {};
17817             var result = ts.parseConfigFileTextToJson(path, jsonText);
17818             if (result.error) {
17819                 return {};
17820             }
17821             return result.config;
17822         }
17823         catch (e) {
17824             // gracefully handle if readFile fails or returns not JSON
17825             return {};
17826         }
17827     }
17828     ts.readJson = readJson;
17829     function directoryProbablyExists(directoryName, host) {
17830         // if host does not support 'directoryExists' assume that directory will exist
17831         return !host.directoryExists || host.directoryExists(directoryName);
17832     }
17833     ts.directoryProbablyExists = directoryProbablyExists;
17834     var carriageReturnLineFeed = "\r\n";
17835     var lineFeed = "\n";
17836     function getNewLineCharacter(options, getNewLine) {
17837         switch (options.newLine) {
17838             case 0 /* CarriageReturnLineFeed */:
17839                 return carriageReturnLineFeed;
17840             case 1 /* LineFeed */:
17841                 return lineFeed;
17842         }
17843         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
17844     }
17845     ts.getNewLineCharacter = getNewLineCharacter;
17846     /**
17847      * Creates a new TextRange from the provided pos and end.
17848      *
17849      * @param pos The start position.
17850      * @param end The end position.
17851      */
17852     function createRange(pos, end) {
17853         if (end === void 0) { end = pos; }
17854         ts.Debug.assert(end >= pos || end === -1);
17855         return { pos: pos, end: end };
17856     }
17857     ts.createRange = createRange;
17858     /**
17859      * Creates a new TextRange from a provided range with a new end position.
17860      *
17861      * @param range A TextRange.
17862      * @param end The new end position.
17863      */
17864     function moveRangeEnd(range, end) {
17865         return createRange(range.pos, end);
17866     }
17867     ts.moveRangeEnd = moveRangeEnd;
17868     /**
17869      * Creates a new TextRange from a provided range with a new start position.
17870      *
17871      * @param range A TextRange.
17872      * @param pos The new Start position.
17873      */
17874     function moveRangePos(range, pos) {
17875         return createRange(pos, range.end);
17876     }
17877     ts.moveRangePos = moveRangePos;
17878     /**
17879      * Moves the start position of a range past any decorators.
17880      */
17881     function moveRangePastDecorators(node) {
17882         return node.decorators && node.decorators.length > 0
17883             ? moveRangePos(node, node.decorators.end)
17884             : node;
17885     }
17886     ts.moveRangePastDecorators = moveRangePastDecorators;
17887     /**
17888      * Moves the start position of a range past any decorators or modifiers.
17889      */
17890     function moveRangePastModifiers(node) {
17891         return node.modifiers && node.modifiers.length > 0
17892             ? moveRangePos(node, node.modifiers.end)
17893             : moveRangePastDecorators(node);
17894     }
17895     ts.moveRangePastModifiers = moveRangePastModifiers;
17896     /**
17897      * Determines whether a TextRange has the same start and end positions.
17898      *
17899      * @param range A TextRange.
17900      */
17901     function isCollapsedRange(range) {
17902         return range.pos === range.end;
17903     }
17904     ts.isCollapsedRange = isCollapsedRange;
17905     /**
17906      * Creates a new TextRange for a token at the provides start position.
17907      *
17908      * @param pos The start position.
17909      * @param token The token.
17910      */
17911     function createTokenRange(pos, token) {
17912         return createRange(pos, pos + ts.tokenToString(token).length);
17913     }
17914     ts.createTokenRange = createTokenRange;
17915     function rangeIsOnSingleLine(range, sourceFile) {
17916         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
17917     }
17918     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
17919     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
17920         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17921     }
17922     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
17923     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
17924         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
17925     }
17926     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
17927     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
17928         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
17929     }
17930     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
17931     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
17932         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17933     }
17934     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
17935     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
17936         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
17937         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
17938     }
17939     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
17940     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
17941         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
17942     }
17943     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
17944     function isNodeArrayMultiLine(list, sourceFile) {
17945         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
17946     }
17947     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
17948     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
17949         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
17950     }
17951     ts.positionsAreOnSameLine = positionsAreOnSameLine;
17952     function getStartPositionOfRange(range, sourceFile, includeComments) {
17953         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
17954     }
17955     ts.getStartPositionOfRange = getStartPositionOfRange;
17956     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17957         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17958         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
17959         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
17960     }
17961     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
17962     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17963         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17964         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
17965     }
17966     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
17967     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
17968         if (stopPos === void 0) { stopPos = 0; }
17969         while (pos-- > stopPos) {
17970             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
17971                 return pos;
17972             }
17973         }
17974     }
17975     /**
17976      * Determines whether a name was originally the declaration name of an enum or namespace
17977      * declaration.
17978      */
17979     function isDeclarationNameOfEnumOrNamespace(node) {
17980         var parseNode = ts.getParseTreeNode(node);
17981         if (parseNode) {
17982             switch (parseNode.parent.kind) {
17983                 case 255 /* EnumDeclaration */:
17984                 case 256 /* ModuleDeclaration */:
17985                     return parseNode === parseNode.parent.name;
17986             }
17987         }
17988         return false;
17989     }
17990     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
17991     function getInitializedVariables(node) {
17992         return ts.filter(node.declarations, isInitializedVariable);
17993     }
17994     ts.getInitializedVariables = getInitializedVariables;
17995     function isInitializedVariable(node) {
17996         return node.initializer !== undefined;
17997     }
17998     function isWatchSet(options) {
17999         // Firefox has Object.prototype.watch
18000         return options.watch && options.hasOwnProperty("watch");
18001     }
18002     ts.isWatchSet = isWatchSet;
18003     function closeFileWatcher(watcher) {
18004         watcher.close();
18005     }
18006     ts.closeFileWatcher = closeFileWatcher;
18007     function getCheckFlags(symbol) {
18008         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
18009     }
18010     ts.getCheckFlags = getCheckFlags;
18011     function getDeclarationModifierFlagsFromSymbol(s) {
18012         if (s.valueDeclaration) {
18013             var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
18014             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
18015         }
18016         if (getCheckFlags(s) & 6 /* Synthetic */) {
18017             var checkFlags = s.checkFlags;
18018             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
18019                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
18020                     16 /* Protected */;
18021             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
18022             return accessModifier | staticModifier;
18023         }
18024         if (s.flags & 4194304 /* Prototype */) {
18025             return 4 /* Public */ | 32 /* Static */;
18026         }
18027         return 0;
18028     }
18029     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
18030     function skipAlias(symbol, checker) {
18031         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
18032     }
18033     ts.skipAlias = skipAlias;
18034     /** See comment on `declareModuleMember` in `binder.ts`. */
18035     function getCombinedLocalAndExportSymbolFlags(symbol) {
18036         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
18037     }
18038     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
18039     function isWriteOnlyAccess(node) {
18040         return accessKind(node) === 1 /* Write */;
18041     }
18042     ts.isWriteOnlyAccess = isWriteOnlyAccess;
18043     function isWriteAccess(node) {
18044         return accessKind(node) !== 0 /* Read */;
18045     }
18046     ts.isWriteAccess = isWriteAccess;
18047     var AccessKind;
18048     (function (AccessKind) {
18049         /** Only reads from a variable. */
18050         AccessKind[AccessKind["Read"] = 0] = "Read";
18051         /** Only writes to a variable without using the result. E.g.: `x++;`. */
18052         AccessKind[AccessKind["Write"] = 1] = "Write";
18053         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
18054         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
18055     })(AccessKind || (AccessKind = {}));
18056     function accessKind(node) {
18057         var parent = node.parent;
18058         if (!parent)
18059             return 0 /* Read */;
18060         switch (parent.kind) {
18061             case 207 /* ParenthesizedExpression */:
18062                 return accessKind(parent);
18063             case 215 /* PostfixUnaryExpression */:
18064             case 214 /* PrefixUnaryExpression */:
18065                 var operator = parent.operator;
18066                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
18067             case 216 /* BinaryExpression */:
18068                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
18069                 return left === node && isAssignmentOperator(operatorToken.kind) ?
18070                     operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
18071                     : 0 /* Read */;
18072             case 201 /* PropertyAccessExpression */:
18073                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
18074             case 288 /* PropertyAssignment */: {
18075                 var parentAccess = accessKind(parent.parent);
18076                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
18077                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
18078             }
18079             case 289 /* ShorthandPropertyAssignment */:
18080                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
18081                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
18082             case 199 /* ArrayLiteralExpression */:
18083                 return accessKind(parent);
18084             default:
18085                 return 0 /* Read */;
18086         }
18087         function writeOrReadWrite() {
18088             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
18089             return parent.parent && skipParenthesesUp(parent.parent).kind === 233 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
18090         }
18091     }
18092     function reverseAccessKind(a) {
18093         switch (a) {
18094             case 0 /* Read */:
18095                 return 1 /* Write */;
18096             case 1 /* Write */:
18097                 return 0 /* Read */;
18098             case 2 /* ReadWrite */:
18099                 return 2 /* ReadWrite */;
18100             default:
18101                 return ts.Debug.assertNever(a);
18102         }
18103     }
18104     function compareDataObjects(dst, src) {
18105         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
18106             return false;
18107         }
18108         for (var e in dst) {
18109             if (typeof dst[e] === "object") {
18110                 if (!compareDataObjects(dst[e], src[e])) {
18111                     return false;
18112                 }
18113             }
18114             else if (typeof dst[e] !== "function") {
18115                 if (dst[e] !== src[e]) {
18116                     return false;
18117                 }
18118             }
18119         }
18120         return true;
18121     }
18122     ts.compareDataObjects = compareDataObjects;
18123     /**
18124      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
18125      */
18126     function clearMap(map, onDeleteValue) {
18127         // Remove all
18128         map.forEach(onDeleteValue);
18129         map.clear();
18130     }
18131     ts.clearMap = clearMap;
18132     /**
18133      * Mutates the map with newMap such that keys in map will be same as newMap.
18134      */
18135     function mutateMapSkippingNewValues(map, newMap, options) {
18136         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
18137         // Needs update
18138         map.forEach(function (existingValue, key) {
18139             var valueInNewMap = newMap.get(key);
18140             // Not present any more in new map, remove it
18141             if (valueInNewMap === undefined) {
18142                 map.delete(key);
18143                 onDeleteValue(existingValue, key);
18144             }
18145             // If present notify about existing values
18146             else if (onExistingValue) {
18147                 onExistingValue(existingValue, valueInNewMap, key);
18148             }
18149         });
18150     }
18151     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
18152     /**
18153      * Mutates the map with newMap such that keys in map will be same as newMap.
18154      */
18155     function mutateMap(map, newMap, options) {
18156         // Needs update
18157         mutateMapSkippingNewValues(map, newMap, options);
18158         var createNewValue = options.createNewValue;
18159         // Add new values that are not already present
18160         newMap.forEach(function (valueInNewMap, key) {
18161             if (!map.has(key)) {
18162                 // New values
18163                 map.set(key, createNewValue(key, valueInNewMap));
18164             }
18165         });
18166     }
18167     ts.mutateMap = mutateMap;
18168     // Return true if the given type is the constructor type for an abstract class
18169     function isAbstractConstructorType(type) {
18170         return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
18171     }
18172     ts.isAbstractConstructorType = isAbstractConstructorType;
18173     function isAbstractConstructorSymbol(symbol) {
18174         if (symbol.flags & 32 /* Class */) {
18175             var declaration = getClassLikeDeclarationOfSymbol(symbol);
18176             return !!declaration && hasSyntacticModifier(declaration, 128 /* Abstract */);
18177         }
18178         return false;
18179     }
18180     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
18181     function getClassLikeDeclarationOfSymbol(symbol) {
18182         return ts.find(symbol.declarations, ts.isClassLike);
18183     }
18184     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
18185     function getObjectFlags(type) {
18186         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
18187     }
18188     ts.getObjectFlags = getObjectFlags;
18189     function typeHasCallOrConstructSignatures(type, checker) {
18190         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
18191     }
18192     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
18193     function forSomeAncestorDirectory(directory, callback) {
18194         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
18195     }
18196     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
18197     function isUMDExportSymbol(symbol) {
18198         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
18199     }
18200     ts.isUMDExportSymbol = isUMDExportSymbol;
18201     function showModuleSpecifier(_a) {
18202         var moduleSpecifier = _a.moduleSpecifier;
18203         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
18204     }
18205     ts.showModuleSpecifier = showModuleSpecifier;
18206     function getLastChild(node) {
18207         var lastChild;
18208         ts.forEachChild(node, function (child) {
18209             if (nodeIsPresent(child))
18210                 lastChild = child;
18211         }, function (children) {
18212             // As an optimization, jump straight to the end of the list.
18213             for (var i = children.length - 1; i >= 0; i--) {
18214                 if (nodeIsPresent(children[i])) {
18215                     lastChild = children[i];
18216                     break;
18217                 }
18218             }
18219         });
18220         return lastChild;
18221     }
18222     ts.getLastChild = getLastChild;
18223     function addToSeen(seen, key, value) {
18224         if (value === void 0) { value = true; }
18225         key = String(key);
18226         if (seen.has(key)) {
18227             return false;
18228         }
18229         seen.set(key, value);
18230         return true;
18231     }
18232     ts.addToSeen = addToSeen;
18233     function isObjectTypeDeclaration(node) {
18234         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
18235     }
18236     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
18237     function isTypeNodeKind(kind) {
18238         return (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */)
18239             || kind === 128 /* AnyKeyword */
18240             || kind === 152 /* UnknownKeyword */
18241             || kind === 144 /* NumberKeyword */
18242             || kind === 155 /* BigIntKeyword */
18243             || kind === 145 /* ObjectKeyword */
18244             || kind === 131 /* BooleanKeyword */
18245             || kind === 147 /* StringKeyword */
18246             || kind === 148 /* SymbolKeyword */
18247             || kind === 113 /* VoidKeyword */
18248             || kind === 150 /* UndefinedKeyword */
18249             || kind === 141 /* NeverKeyword */
18250             || kind === 223 /* ExpressionWithTypeArguments */
18251             || kind === 303 /* JSDocAllType */
18252             || kind === 304 /* JSDocUnknownType */
18253             || kind === 305 /* JSDocNullableType */
18254             || kind === 306 /* JSDocNonNullableType */
18255             || kind === 307 /* JSDocOptionalType */
18256             || kind === 308 /* JSDocFunctionType */
18257             || kind === 309 /* JSDocVariadicType */;
18258     }
18259     ts.isTypeNodeKind = isTypeNodeKind;
18260     function isAccessExpression(node) {
18261         return node.kind === 201 /* PropertyAccessExpression */ || node.kind === 202 /* ElementAccessExpression */;
18262     }
18263     ts.isAccessExpression = isAccessExpression;
18264     function getNameOfAccessExpression(node) {
18265         if (node.kind === 201 /* PropertyAccessExpression */) {
18266             return node.name;
18267         }
18268         ts.Debug.assert(node.kind === 202 /* ElementAccessExpression */);
18269         return node.argumentExpression;
18270     }
18271     ts.getNameOfAccessExpression = getNameOfAccessExpression;
18272     function isBundleFileTextLike(section) {
18273         switch (section.kind) {
18274             case "text" /* Text */:
18275             case "internal" /* Internal */:
18276                 return true;
18277             default:
18278                 return false;
18279         }
18280     }
18281     ts.isBundleFileTextLike = isBundleFileTextLike;
18282     function isNamedImportsOrExports(node) {
18283         return node.kind === 264 /* NamedImports */ || node.kind === 268 /* NamedExports */;
18284     }
18285     ts.isNamedImportsOrExports = isNamedImportsOrExports;
18286     function getLeftmostAccessExpression(expr) {
18287         while (isAccessExpression(expr)) {
18288             expr = expr.expression;
18289         }
18290         return expr;
18291     }
18292     ts.getLeftmostAccessExpression = getLeftmostAccessExpression;
18293     function getLeftmostExpression(node, stopAtCallExpressions) {
18294         while (true) {
18295             switch (node.kind) {
18296                 case 215 /* PostfixUnaryExpression */:
18297                     node = node.operand;
18298                     continue;
18299                 case 216 /* BinaryExpression */:
18300                     node = node.left;
18301                     continue;
18302                 case 217 /* ConditionalExpression */:
18303                     node = node.condition;
18304                     continue;
18305                 case 205 /* TaggedTemplateExpression */:
18306                     node = node.tag;
18307                     continue;
18308                 case 203 /* CallExpression */:
18309                     if (stopAtCallExpressions) {
18310                         return node;
18311                     }
18312                 // falls through
18313                 case 224 /* AsExpression */:
18314                 case 202 /* ElementAccessExpression */:
18315                 case 201 /* PropertyAccessExpression */:
18316                 case 225 /* NonNullExpression */:
18317                 case 336 /* PartiallyEmittedExpression */:
18318                     node = node.expression;
18319                     continue;
18320             }
18321             return node;
18322         }
18323     }
18324     ts.getLeftmostExpression = getLeftmostExpression;
18325     function Symbol(flags, name) {
18326         this.flags = flags;
18327         this.escapedName = name;
18328         this.declarations = undefined;
18329         this.valueDeclaration = undefined;
18330         this.id = undefined;
18331         this.mergeId = undefined;
18332         this.parent = undefined;
18333     }
18334     function Type(checker, flags) {
18335         this.flags = flags;
18336         if (ts.Debug.isDebugging || ts.tracing.isTracing()) {
18337             this.checker = checker;
18338         }
18339     }
18340     function Signature(checker, flags) {
18341         this.flags = flags;
18342         if (ts.Debug.isDebugging) {
18343             this.checker = checker;
18344         }
18345     }
18346     function Node(kind, pos, end) {
18347         this.pos = pos;
18348         this.end = end;
18349         this.kind = kind;
18350         this.id = 0;
18351         this.flags = 0 /* None */;
18352         this.modifierFlagsCache = 0 /* None */;
18353         this.transformFlags = 0 /* None */;
18354         this.parent = undefined;
18355         this.original = undefined;
18356     }
18357     function Token(kind, pos, end) {
18358         this.pos = pos;
18359         this.end = end;
18360         this.kind = kind;
18361         this.id = 0;
18362         this.flags = 0 /* None */;
18363         this.transformFlags = 0 /* None */;
18364         this.parent = undefined;
18365     }
18366     function Identifier(kind, pos, end) {
18367         this.pos = pos;
18368         this.end = end;
18369         this.kind = kind;
18370         this.id = 0;
18371         this.flags = 0 /* None */;
18372         this.transformFlags = 0 /* None */;
18373         this.parent = undefined;
18374         this.original = undefined;
18375         this.flowNode = undefined;
18376     }
18377     function SourceMapSource(fileName, text, skipTrivia) {
18378         this.fileName = fileName;
18379         this.text = text;
18380         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
18381     }
18382     // eslint-disable-next-line prefer-const
18383     ts.objectAllocator = {
18384         getNodeConstructor: function () { return Node; },
18385         getTokenConstructor: function () { return Token; },
18386         getIdentifierConstructor: function () { return Identifier; },
18387         getPrivateIdentifierConstructor: function () { return Node; },
18388         getSourceFileConstructor: function () { return Node; },
18389         getSymbolConstructor: function () { return Symbol; },
18390         getTypeConstructor: function () { return Type; },
18391         getSignatureConstructor: function () { return Signature; },
18392         getSourceMapSourceConstructor: function () { return SourceMapSource; },
18393     };
18394     function setObjectAllocator(alloc) {
18395         ts.objectAllocator = alloc;
18396     }
18397     ts.setObjectAllocator = setObjectAllocator;
18398     function formatStringFromArgs(text, args, baseIndex) {
18399         if (baseIndex === void 0) { baseIndex = 0; }
18400         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
18401     }
18402     ts.formatStringFromArgs = formatStringFromArgs;
18403     /* @internal */
18404     function setLocalizedDiagnosticMessages(messages) {
18405         ts.localizedDiagnosticMessages = messages;
18406     }
18407     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
18408     function getLocaleSpecificMessage(message) {
18409         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
18410     }
18411     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
18412     function createDetachedDiagnostic(fileName, start, length, message) {
18413         ts.Debug.assertGreaterThanOrEqual(start, 0);
18414         ts.Debug.assertGreaterThanOrEqual(length, 0);
18415         var text = getLocaleSpecificMessage(message);
18416         if (arguments.length > 4) {
18417             text = formatStringFromArgs(text, arguments, 4);
18418         }
18419         return {
18420             file: undefined,
18421             start: start,
18422             length: length,
18423             messageText: text,
18424             category: message.category,
18425             code: message.code,
18426             reportsUnnecessary: message.reportsUnnecessary,
18427             fileName: fileName,
18428         };
18429     }
18430     ts.createDetachedDiagnostic = createDetachedDiagnostic;
18431     function isDiagnosticWithDetachedLocation(diagnostic) {
18432         return diagnostic.file === undefined
18433             && diagnostic.start !== undefined
18434             && diagnostic.length !== undefined
18435             && typeof diagnostic.fileName === "string";
18436     }
18437     function attachFileToDiagnostic(diagnostic, file) {
18438         var fileName = file.fileName || "";
18439         var length = file.text.length;
18440         ts.Debug.assertEqual(diagnostic.fileName, fileName);
18441         ts.Debug.assertLessThanOrEqual(diagnostic.start, length);
18442         ts.Debug.assertLessThanOrEqual(diagnostic.start + diagnostic.length, length);
18443         var diagnosticWithLocation = {
18444             file: file,
18445             start: diagnostic.start,
18446             length: diagnostic.length,
18447             messageText: diagnostic.messageText,
18448             category: diagnostic.category,
18449             code: diagnostic.code,
18450             reportsUnnecessary: diagnostic.reportsUnnecessary
18451         };
18452         if (diagnostic.relatedInformation) {
18453             diagnosticWithLocation.relatedInformation = [];
18454             for (var _i = 0, _a = diagnostic.relatedInformation; _i < _a.length; _i++) {
18455                 var related = _a[_i];
18456                 if (isDiagnosticWithDetachedLocation(related) && related.fileName === fileName) {
18457                     ts.Debug.assertLessThanOrEqual(related.start, length);
18458                     ts.Debug.assertLessThanOrEqual(related.start + related.length, length);
18459                     diagnosticWithLocation.relatedInformation.push(attachFileToDiagnostic(related, file));
18460                 }
18461                 else {
18462                     diagnosticWithLocation.relatedInformation.push(related);
18463                 }
18464             }
18465         }
18466         return diagnosticWithLocation;
18467     }
18468     function attachFileToDiagnostics(diagnostics, file) {
18469         var diagnosticsWithLocation = [];
18470         for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
18471             var diagnostic = diagnostics_1[_i];
18472             diagnosticsWithLocation.push(attachFileToDiagnostic(diagnostic, file));
18473         }
18474         return diagnosticsWithLocation;
18475     }
18476     ts.attachFileToDiagnostics = attachFileToDiagnostics;
18477     function createFileDiagnostic(file, start, length, message) {
18478         ts.Debug.assertGreaterThanOrEqual(start, 0);
18479         ts.Debug.assertGreaterThanOrEqual(length, 0);
18480         if (file) {
18481             ts.Debug.assertLessThanOrEqual(start, file.text.length);
18482             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
18483         }
18484         var text = getLocaleSpecificMessage(message);
18485         if (arguments.length > 4) {
18486             text = formatStringFromArgs(text, arguments, 4);
18487         }
18488         return {
18489             file: file,
18490             start: start,
18491             length: length,
18492             messageText: text,
18493             category: message.category,
18494             code: message.code,
18495             reportsUnnecessary: message.reportsUnnecessary,
18496             reportsDeprecated: message.reportsDeprecated
18497         };
18498     }
18499     ts.createFileDiagnostic = createFileDiagnostic;
18500     function formatMessage(_dummy, message) {
18501         var text = getLocaleSpecificMessage(message);
18502         if (arguments.length > 2) {
18503             text = formatStringFromArgs(text, arguments, 2);
18504         }
18505         return text;
18506     }
18507     ts.formatMessage = formatMessage;
18508     function createCompilerDiagnostic(message) {
18509         var text = getLocaleSpecificMessage(message);
18510         if (arguments.length > 1) {
18511             text = formatStringFromArgs(text, arguments, 1);
18512         }
18513         return {
18514             file: undefined,
18515             start: undefined,
18516             length: undefined,
18517             messageText: text,
18518             category: message.category,
18519             code: message.code,
18520             reportsUnnecessary: message.reportsUnnecessary,
18521             reportsDeprecated: message.reportsDeprecated
18522         };
18523     }
18524     ts.createCompilerDiagnostic = createCompilerDiagnostic;
18525     function createCompilerDiagnosticFromMessageChain(chain) {
18526         return {
18527             file: undefined,
18528             start: undefined,
18529             length: undefined,
18530             code: chain.code,
18531             category: chain.category,
18532             messageText: chain.next ? chain : chain.messageText,
18533         };
18534     }
18535     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
18536     function chainDiagnosticMessages(details, message) {
18537         var text = getLocaleSpecificMessage(message);
18538         if (arguments.length > 2) {
18539             text = formatStringFromArgs(text, arguments, 2);
18540         }
18541         return {
18542             messageText: text,
18543             category: message.category,
18544             code: message.code,
18545             next: details === undefined || Array.isArray(details) ? details : [details]
18546         };
18547     }
18548     ts.chainDiagnosticMessages = chainDiagnosticMessages;
18549     function concatenateDiagnosticMessageChains(headChain, tailChain) {
18550         var lastChain = headChain;
18551         while (lastChain.next) {
18552             lastChain = lastChain.next[0];
18553         }
18554         lastChain.next = [tailChain];
18555     }
18556     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
18557     function getDiagnosticFilePath(diagnostic) {
18558         return diagnostic.file ? diagnostic.file.path : undefined;
18559     }
18560     function compareDiagnostics(d1, d2) {
18561         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
18562             compareRelatedInformation(d1, d2) ||
18563             0 /* EqualTo */;
18564     }
18565     ts.compareDiagnostics = compareDiagnostics;
18566     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
18567         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
18568             ts.compareValues(d1.start, d2.start) ||
18569             ts.compareValues(d1.length, d2.length) ||
18570             ts.compareValues(d1.code, d2.code) ||
18571             compareMessageText(d1.messageText, d2.messageText) ||
18572             0 /* EqualTo */;
18573     }
18574     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
18575     function compareRelatedInformation(d1, d2) {
18576         if (!d1.relatedInformation && !d2.relatedInformation) {
18577             return 0 /* EqualTo */;
18578         }
18579         if (d1.relatedInformation && d2.relatedInformation) {
18580             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
18581                 var d2i = d2.relatedInformation[index];
18582                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
18583             }) || 0 /* EqualTo */;
18584         }
18585         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
18586     }
18587     function compareMessageText(t1, t2) {
18588         if (typeof t1 === "string" && typeof t2 === "string") {
18589             return ts.compareStringsCaseSensitive(t1, t2);
18590         }
18591         else if (typeof t1 === "string") {
18592             return -1 /* LessThan */;
18593         }
18594         else if (typeof t2 === "string") {
18595             return 1 /* GreaterThan */;
18596         }
18597         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
18598         if (res) {
18599             return res;
18600         }
18601         if (!t1.next && !t2.next) {
18602             return 0 /* EqualTo */;
18603         }
18604         if (!t1.next) {
18605             return -1 /* LessThan */;
18606         }
18607         if (!t2.next) {
18608             return 1 /* GreaterThan */;
18609         }
18610         var len = Math.min(t1.next.length, t2.next.length);
18611         for (var i = 0; i < len; i++) {
18612             res = compareMessageText(t1.next[i], t2.next[i]);
18613             if (res) {
18614                 return res;
18615             }
18616         }
18617         if (t1.next.length < t2.next.length) {
18618             return -1 /* LessThan */;
18619         }
18620         else if (t1.next.length > t2.next.length) {
18621             return 1 /* GreaterThan */;
18622         }
18623         return 0 /* EqualTo */;
18624     }
18625     function getLanguageVariant(scriptKind) {
18626         // .tsx and .jsx files are treated as jsx language variant.
18627         return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
18628     }
18629     ts.getLanguageVariant = getLanguageVariant;
18630     function getEmitScriptTarget(compilerOptions) {
18631         return compilerOptions.target || 0 /* ES3 */;
18632     }
18633     ts.getEmitScriptTarget = getEmitScriptTarget;
18634     function getEmitModuleKind(compilerOptions) {
18635         return typeof compilerOptions.module === "number" ?
18636             compilerOptions.module :
18637             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
18638     }
18639     ts.getEmitModuleKind = getEmitModuleKind;
18640     function getEmitModuleResolutionKind(compilerOptions) {
18641         var moduleResolution = compilerOptions.moduleResolution;
18642         if (moduleResolution === undefined) {
18643             moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
18644         }
18645         return moduleResolution;
18646     }
18647     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
18648     function hasJsonModuleEmitEnabled(options) {
18649         switch (getEmitModuleKind(options)) {
18650             case ts.ModuleKind.CommonJS:
18651             case ts.ModuleKind.AMD:
18652             case ts.ModuleKind.ES2015:
18653             case ts.ModuleKind.ES2020:
18654             case ts.ModuleKind.ESNext:
18655                 return true;
18656             default:
18657                 return false;
18658         }
18659     }
18660     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
18661     function unreachableCodeIsError(options) {
18662         return options.allowUnreachableCode === false;
18663     }
18664     ts.unreachableCodeIsError = unreachableCodeIsError;
18665     function unusedLabelIsError(options) {
18666         return options.allowUnusedLabels === false;
18667     }
18668     ts.unusedLabelIsError = unusedLabelIsError;
18669     function getAreDeclarationMapsEnabled(options) {
18670         return !!(getEmitDeclarations(options) && options.declarationMap);
18671     }
18672     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
18673     function getAllowSyntheticDefaultImports(compilerOptions) {
18674         var moduleKind = getEmitModuleKind(compilerOptions);
18675         return compilerOptions.allowSyntheticDefaultImports !== undefined
18676             ? compilerOptions.allowSyntheticDefaultImports
18677             : compilerOptions.esModuleInterop ||
18678                 moduleKind === ts.ModuleKind.System;
18679     }
18680     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
18681     function getEmitDeclarations(compilerOptions) {
18682         return !!(compilerOptions.declaration || compilerOptions.composite);
18683     }
18684     ts.getEmitDeclarations = getEmitDeclarations;
18685     function isIncrementalCompilation(options) {
18686         return !!(options.incremental || options.composite);
18687     }
18688     ts.isIncrementalCompilation = isIncrementalCompilation;
18689     function getStrictOptionValue(compilerOptions, flag) {
18690         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
18691     }
18692     ts.getStrictOptionValue = getStrictOptionValue;
18693     function getAllowJSCompilerOption(compilerOptions) {
18694         return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs;
18695     }
18696     ts.getAllowJSCompilerOption = getAllowJSCompilerOption;
18697     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
18698         return oldOptions !== newOptions &&
18699             ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18700     }
18701     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
18702     function compilerOptionsAffectEmit(newOptions, oldOptions) {
18703         return oldOptions !== newOptions &&
18704             ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18705     }
18706     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
18707     function getCompilerOptionValue(options, option) {
18708         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
18709     }
18710     ts.getCompilerOptionValue = getCompilerOptionValue;
18711     function getJSXTransformEnabled(options) {
18712         var jsx = options.jsx;
18713         return jsx === 2 /* React */ || jsx === 4 /* ReactJSX */ || jsx === 5 /* ReactJSXDev */;
18714     }
18715     ts.getJSXTransformEnabled = getJSXTransformEnabled;
18716     function getJSXImplicitImportBase(compilerOptions, file) {
18717         var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource");
18718         var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas;
18719         return compilerOptions.jsx === 4 /* ReactJSX */ ||
18720             compilerOptions.jsx === 5 /* ReactJSXDev */ ||
18721             compilerOptions.jsxImportSource ||
18722             jsxImportSourcePragma ?
18723             (jsxImportSourcePragma === null || jsxImportSourcePragma === void 0 ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" :
18724             undefined;
18725     }
18726     ts.getJSXImplicitImportBase = getJSXImplicitImportBase;
18727     function getJSXRuntimeImport(base, options) {
18728         return base ? base + "/" + (options.jsx === 5 /* ReactJSXDev */ ? "jsx-dev-runtime" : "jsx-runtime") : undefined;
18729     }
18730     ts.getJSXRuntimeImport = getJSXRuntimeImport;
18731     function hasZeroOrOneAsteriskCharacter(str) {
18732         var seenAsterisk = false;
18733         for (var i = 0; i < str.length; i++) {
18734             if (str.charCodeAt(i) === 42 /* asterisk */) {
18735                 if (!seenAsterisk) {
18736                     seenAsterisk = true;
18737                 }
18738                 else {
18739                     // have already seen asterisk
18740                     return false;
18741                 }
18742             }
18743         }
18744         return true;
18745     }
18746     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
18747     function createSymlinkCache() {
18748         var symlinkedDirectories;
18749         var symlinkedFiles;
18750         return {
18751             getSymlinkedFiles: function () { return symlinkedFiles; },
18752             getSymlinkedDirectories: function () { return symlinkedDirectories; },
18753             setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); },
18754             setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); },
18755         };
18756     }
18757     ts.createSymlinkCache = createSymlinkCache;
18758     function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
18759         var cache = createSymlinkCache();
18760         var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
18761             return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
18762                 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
18763             })));
18764         }));
18765         for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
18766             var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
18767             var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1];
18768             if (commonResolved && commonOriginal) {
18769                 cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) });
18770             }
18771         }
18772         return cache;
18773     }
18774     ts.discoverProbableSymlinks = discoverProbableSymlinks;
18775     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
18776         var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
18777         var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
18778         var isDirectory = false;
18779         while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
18780             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
18781             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
18782             aParts.pop();
18783             bParts.pop();
18784             isDirectory = true;
18785         }
18786         return isDirectory ? [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)] : undefined;
18787     }
18788     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
18789     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
18790     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
18791         return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
18792     }
18793     function stripLeadingDirectorySeparator(s) {
18794         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
18795     }
18796     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
18797         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
18798         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
18799     }
18800     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
18801     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
18802     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
18803     // proof.
18804     var reservedCharacterPattern = /[^\w\s\/]/g;
18805     function regExpEscape(text) {
18806         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
18807     }
18808     ts.regExpEscape = regExpEscape;
18809     function escapeRegExpCharacter(match) {
18810         return "\\" + match;
18811     }
18812     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
18813     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
18814     var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
18815     var filesMatcher = {
18816         /**
18817          * Matches any single directory segment unless it is the last segment and a .min.js file
18818          * Breakdown:
18819          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
18820          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
18821          */
18822         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
18823         /**
18824          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18825          * files or directories, does not match subdirectories that start with a . character
18826          */
18827         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18828         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
18829     };
18830     var directoriesMatcher = {
18831         singleAsteriskRegexFragment: "[^/]*",
18832         /**
18833          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18834          * files or directories, does not match subdirectories that start with a . character
18835          */
18836         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18837         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
18838     };
18839     var excludeMatcher = {
18840         singleAsteriskRegexFragment: "[^/]*",
18841         doubleAsteriskRegexFragment: "(/.+?)?",
18842         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
18843     };
18844     var wildcardMatchers = {
18845         files: filesMatcher,
18846         directories: directoriesMatcher,
18847         exclude: excludeMatcher
18848     };
18849     function getRegularExpressionForWildcard(specs, basePath, usage) {
18850         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
18851         if (!patterns || !patterns.length) {
18852             return undefined;
18853         }
18854         var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
18855         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
18856         var terminator = usage === "exclude" ? "($|/)" : "$";
18857         return "^(" + pattern + ")" + terminator;
18858     }
18859     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
18860     function getRegularExpressionsForWildcards(specs, basePath, usage) {
18861         if (specs === undefined || specs.length === 0) {
18862             return undefined;
18863         }
18864         return ts.flatMap(specs, function (spec) {
18865             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
18866         });
18867     }
18868     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
18869     /**
18870      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
18871      * and does not contain any glob characters itself.
18872      */
18873     function isImplicitGlob(lastPathComponent) {
18874         return !/[.*?]/.test(lastPathComponent);
18875     }
18876     ts.isImplicitGlob = isImplicitGlob;
18877     function getSubPatternFromSpec(spec, basePath, usage, _a) {
18878         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
18879         var subpattern = "";
18880         var hasWrittenComponent = false;
18881         var components = ts.getNormalizedPathComponents(spec, basePath);
18882         var lastComponent = ts.last(components);
18883         if (usage !== "exclude" && lastComponent === "**") {
18884             return undefined;
18885         }
18886         // getNormalizedPathComponents includes the separator for the root component.
18887         // We need to remove to create our regex correctly.
18888         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
18889         if (isImplicitGlob(lastComponent)) {
18890             components.push("**", "*");
18891         }
18892         var optionalCount = 0;
18893         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
18894             var component = components_1[_i];
18895             if (component === "**") {
18896                 subpattern += doubleAsteriskRegexFragment;
18897             }
18898             else {
18899                 if (usage === "directories") {
18900                     subpattern += "(";
18901                     optionalCount++;
18902                 }
18903                 if (hasWrittenComponent) {
18904                     subpattern += ts.directorySeparator;
18905                 }
18906                 if (usage !== "exclude") {
18907                     var componentPattern = "";
18908                     // The * and ? wildcards should not match directories or files that start with . if they
18909                     // appear first in a component. Dotted directories and files can be included explicitly
18910                     // like so: **/.*/.*
18911                     if (component.charCodeAt(0) === 42 /* asterisk */) {
18912                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
18913                         component = component.substr(1);
18914                     }
18915                     else if (component.charCodeAt(0) === 63 /* question */) {
18916                         componentPattern += "[^./]";
18917                         component = component.substr(1);
18918                     }
18919                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18920                     // Patterns should not include subfolders like node_modules unless they are
18921                     // explicitly included as part of the path.
18922                     //
18923                     // As an optimization, if the component pattern is the same as the component,
18924                     // then there definitely were no wildcard characters and we do not need to
18925                     // add the exclusion pattern.
18926                     if (componentPattern !== component) {
18927                         subpattern += implicitExcludePathRegexPattern;
18928                     }
18929                     subpattern += componentPattern;
18930                 }
18931                 else {
18932                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18933                 }
18934             }
18935             hasWrittenComponent = true;
18936         }
18937         while (optionalCount > 0) {
18938             subpattern += ")?";
18939             optionalCount--;
18940         }
18941         return subpattern;
18942     }
18943     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
18944         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
18945     }
18946     /** @param path directory of the tsconfig.json */
18947     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
18948         path = ts.normalizePath(path);
18949         currentDirectory = ts.normalizePath(currentDirectory);
18950         var absolutePath = ts.combinePaths(currentDirectory, path);
18951         return {
18952             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
18953             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
18954             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
18955             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
18956             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
18957         };
18958     }
18959     ts.getFileMatcherPatterns = getFileMatcherPatterns;
18960     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
18961         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
18962     }
18963     ts.getRegexFromPattern = getRegexFromPattern;
18964     /** @param path directory of the tsconfig.json */
18965     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
18966         path = ts.normalizePath(path);
18967         currentDirectory = ts.normalizePath(currentDirectory);
18968         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
18969         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
18970         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
18971         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
18972         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
18973         // If there are no "includes", then just put everything in results[0].
18974         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
18975         var visited = new ts.Map();
18976         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
18977         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
18978             var basePath = _a[_i];
18979             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
18980         }
18981         return ts.flatten(results);
18982         function visitDirectory(path, absolutePath, depth) {
18983             var canonicalPath = toCanonical(realpath(absolutePath));
18984             if (visited.has(canonicalPath))
18985                 return;
18986             visited.set(canonicalPath, true);
18987             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
18988             var _loop_1 = function (current) {
18989                 var name = ts.combinePaths(path, current);
18990                 var absoluteName = ts.combinePaths(absolutePath, current);
18991                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
18992                     return "continue";
18993                 if (excludeRegex && excludeRegex.test(absoluteName))
18994                     return "continue";
18995                 if (!includeFileRegexes) {
18996                     results[0].push(name);
18997                 }
18998                 else {
18999                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
19000                     if (includeIndex !== -1) {
19001                         results[includeIndex].push(name);
19002                     }
19003                 }
19004             };
19005             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
19006                 var current = _b[_i];
19007                 _loop_1(current);
19008             }
19009             if (depth !== undefined) {
19010                 depth--;
19011                 if (depth === 0) {
19012                     return;
19013                 }
19014             }
19015             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
19016                 var current = _d[_c];
19017                 var name = ts.combinePaths(path, current);
19018                 var absoluteName = ts.combinePaths(absolutePath, current);
19019                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
19020                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
19021                     visitDirectory(name, absoluteName, depth);
19022                 }
19023             }
19024         }
19025     }
19026     ts.matchFiles = matchFiles;
19027     /**
19028      * Computes the unique non-wildcard base paths amongst the provided include patterns.
19029      */
19030     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
19031         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
19032         var basePaths = [path];
19033         if (includes) {
19034             // Storage for literal base paths amongst the include patterns.
19035             var includeBasePaths = [];
19036             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
19037                 var include = includes_1[_i];
19038                 // We also need to check the relative paths by converting them to absolute and normalizing
19039                 // in case they escape the base path (e.g "..\somedirectory")
19040                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
19041                 // Append the literal and canonical candidate base paths.
19042                 includeBasePaths.push(getIncludeBasePath(absolute));
19043             }
19044             // Sort the offsets array using either the literal or canonical path representations.
19045             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
19046             var _loop_2 = function (includeBasePath) {
19047                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
19048                     basePaths.push(includeBasePath);
19049                 }
19050             };
19051             // Iterate over each include base path and include unique base paths that are not a
19052             // subpath of an existing base path
19053             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
19054                 var includeBasePath = includeBasePaths_1[_a];
19055                 _loop_2(includeBasePath);
19056             }
19057         }
19058         return basePaths;
19059     }
19060     function getIncludeBasePath(absolute) {
19061         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
19062         if (wildcardOffset < 0) {
19063             // No "*" or "?" in the path
19064             return !ts.hasExtension(absolute)
19065                 ? absolute
19066                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
19067         }
19068         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
19069     }
19070     function ensureScriptKind(fileName, scriptKind) {
19071         // Using scriptKind as a condition handles both:
19072         // - 'scriptKind' is unspecified and thus it is `undefined`
19073         // - 'scriptKind' is set and it is `Unknown` (0)
19074         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
19075         // to get the ScriptKind from the file name. If it cannot be resolved
19076         // from the file name then the default 'TS' script kind is returned.
19077         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
19078     }
19079     ts.ensureScriptKind = ensureScriptKind;
19080     function getScriptKindFromFileName(fileName) {
19081         var ext = fileName.substr(fileName.lastIndexOf("."));
19082         switch (ext.toLowerCase()) {
19083             case ".js" /* Js */:
19084                 return 1 /* JS */;
19085             case ".jsx" /* Jsx */:
19086                 return 2 /* JSX */;
19087             case ".ts" /* Ts */:
19088                 return 3 /* TS */;
19089             case ".tsx" /* Tsx */:
19090                 return 4 /* TSX */;
19091             case ".json" /* Json */:
19092                 return 6 /* JSON */;
19093             default:
19094                 return 0 /* Unknown */;
19095         }
19096     }
19097     ts.getScriptKindFromFileName = getScriptKindFromFileName;
19098     /**
19099      *  List of supported extensions in order of file resolution precedence.
19100      */
19101     ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
19102     ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
19103     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
19104     ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
19105     ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
19106     ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
19107     var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
19108     var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
19109     function getSupportedExtensions(options, extraFileExtensions) {
19110         var needJsExtensions = options && getAllowJSCompilerOption(options);
19111         if (!extraFileExtensions || extraFileExtensions.length === 0) {
19112             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
19113         }
19114         var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
19115         return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
19116     }
19117     ts.getSupportedExtensions = getSupportedExtensions;
19118     function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
19119         if (!options || !options.resolveJsonModule) {
19120             return supportedExtensions;
19121         }
19122         if (supportedExtensions === allSupportedExtensions) {
19123             return allSupportedExtensionsWithJson;
19124         }
19125         if (supportedExtensions === ts.supportedTSExtensions) {
19126             return ts.supportedTSExtensionsWithJson;
19127         }
19128         return __spreadArrays(supportedExtensions, [".json" /* Json */]);
19129     }
19130     ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
19131     function isJSLike(scriptKind) {
19132         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
19133     }
19134     function hasJSFileExtension(fileName) {
19135         return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
19136     }
19137     ts.hasJSFileExtension = hasJSFileExtension;
19138     function hasTSFileExtension(fileName) {
19139         return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
19140     }
19141     ts.hasTSFileExtension = hasTSFileExtension;
19142     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
19143         if (!fileName) {
19144             return false;
19145         }
19146         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
19147         for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
19148             var extension = _a[_i];
19149             if (ts.fileExtensionIs(fileName, extension)) {
19150                 return true;
19151             }
19152         }
19153         return false;
19154     }
19155     ts.isSupportedSourceFileName = isSupportedSourceFileName;
19156     /**
19157      * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
19158      * aligned to the offset of the highest priority extension in the
19159      * allSupportedExtensions array.
19160      */
19161     var ExtensionPriority;
19162     (function (ExtensionPriority) {
19163         ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
19164         ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
19165         ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
19166         ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
19167     })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
19168     function getExtensionPriority(path, supportedExtensions) {
19169         for (var i = supportedExtensions.length - 1; i >= 0; i--) {
19170             if (ts.fileExtensionIs(path, supportedExtensions[i])) {
19171                 return adjustExtensionPriority(i, supportedExtensions);
19172             }
19173         }
19174         // If its not in the list of supported extensions, this is likely a
19175         // TypeScript file with a non-ts extension
19176         return 0 /* Highest */;
19177     }
19178     ts.getExtensionPriority = getExtensionPriority;
19179     /**
19180      * Adjusts an extension priority to be the highest priority within the same range.
19181      */
19182     function adjustExtensionPriority(extensionPriority, supportedExtensions) {
19183         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
19184             return 0 /* TypeScriptFiles */;
19185         }
19186         else if (extensionPriority < supportedExtensions.length) {
19187             return 2 /* DeclarationAndJavaScriptFiles */;
19188         }
19189         else {
19190             return supportedExtensions.length;
19191         }
19192     }
19193     ts.adjustExtensionPriority = adjustExtensionPriority;
19194     /**
19195      * Gets the next lowest extension priority for a given priority.
19196      */
19197     function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
19198         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
19199             return 2 /* DeclarationAndJavaScriptFiles */;
19200         }
19201         else {
19202             return supportedExtensions.length;
19203         }
19204     }
19205     ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
19206     var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
19207     function removeFileExtension(path) {
19208         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
19209             var ext = extensionsToRemove_1[_i];
19210             var extensionless = tryRemoveExtension(path, ext);
19211             if (extensionless !== undefined) {
19212                 return extensionless;
19213             }
19214         }
19215         return path;
19216     }
19217     ts.removeFileExtension = removeFileExtension;
19218     function tryRemoveExtension(path, extension) {
19219         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
19220     }
19221     ts.tryRemoveExtension = tryRemoveExtension;
19222     function removeExtension(path, extension) {
19223         return path.substring(0, path.length - extension.length);
19224     }
19225     ts.removeExtension = removeExtension;
19226     function changeExtension(path, newExtension) {
19227         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
19228     }
19229     ts.changeExtension = changeExtension;
19230     function tryParsePattern(pattern) {
19231         // This should be verified outside of here and a proper error thrown.
19232         ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
19233         var indexOfStar = pattern.indexOf("*");
19234         return indexOfStar === -1 ? undefined : {
19235             prefix: pattern.substr(0, indexOfStar),
19236             suffix: pattern.substr(indexOfStar + 1)
19237         };
19238     }
19239     ts.tryParsePattern = tryParsePattern;
19240     function positionIsSynthesized(pos) {
19241         // This is a fast way of testing the following conditions:
19242         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
19243         return !(pos >= 0);
19244     }
19245     ts.positionIsSynthesized = positionIsSynthesized;
19246     /** True if an extension is one of the supported TypeScript extensions. */
19247     function extensionIsTS(ext) {
19248         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
19249     }
19250     ts.extensionIsTS = extensionIsTS;
19251     function resolutionExtensionIsTSOrJson(ext) {
19252         return extensionIsTS(ext) || ext === ".json" /* Json */;
19253     }
19254     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
19255     /**
19256      * Gets the extension from a path.
19257      * Path must have a valid extension.
19258      */
19259     function extensionFromPath(path) {
19260         var ext = tryGetExtensionFromPath(path);
19261         return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
19262     }
19263     ts.extensionFromPath = extensionFromPath;
19264     function isAnySupportedFileExtension(path) {
19265         return tryGetExtensionFromPath(path) !== undefined;
19266     }
19267     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
19268     function tryGetExtensionFromPath(path) {
19269         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
19270     }
19271     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
19272     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
19273         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
19274     }
19275     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
19276     ts.emptyFileSystemEntries = {
19277         files: ts.emptyArray,
19278         directories: ts.emptyArray
19279     };
19280     /**
19281      * patternStrings contains both pattern strings (containing "*") and regular strings.
19282      * Return an exact match if possible, or a pattern match, or undefined.
19283      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
19284      */
19285     function matchPatternOrExact(patternStrings, candidate) {
19286         var patterns = [];
19287         for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
19288             var patternString = patternStrings_1[_i];
19289             if (!hasZeroOrOneAsteriskCharacter(patternString))
19290                 continue;
19291             var pattern = tryParsePattern(patternString);
19292             if (pattern) {
19293                 patterns.push(pattern);
19294             }
19295             else if (patternString === candidate) {
19296                 // pattern was matched as is - no need to search further
19297                 return patternString;
19298             }
19299         }
19300         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
19301     }
19302     ts.matchPatternOrExact = matchPatternOrExact;
19303     function sliceAfter(arr, value) {
19304         var index = arr.indexOf(value);
19305         ts.Debug.assert(index !== -1);
19306         return arr.slice(index);
19307     }
19308     ts.sliceAfter = sliceAfter;
19309     function addRelatedInfo(diagnostic) {
19310         var _a;
19311         var relatedInformation = [];
19312         for (var _i = 1; _i < arguments.length; _i++) {
19313             relatedInformation[_i - 1] = arguments[_i];
19314         }
19315         if (!relatedInformation.length) {
19316             return diagnostic;
19317         }
19318         if (!diagnostic.relatedInformation) {
19319             diagnostic.relatedInformation = [];
19320         }
19321         ts.Debug.assert(diagnostic.relatedInformation !== ts.emptyArray, "Diagnostic had empty array singleton for related info, but is still being constructed!");
19322         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
19323         return diagnostic;
19324     }
19325     ts.addRelatedInfo = addRelatedInfo;
19326     function minAndMax(arr, getValue) {
19327         ts.Debug.assert(arr.length !== 0);
19328         var min = getValue(arr[0]);
19329         var max = min;
19330         for (var i = 1; i < arr.length; i++) {
19331             var value = getValue(arr[i]);
19332             if (value < min) {
19333                 min = value;
19334             }
19335             else if (value > max) {
19336                 max = value;
19337             }
19338         }
19339         return { min: min, max: max };
19340     }
19341     ts.minAndMax = minAndMax;
19342     function rangeOfNode(node) {
19343         return { pos: getTokenPosOfNode(node), end: node.end };
19344     }
19345     ts.rangeOfNode = rangeOfNode;
19346     function rangeOfTypeParameters(typeParameters) {
19347         // Include the `<>`
19348         return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
19349     }
19350     ts.rangeOfTypeParameters = rangeOfTypeParameters;
19351     function skipTypeChecking(sourceFile, options, host) {
19352         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
19353         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
19354         // '/// <reference no-default-lib="true"/>' directive.
19355         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
19356             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
19357             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
19358     }
19359     ts.skipTypeChecking = skipTypeChecking;
19360     function isJsonEqual(a, b) {
19361         // eslint-disable-next-line no-null/no-null
19362         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
19363     }
19364     ts.isJsonEqual = isJsonEqual;
19365     /**
19366      * Converts a bigint literal string, e.g. `0x1234n`,
19367      * to its decimal string representation, e.g. `4660`.
19368      */
19369     function parsePseudoBigInt(stringValue) {
19370         var log2Base;
19371         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
19372             case 98 /* b */:
19373             case 66 /* B */: // 0b or 0B
19374                 log2Base = 1;
19375                 break;
19376             case 111 /* o */:
19377             case 79 /* O */: // 0o or 0O
19378                 log2Base = 3;
19379                 break;
19380             case 120 /* x */:
19381             case 88 /* X */: // 0x or 0X
19382                 log2Base = 4;
19383                 break;
19384             default: // already in decimal; omit trailing "n"
19385                 var nIndex = stringValue.length - 1;
19386                 // Skip leading 0s
19387                 var nonZeroStart = 0;
19388                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
19389                     nonZeroStart++;
19390                 }
19391                 return stringValue.slice(nonZeroStart, nIndex) || "0";
19392         }
19393         // Omit leading "0b", "0o", or "0x", and trailing "n"
19394         var startIndex = 2, endIndex = stringValue.length - 1;
19395         var bitsNeeded = (endIndex - startIndex) * log2Base;
19396         // Stores the value specified by the string as a LE array of 16-bit integers
19397         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
19398         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
19399         // Add the digits, one at a time
19400         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
19401             var segment = bitOffset >>> 4;
19402             var digitChar = stringValue.charCodeAt(i);
19403             // Find character range: 0-9 < A-F < a-f
19404             var digit = digitChar <= 57 /* _9 */
19405                 ? digitChar - 48 /* _0 */
19406                 : 10 + digitChar -
19407                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
19408             var shiftedDigit = digit << (bitOffset & 15);
19409             segments[segment] |= shiftedDigit;
19410             var residual = shiftedDigit >>> 16;
19411             if (residual)
19412                 segments[segment + 1] |= residual; // overflows segment
19413         }
19414         // Repeatedly divide segments by 10 and add remainder to base10Value
19415         var base10Value = "";
19416         var firstNonzeroSegment = segments.length - 1;
19417         var segmentsRemaining = true;
19418         while (segmentsRemaining) {
19419             var mod10 = 0;
19420             segmentsRemaining = false;
19421             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
19422                 var newSegment = mod10 << 16 | segments[segment];
19423                 var segmentValue = (newSegment / 10) | 0;
19424                 segments[segment] = segmentValue;
19425                 mod10 = newSegment - segmentValue * 10;
19426                 if (segmentValue && !segmentsRemaining) {
19427                     firstNonzeroSegment = segment;
19428                     segmentsRemaining = true;
19429                 }
19430             }
19431             base10Value = mod10 + base10Value;
19432         }
19433         return base10Value;
19434     }
19435     ts.parsePseudoBigInt = parsePseudoBigInt;
19436     function pseudoBigIntToString(_a) {
19437         var negative = _a.negative, base10Value = _a.base10Value;
19438         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
19439     }
19440     ts.pseudoBigIntToString = pseudoBigIntToString;
19441     function isValidTypeOnlyAliasUseSite(useSite) {
19442         return !!(useSite.flags & 8388608 /* Ambient */)
19443             || isPartOfTypeQuery(useSite)
19444             || isIdentifierInNonEmittingHeritageClause(useSite)
19445             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
19446             || !isExpressionNode(useSite);
19447     }
19448     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
19449     function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
19450         return typeOnlyDeclaration.kind === 270 /* ExportSpecifier */;
19451     }
19452     ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
19453     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
19454         while (node.kind === 78 /* Identifier */ || node.kind === 201 /* PropertyAccessExpression */) {
19455             node = node.parent;
19456         }
19457         if (node.kind !== 158 /* ComputedPropertyName */) {
19458             return false;
19459         }
19460         if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) {
19461             return true;
19462         }
19463         var containerKind = node.parent.parent.kind;
19464         return containerKind === 253 /* InterfaceDeclaration */ || containerKind === 177 /* TypeLiteral */;
19465     }
19466     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
19467     function isIdentifierInNonEmittingHeritageClause(node) {
19468         if (node.kind !== 78 /* Identifier */)
19469             return false;
19470         var heritageClause = ts.findAncestor(node.parent, function (parent) {
19471             switch (parent.kind) {
19472                 case 286 /* HeritageClause */:
19473                     return true;
19474                 case 201 /* PropertyAccessExpression */:
19475                 case 223 /* ExpressionWithTypeArguments */:
19476                     return false;
19477                 default:
19478                     return "quit";
19479             }
19480         });
19481         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 253 /* InterfaceDeclaration */;
19482     }
19483     function isIdentifierTypeReference(node) {
19484         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
19485     }
19486     ts.isIdentifierTypeReference = isIdentifierTypeReference;
19487     function arrayIsHomogeneous(array, comparer) {
19488         if (comparer === void 0) { comparer = ts.equateValues; }
19489         if (array.length < 2)
19490             return true;
19491         var first = array[0];
19492         for (var i = 1, length_1 = array.length; i < length_1; i++) {
19493             var target = array[i];
19494             if (!comparer(first, target))
19495                 return false;
19496         }
19497         return true;
19498     }
19499     ts.arrayIsHomogeneous = arrayIsHomogeneous;
19500     /**
19501      * Bypasses immutability and directly sets the `pos` property of a `TextRange` or `Node`.
19502      */
19503     /* @internal */
19504     function setTextRangePos(range, pos) {
19505         range.pos = pos;
19506         return range;
19507     }
19508     ts.setTextRangePos = setTextRangePos;
19509     /**
19510      * Bypasses immutability and directly sets the `end` property of a `TextRange` or `Node`.
19511      */
19512     /* @internal */
19513     function setTextRangeEnd(range, end) {
19514         range.end = end;
19515         return range;
19516     }
19517     ts.setTextRangeEnd = setTextRangeEnd;
19518     /**
19519      * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node`.
19520      */
19521     /* @internal */
19522     function setTextRangePosEnd(range, pos, end) {
19523         return setTextRangeEnd(setTextRangePos(range, pos), end);
19524     }
19525     ts.setTextRangePosEnd = setTextRangePosEnd;
19526     /**
19527      * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node` from the
19528      * provided position and width.
19529      */
19530     /* @internal */
19531     function setTextRangePosWidth(range, pos, width) {
19532         return setTextRangePosEnd(range, pos, pos + width);
19533     }
19534     ts.setTextRangePosWidth = setTextRangePosWidth;
19535     function setNodeFlags(node, newFlags) {
19536         if (node) {
19537             node.flags = newFlags;
19538         }
19539         return node;
19540     }
19541     ts.setNodeFlags = setNodeFlags;
19542     function setParent(child, parent) {
19543         if (child && parent) {
19544             child.parent = parent;
19545         }
19546         return child;
19547     }
19548     ts.setParent = setParent;
19549     function setEachParent(children, parent) {
19550         if (children) {
19551             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
19552                 var child = children_1[_i];
19553                 setParent(child, parent);
19554             }
19555         }
19556         return children;
19557     }
19558     ts.setEachParent = setEachParent;
19559     function setParentRecursive(rootNode, incremental) {
19560         if (!rootNode)
19561             return rootNode;
19562         ts.forEachChildRecursively(rootNode, ts.isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild);
19563         return rootNode;
19564         function bindParentToChildIgnoringJSDoc(child, parent) {
19565             if (incremental && child.parent === parent) {
19566                 return "skip";
19567             }
19568             setParent(child, parent);
19569         }
19570         function bindJSDoc(child) {
19571             if (ts.hasJSDocNodes(child)) {
19572                 for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
19573                     var doc = _a[_i];
19574                     bindParentToChildIgnoringJSDoc(doc, child);
19575                     ts.forEachChildRecursively(doc, bindParentToChildIgnoringJSDoc);
19576                 }
19577             }
19578         }
19579         function bindParentToChild(child, parent) {
19580             return bindParentToChildIgnoringJSDoc(child, parent) || bindJSDoc(child);
19581         }
19582     }
19583     ts.setParentRecursive = setParentRecursive;
19584 })(ts || (ts = {}));
19585 /* @internal */
19586 var ts;
19587 (function (ts) {
19588     /**
19589      * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator.
19590      */
19591     function createBaseNodeFactory() {
19592         // tslint:disable variable-name
19593         var NodeConstructor;
19594         var TokenConstructor;
19595         var IdentifierConstructor;
19596         var PrivateIdentifierConstructor;
19597         var SourceFileConstructor;
19598         // tslint:enable variable-name
19599         return {
19600             createBaseSourceFileNode: createBaseSourceFileNode,
19601             createBaseIdentifierNode: createBaseIdentifierNode,
19602             createBasePrivateIdentifierNode: createBasePrivateIdentifierNode,
19603             createBaseTokenNode: createBaseTokenNode,
19604             createBaseNode: createBaseNode
19605         };
19606         function createBaseSourceFileNode(kind) {
19607             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19608         }
19609         function createBaseIdentifierNode(kind) {
19610             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19611         }
19612         function createBasePrivateIdentifierNode(kind) {
19613             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19614         }
19615         function createBaseTokenNode(kind) {
19616             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19617         }
19618         function createBaseNode(kind) {
19619             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19620         }
19621     }
19622     ts.createBaseNodeFactory = createBaseNodeFactory;
19623 })(ts || (ts = {}));
19624 /* @internal */
19625 var ts;
19626 (function (ts) {
19627     function createParenthesizerRules(factory) {
19628         return {
19629             parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary,
19630             parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary,
19631             parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName,
19632             parenthesizeConditionOfConditionalExpression: parenthesizeConditionOfConditionalExpression,
19633             parenthesizeBranchOfConditionalExpression: parenthesizeBranchOfConditionalExpression,
19634             parenthesizeExpressionOfExportDefault: parenthesizeExpressionOfExportDefault,
19635             parenthesizeExpressionOfNew: parenthesizeExpressionOfNew,
19636             parenthesizeLeftSideOfAccess: parenthesizeLeftSideOfAccess,
19637             parenthesizeOperandOfPostfixUnary: parenthesizeOperandOfPostfixUnary,
19638             parenthesizeOperandOfPrefixUnary: parenthesizeOperandOfPrefixUnary,
19639             parenthesizeExpressionsOfCommaDelimitedList: parenthesizeExpressionsOfCommaDelimitedList,
19640             parenthesizeExpressionForDisallowedComma: parenthesizeExpressionForDisallowedComma,
19641             parenthesizeExpressionOfExpressionStatement: parenthesizeExpressionOfExpressionStatement,
19642             parenthesizeConciseBodyOfArrowFunction: parenthesizeConciseBodyOfArrowFunction,
19643             parenthesizeMemberOfConditionalType: parenthesizeMemberOfConditionalType,
19644             parenthesizeMemberOfElementType: parenthesizeMemberOfElementType,
19645             parenthesizeElementTypeOfArrayType: parenthesizeElementTypeOfArrayType,
19646             parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType,
19647             parenthesizeTypeArguments: parenthesizeTypeArguments,
19648         };
19649         /**
19650          * Determines whether the operand to a BinaryExpression needs to be parenthesized.
19651          *
19652          * @param binaryOperator The operator for the BinaryExpression.
19653          * @param operand The operand for the BinaryExpression.
19654          * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
19655          *                           BinaryExpression.
19656          */
19657         function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
19658             // If the operand has lower precedence, then it needs to be parenthesized to preserve the
19659             // intent of the expression. For example, if the operand is `a + b` and the operator is
19660             // `*`, then we need to parenthesize the operand to preserve the intended order of
19661             // operations: `(a + b) * x`.
19662             //
19663             // If the operand has higher precedence, then it does not need to be parenthesized. For
19664             // example, if the operand is `a * b` and the operator is `+`, then we do not need to
19665             // parenthesize to preserve the intended order of operations: `a * b + x`.
19666             //
19667             // If the operand has the same precedence, then we need to check the associativity of
19668             // the operator based on whether this is the left or right operand of the expression.
19669             //
19670             // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
19671             // to preserve the intended order of operations: `x * (a / d)`
19672             //
19673             // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
19674             // the intended order of operations: `(a ** b) ** c`
19675             var binaryOperatorPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, binaryOperator);
19676             var binaryOperatorAssociativity = ts.getOperatorAssociativity(216 /* BinaryExpression */, binaryOperator);
19677             var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
19678             if (!isLeftSideOfBinary && operand.kind === 209 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) {
19679                 // We need to parenthesize arrow functions on the right side to avoid it being
19680                 // parsed as parenthesized expression: `a && (() => {})`
19681                 return true;
19682             }
19683             var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
19684             switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
19685                 case -1 /* LessThan */:
19686                     // If the operand is the right side of a right-associative binary operation
19687                     // and is a yield expression, then we do not need parentheses.
19688                     if (!isLeftSideOfBinary
19689                         && binaryOperatorAssociativity === 1 /* Right */
19690                         && operand.kind === 219 /* YieldExpression */) {
19691                         return false;
19692                     }
19693                     return true;
19694                 case 1 /* GreaterThan */:
19695                     return false;
19696                 case 0 /* EqualTo */:
19697                     if (isLeftSideOfBinary) {
19698                         // No need to parenthesize the left operand when the binary operator is
19699                         // left associative:
19700                         //  (a*b)/x    -> a*b/x
19701                         //  (a**b)/x   -> a**b/x
19702                         //
19703                         // Parentheses are needed for the left operand when the binary operator is
19704                         // right associative:
19705                         //  (a/b)**x   -> (a/b)**x
19706                         //  (a**b)**x  -> (a**b)**x
19707                         return binaryOperatorAssociativity === 1 /* Right */;
19708                     }
19709                     else {
19710                         if (ts.isBinaryExpression(emittedOperand)
19711                             && emittedOperand.operatorToken.kind === binaryOperator) {
19712                             // No need to parenthesize the right operand when the binary operator and
19713                             // operand are the same and one of the following:
19714                             //  x*(a*b)     => x*a*b
19715                             //  x|(a|b)     => x|a|b
19716                             //  x&(a&b)     => x&a&b
19717                             //  x^(a^b)     => x^a^b
19718                             if (operatorHasAssociativeProperty(binaryOperator)) {
19719                                 return false;
19720                             }
19721                             // No need to parenthesize the right operand when the binary operator
19722                             // is plus (+) if both the left and right operands consist solely of either
19723                             // literals of the same kind or binary plus (+) expressions for literals of
19724                             // the same kind (recursively).
19725                             //  "a"+(1+2)       => "a"+(1+2)
19726                             //  "a"+("b"+"c")   => "a"+"b"+"c"
19727                             if (binaryOperator === 39 /* PlusToken */) {
19728                                 var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
19729                                 if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
19730                                     return false;
19731                                 }
19732                             }
19733                         }
19734                         // No need to parenthesize the right operand when the operand is right
19735                         // associative:
19736                         //  x/(a**b)    -> x/a**b
19737                         //  x**(a**b)   -> x**a**b
19738                         //
19739                         // Parentheses are needed for the right operand when the operand is left
19740                         // associative:
19741                         //  x/(a*b)     -> x/(a*b)
19742                         //  x**(a/b)    -> x**(a/b)
19743                         var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
19744                         return operandAssociativity === 0 /* Left */;
19745                     }
19746             }
19747         }
19748         /**
19749          * Determines whether a binary operator is mathematically associative.
19750          *
19751          * @param binaryOperator The binary operator.
19752          */
19753         function operatorHasAssociativeProperty(binaryOperator) {
19754             // The following operators are associative in JavaScript:
19755             //  (a*b)*c     -> a*(b*c)  -> a*b*c
19756             //  (a|b)|c     -> a|(b|c)  -> a|b|c
19757             //  (a&b)&c     -> a&(b&c)  -> a&b&c
19758             //  (a^b)^c     -> a^(b^c)  -> a^b^c
19759             //
19760             // While addition is associative in mathematics, JavaScript's `+` is not
19761             // guaranteed to be associative as it is overloaded with string concatenation.
19762             return binaryOperator === 41 /* AsteriskToken */
19763                 || binaryOperator === 51 /* BarToken */
19764                 || binaryOperator === 50 /* AmpersandToken */
19765                 || binaryOperator === 52 /* CaretToken */;
19766         }
19767         /**
19768          * This function determines whether an expression consists of a homogeneous set of
19769          * literal expressions or binary plus expressions that all share the same literal kind.
19770          * It is used to determine whether the right-hand operand of a binary plus expression can be
19771          * emitted without parentheses.
19772          */
19773         function getLiteralKindOfBinaryPlusOperand(node) {
19774             node = ts.skipPartiallyEmittedExpressions(node);
19775             if (ts.isLiteralKind(node.kind)) {
19776                 return node.kind;
19777             }
19778             if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
19779                 if (node.cachedLiteralKind !== undefined) {
19780                     return node.cachedLiteralKind;
19781                 }
19782                 var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
19783                 var literalKind = ts.isLiteralKind(leftKind)
19784                     && leftKind === getLiteralKindOfBinaryPlusOperand(node.right)
19785                     ? leftKind
19786                     : 0 /* Unknown */;
19787                 node.cachedLiteralKind = literalKind;
19788                 return literalKind;
19789             }
19790             return 0 /* Unknown */;
19791         }
19792         /**
19793          * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
19794          * order of operations.
19795          *
19796          * @param binaryOperator The operator for the BinaryExpression.
19797          * @param operand The operand for the BinaryExpression.
19798          * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
19799          *                           BinaryExpression.
19800          */
19801         function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
19802             var skipped = ts.skipPartiallyEmittedExpressions(operand);
19803             // If the resulting expression is already parenthesized, we do not need to do any further processing.
19804             if (skipped.kind === 207 /* ParenthesizedExpression */) {
19805                 return operand;
19806             }
19807             return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
19808                 ? factory.createParenthesizedExpression(operand)
19809                 : operand;
19810         }
19811         function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) {
19812             return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ true);
19813         }
19814         function parenthesizeRightSideOfBinary(binaryOperator, leftSide, rightSide) {
19815             return parenthesizeBinaryOperand(binaryOperator, rightSide, /*isLeftSideOfBinary*/ false, leftSide);
19816         }
19817         function parenthesizeExpressionOfComputedPropertyName(expression) {
19818             return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression;
19819         }
19820         function parenthesizeConditionOfConditionalExpression(condition) {
19821             var conditionalPrecedence = ts.getOperatorPrecedence(217 /* ConditionalExpression */, 57 /* QuestionToken */);
19822             var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
19823             var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
19824             if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
19825                 return factory.createParenthesizedExpression(condition);
19826             }
19827             return condition;
19828         }
19829         function parenthesizeBranchOfConditionalExpression(branch) {
19830             // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
19831             // so in case when comma expression is introduced as a part of previous transformations
19832             // if should be wrapped in parens since comma operator has the lowest precedence
19833             var emittedExpression = ts.skipPartiallyEmittedExpressions(branch);
19834             return ts.isCommaSequence(emittedExpression)
19835                 ? factory.createParenthesizedExpression(branch)
19836                 : branch;
19837         }
19838         /**
19839          *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
19840          *  has a lookahead restriction for `function`, `async function`, and `class`.
19841          *
19842          * Basically, that means we need to parenthesize in the following cases:
19843          *
19844          * - BinaryExpression of CommaToken
19845          * - CommaList (synthetic list of multiple comma expressions)
19846          * - FunctionExpression
19847          * - ClassExpression
19848          */
19849         function parenthesizeExpressionOfExportDefault(expression) {
19850             var check = ts.skipPartiallyEmittedExpressions(expression);
19851             var needsParens = ts.isCommaSequence(check);
19852             if (!needsParens) {
19853                 switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
19854                     case 221 /* ClassExpression */:
19855                     case 208 /* FunctionExpression */:
19856                         needsParens = true;
19857                 }
19858             }
19859             return needsParens ? factory.createParenthesizedExpression(expression) : expression;
19860         }
19861         /**
19862          * Wraps an expression in parentheses if it is needed in order to use the expression
19863          * as the expression of a `NewExpression` node.
19864          */
19865         function parenthesizeExpressionOfNew(expression) {
19866             var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
19867             switch (leftmostExpr.kind) {
19868                 case 203 /* CallExpression */:
19869                     return factory.createParenthesizedExpression(expression);
19870                 case 204 /* NewExpression */:
19871                     return !leftmostExpr.arguments
19872                         ? factory.createParenthesizedExpression(expression)
19873                         : expression; // TODO(rbuckton): Verify this assertion holds
19874             }
19875             return parenthesizeLeftSideOfAccess(expression);
19876         }
19877         /**
19878          * Wraps an expression in parentheses if it is needed in order to use the expression for
19879          * property or element access.
19880          */
19881         function parenthesizeLeftSideOfAccess(expression) {
19882             // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
19883             // to parenthesize the expression before a dot. The known exception is:
19884             //
19885             //    NewExpression:
19886             //       new C.x        -> not the same as (new C).x
19887             //
19888             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
19889             if (ts.isLeftHandSideExpression(emittedExpression)
19890                 && (emittedExpression.kind !== 204 /* NewExpression */ || emittedExpression.arguments)) {
19891                 // TODO(rbuckton): Verify whether this assertion holds.
19892                 return expression;
19893             }
19894             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19895             return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
19896         }
19897         function parenthesizeOperandOfPostfixUnary(operand) {
19898             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19899             return ts.isLeftHandSideExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
19900         }
19901         function parenthesizeOperandOfPrefixUnary(operand) {
19902             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19903             return ts.isUnaryExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
19904         }
19905         function parenthesizeExpressionsOfCommaDelimitedList(elements) {
19906             var result = ts.sameMap(elements, parenthesizeExpressionForDisallowedComma);
19907             return ts.setTextRange(factory.createNodeArray(result, elements.hasTrailingComma), elements);
19908         }
19909         function parenthesizeExpressionForDisallowedComma(expression) {
19910             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
19911             var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
19912             var commaPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, 27 /* CommaToken */);
19913             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19914             return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
19915         }
19916         function parenthesizeExpressionOfExpressionStatement(expression) {
19917             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
19918             if (ts.isCallExpression(emittedExpression)) {
19919                 var callee = emittedExpression.expression;
19920                 var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
19921                 if (kind === 208 /* FunctionExpression */ || kind === 209 /* ArrowFunction */) {
19922                     // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19923                     var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments);
19924                     return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */);
19925                 }
19926             }
19927             var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
19928             if (leftmostExpressionKind === 200 /* ObjectLiteralExpression */ || leftmostExpressionKind === 208 /* FunctionExpression */) {
19929                 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19930                 return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
19931             }
19932             return expression;
19933         }
19934         function parenthesizeConciseBodyOfArrowFunction(body) {
19935             if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 200 /* ObjectLiteralExpression */)) {
19936                 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19937                 return ts.setTextRange(factory.createParenthesizedExpression(body), body);
19938             }
19939             return body;
19940         }
19941         function parenthesizeMemberOfConditionalType(member) {
19942             return member.kind === 184 /* ConditionalType */ ? factory.createParenthesizedType(member) : member;
19943         }
19944         function parenthesizeMemberOfElementType(member) {
19945             switch (member.kind) {
19946                 case 182 /* UnionType */:
19947                 case 183 /* IntersectionType */:
19948                 case 174 /* FunctionType */:
19949                 case 175 /* ConstructorType */:
19950                     return factory.createParenthesizedType(member);
19951             }
19952             return parenthesizeMemberOfConditionalType(member);
19953         }
19954         function parenthesizeElementTypeOfArrayType(member) {
19955             switch (member.kind) {
19956                 case 176 /* TypeQuery */:
19957                 case 188 /* TypeOperator */:
19958                 case 185 /* InferType */:
19959                     return factory.createParenthesizedType(member);
19960             }
19961             return parenthesizeMemberOfElementType(member);
19962         }
19963         function parenthesizeConstituentTypesOfUnionOrIntersectionType(members) {
19964             return factory.createNodeArray(ts.sameMap(members, parenthesizeMemberOfElementType));
19965         }
19966         function parenthesizeOrdinalTypeArgument(node, i) {
19967             return i === 0 && ts.isFunctionOrConstructorTypeNode(node) && node.typeParameters ? factory.createParenthesizedType(node) : node;
19968         }
19969         function parenthesizeTypeArguments(typeArguments) {
19970             if (ts.some(typeArguments)) {
19971                 return factory.createNodeArray(ts.sameMap(typeArguments, parenthesizeOrdinalTypeArgument));
19972             }
19973         }
19974     }
19975     ts.createParenthesizerRules = createParenthesizerRules;
19976     ts.nullParenthesizerRules = {
19977         parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; },
19978         parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; },
19979         parenthesizeExpressionOfComputedPropertyName: ts.identity,
19980         parenthesizeConditionOfConditionalExpression: ts.identity,
19981         parenthesizeBranchOfConditionalExpression: ts.identity,
19982         parenthesizeExpressionOfExportDefault: ts.identity,
19983         parenthesizeExpressionOfNew: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
19984         parenthesizeLeftSideOfAccess: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
19985         parenthesizeOperandOfPostfixUnary: function (operand) { return ts.cast(operand, ts.isLeftHandSideExpression); },
19986         parenthesizeOperandOfPrefixUnary: function (operand) { return ts.cast(operand, ts.isUnaryExpression); },
19987         parenthesizeExpressionsOfCommaDelimitedList: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
19988         parenthesizeExpressionForDisallowedComma: ts.identity,
19989         parenthesizeExpressionOfExpressionStatement: ts.identity,
19990         parenthesizeConciseBodyOfArrowFunction: ts.identity,
19991         parenthesizeMemberOfConditionalType: ts.identity,
19992         parenthesizeMemberOfElementType: ts.identity,
19993         parenthesizeElementTypeOfArrayType: ts.identity,
19994         parenthesizeConstituentTypesOfUnionOrIntersectionType: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
19995         parenthesizeTypeArguments: function (nodes) { return nodes && ts.cast(nodes, ts.isNodeArray); },
19996     };
19997 })(ts || (ts = {}));
19998 /* @internal */
19999 var ts;
20000 (function (ts) {
20001     function createNodeConverters(factory) {
20002         return {
20003             convertToFunctionBlock: convertToFunctionBlock,
20004             convertToFunctionExpression: convertToFunctionExpression,
20005             convertToArrayAssignmentElement: convertToArrayAssignmentElement,
20006             convertToObjectAssignmentElement: convertToObjectAssignmentElement,
20007             convertToAssignmentPattern: convertToAssignmentPattern,
20008             convertToObjectAssignmentPattern: convertToObjectAssignmentPattern,
20009             convertToArrayAssignmentPattern: convertToArrayAssignmentPattern,
20010             convertToAssignmentElementTarget: convertToAssignmentElementTarget,
20011         };
20012         function convertToFunctionBlock(node, multiLine) {
20013             if (ts.isBlock(node))
20014                 return node;
20015             var returnStatement = factory.createReturnStatement(node);
20016             ts.setTextRange(returnStatement, node);
20017             var body = factory.createBlock([returnStatement], multiLine);
20018             ts.setTextRange(body, node);
20019             return body;
20020         }
20021         function convertToFunctionExpression(node) {
20022             if (!node.body)
20023                 return ts.Debug.fail("Cannot convert a FunctionDeclaration without a body");
20024             var updated = factory.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
20025             ts.setOriginalNode(updated, node);
20026             ts.setTextRange(updated, node);
20027             if (ts.getStartsOnNewLine(node)) {
20028                 ts.setStartsOnNewLine(updated, /*newLine*/ true);
20029             }
20030             return updated;
20031         }
20032         function convertToArrayAssignmentElement(element) {
20033             if (ts.isBindingElement(element)) {
20034                 if (element.dotDotDotToken) {
20035                     ts.Debug.assertNode(element.name, ts.isIdentifier);
20036                     return ts.setOriginalNode(ts.setTextRange(factory.createSpreadElement(element.name), element), element);
20037                 }
20038                 var expression = convertToAssignmentElementTarget(element.name);
20039                 return element.initializer
20040                     ? ts.setOriginalNode(ts.setTextRange(factory.createAssignment(expression, element.initializer), element), element)
20041                     : expression;
20042             }
20043             return ts.cast(element, ts.isExpression);
20044         }
20045         function convertToObjectAssignmentElement(element) {
20046             if (ts.isBindingElement(element)) {
20047                 if (element.dotDotDotToken) {
20048                     ts.Debug.assertNode(element.name, ts.isIdentifier);
20049                     return ts.setOriginalNode(ts.setTextRange(factory.createSpreadAssignment(element.name), element), element);
20050                 }
20051                 if (element.propertyName) {
20052                     var expression = convertToAssignmentElementTarget(element.name);
20053                     return ts.setOriginalNode(ts.setTextRange(factory.createPropertyAssignment(element.propertyName, element.initializer ? factory.createAssignment(expression, element.initializer) : expression), element), element);
20054                 }
20055                 ts.Debug.assertNode(element.name, ts.isIdentifier);
20056                 return ts.setOriginalNode(ts.setTextRange(factory.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
20057             }
20058             return ts.cast(element, ts.isObjectLiteralElementLike);
20059         }
20060         function convertToAssignmentPattern(node) {
20061             switch (node.kind) {
20062                 case 197 /* ArrayBindingPattern */:
20063                 case 199 /* ArrayLiteralExpression */:
20064                     return convertToArrayAssignmentPattern(node);
20065                 case 196 /* ObjectBindingPattern */:
20066                 case 200 /* ObjectLiteralExpression */:
20067                     return convertToObjectAssignmentPattern(node);
20068             }
20069         }
20070         function convertToObjectAssignmentPattern(node) {
20071             if (ts.isObjectBindingPattern(node)) {
20072                 return ts.setOriginalNode(ts.setTextRange(factory.createObjectLiteralExpression(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
20073             }
20074             return ts.cast(node, ts.isObjectLiteralExpression);
20075         }
20076         function convertToArrayAssignmentPattern(node) {
20077             if (ts.isArrayBindingPattern(node)) {
20078                 return ts.setOriginalNode(ts.setTextRange(factory.createArrayLiteralExpression(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
20079             }
20080             return ts.cast(node, ts.isArrayLiteralExpression);
20081         }
20082         function convertToAssignmentElementTarget(node) {
20083             if (ts.isBindingPattern(node)) {
20084                 return convertToAssignmentPattern(node);
20085             }
20086             return ts.cast(node, ts.isExpression);
20087         }
20088     }
20089     ts.createNodeConverters = createNodeConverters;
20090     ts.nullNodeConverters = {
20091         convertToFunctionBlock: ts.notImplemented,
20092         convertToFunctionExpression: ts.notImplemented,
20093         convertToArrayAssignmentElement: ts.notImplemented,
20094         convertToObjectAssignmentElement: ts.notImplemented,
20095         convertToAssignmentPattern: ts.notImplemented,
20096         convertToObjectAssignmentPattern: ts.notImplemented,
20097         convertToArrayAssignmentPattern: ts.notImplemented,
20098         convertToAssignmentElementTarget: ts.notImplemented,
20099     };
20100 })(ts || (ts = {}));
20101 var ts;
20102 (function (ts) {
20103     var nextAutoGenerateId = 0;
20104     /* @internal */
20105     var NodeFactoryFlags;
20106     (function (NodeFactoryFlags) {
20107         NodeFactoryFlags[NodeFactoryFlags["None"] = 0] = "None";
20108         // Disables the parenthesizer rules for the factory.
20109         NodeFactoryFlags[NodeFactoryFlags["NoParenthesizerRules"] = 1] = "NoParenthesizerRules";
20110         // Disables the node converters for the factory.
20111         NodeFactoryFlags[NodeFactoryFlags["NoNodeConverters"] = 2] = "NoNodeConverters";
20112         // Ensures new `PropertyAccessExpression` nodes are created with the `NoIndentation` emit flag set.
20113         NodeFactoryFlags[NodeFactoryFlags["NoIndentationOnFreshPropertyAccess"] = 4] = "NoIndentationOnFreshPropertyAccess";
20114         // Do not set an `original` pointer when updating a node.
20115         NodeFactoryFlags[NodeFactoryFlags["NoOriginalNode"] = 8] = "NoOriginalNode";
20116     })(NodeFactoryFlags = ts.NodeFactoryFlags || (ts.NodeFactoryFlags = {}));
20117     /**
20118      * Creates a `NodeFactory` that can be used to create and update a syntax tree.
20119      * @param flags Flags that control factory behavior.
20120      * @param baseFactory A `BaseNodeFactory` used to create the base `Node` objects.
20121      */
20122     /* @internal */
20123     function createNodeFactory(flags, baseFactory) {
20124         var update = flags & 8 /* NoOriginalNode */ ? updateWithoutOriginal : updateWithOriginal;
20125         // Lazily load the parenthesizer, node converters, and some factory methods until they are used.
20126         var parenthesizerRules = ts.memoize(function () { return flags & 1 /* NoParenthesizerRules */ ? ts.nullParenthesizerRules : ts.createParenthesizerRules(factory); });
20127         var converters = ts.memoize(function () { return flags & 2 /* NoNodeConverters */ ? ts.nullNodeConverters : ts.createNodeConverters(factory); });
20128         // lazy initializaton of common operator factories
20129         var getBinaryCreateFunction = ts.memoizeOne(function (operator) { return function (left, right) { return createBinaryExpression(left, operator, right); }; });
20130         var getPrefixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPrefixUnaryExpression(operator, operand); }; });
20131         var getPostfixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPostfixUnaryExpression(operand, operator); }; });
20132         var getJSDocPrimaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function () { return createJSDocPrimaryTypeWorker(kind); }; });
20133         var getJSDocUnaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function (type) { return createJSDocUnaryTypeWorker(kind, type); }; });
20134         var getJSDocUnaryTypeUpdateFunction = ts.memoizeOne(function (kind) { return function (node, type) { return updateJSDocUnaryTypeWorker(kind, node, type); }; });
20135         var getJSDocSimpleTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, comment) { return createJSDocSimpleTagWorker(kind, tagName, comment); }; });
20136         var getJSDocSimpleTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, comment) { return updateJSDocSimpleTagWorker(kind, node, tagName, comment); }; });
20137         var getJSDocTypeLikeTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, typeExpression, comment) { return createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment); }; });
20138         var getJSDocTypeLikeTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, typeExpression, comment) { return updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment); }; });
20139         var factory = {
20140             get parenthesizer() { return parenthesizerRules(); },
20141             get converters() { return converters(); },
20142             createNodeArray: createNodeArray,
20143             createNumericLiteral: createNumericLiteral,
20144             createBigIntLiteral: createBigIntLiteral,
20145             createStringLiteral: createStringLiteral,
20146             createStringLiteralFromNode: createStringLiteralFromNode,
20147             createRegularExpressionLiteral: createRegularExpressionLiteral,
20148             createLiteralLikeNode: createLiteralLikeNode,
20149             createIdentifier: createIdentifier,
20150             updateIdentifier: updateIdentifier,
20151             createTempVariable: createTempVariable,
20152             createLoopVariable: createLoopVariable,
20153             createUniqueName: createUniqueName,
20154             getGeneratedNameForNode: getGeneratedNameForNode,
20155             createPrivateIdentifier: createPrivateIdentifier,
20156             createToken: createToken,
20157             createSuper: createSuper,
20158             createThis: createThis,
20159             createNull: createNull,
20160             createTrue: createTrue,
20161             createFalse: createFalse,
20162             createModifier: createModifier,
20163             createModifiersFromModifierFlags: createModifiersFromModifierFlags,
20164             createQualifiedName: createQualifiedName,
20165             updateQualifiedName: updateQualifiedName,
20166             createComputedPropertyName: createComputedPropertyName,
20167             updateComputedPropertyName: updateComputedPropertyName,
20168             createTypeParameterDeclaration: createTypeParameterDeclaration,
20169             updateTypeParameterDeclaration: updateTypeParameterDeclaration,
20170             createParameterDeclaration: createParameterDeclaration,
20171             updateParameterDeclaration: updateParameterDeclaration,
20172             createDecorator: createDecorator,
20173             updateDecorator: updateDecorator,
20174             createPropertySignature: createPropertySignature,
20175             updatePropertySignature: updatePropertySignature,
20176             createPropertyDeclaration: createPropertyDeclaration,
20177             updatePropertyDeclaration: updatePropertyDeclaration,
20178             createMethodSignature: createMethodSignature,
20179             updateMethodSignature: updateMethodSignature,
20180             createMethodDeclaration: createMethodDeclaration,
20181             updateMethodDeclaration: updateMethodDeclaration,
20182             createConstructorDeclaration: createConstructorDeclaration,
20183             updateConstructorDeclaration: updateConstructorDeclaration,
20184             createGetAccessorDeclaration: createGetAccessorDeclaration,
20185             updateGetAccessorDeclaration: updateGetAccessorDeclaration,
20186             createSetAccessorDeclaration: createSetAccessorDeclaration,
20187             updateSetAccessorDeclaration: updateSetAccessorDeclaration,
20188             createCallSignature: createCallSignature,
20189             updateCallSignature: updateCallSignature,
20190             createConstructSignature: createConstructSignature,
20191             updateConstructSignature: updateConstructSignature,
20192             createIndexSignature: createIndexSignature,
20193             updateIndexSignature: updateIndexSignature,
20194             createTemplateLiteralTypeSpan: createTemplateLiteralTypeSpan,
20195             updateTemplateLiteralTypeSpan: updateTemplateLiteralTypeSpan,
20196             createKeywordTypeNode: createKeywordTypeNode,
20197             createTypePredicateNode: createTypePredicateNode,
20198             updateTypePredicateNode: updateTypePredicateNode,
20199             createTypeReferenceNode: createTypeReferenceNode,
20200             updateTypeReferenceNode: updateTypeReferenceNode,
20201             createFunctionTypeNode: createFunctionTypeNode,
20202             updateFunctionTypeNode: updateFunctionTypeNode,
20203             createConstructorTypeNode: createConstructorTypeNode,
20204             updateConstructorTypeNode: updateConstructorTypeNode,
20205             createTypeQueryNode: createTypeQueryNode,
20206             updateTypeQueryNode: updateTypeQueryNode,
20207             createTypeLiteralNode: createTypeLiteralNode,
20208             updateTypeLiteralNode: updateTypeLiteralNode,
20209             createArrayTypeNode: createArrayTypeNode,
20210             updateArrayTypeNode: updateArrayTypeNode,
20211             createTupleTypeNode: createTupleTypeNode,
20212             updateTupleTypeNode: updateTupleTypeNode,
20213             createNamedTupleMember: createNamedTupleMember,
20214             updateNamedTupleMember: updateNamedTupleMember,
20215             createOptionalTypeNode: createOptionalTypeNode,
20216             updateOptionalTypeNode: updateOptionalTypeNode,
20217             createRestTypeNode: createRestTypeNode,
20218             updateRestTypeNode: updateRestTypeNode,
20219             createUnionTypeNode: createUnionTypeNode,
20220             updateUnionTypeNode: updateUnionTypeNode,
20221             createIntersectionTypeNode: createIntersectionTypeNode,
20222             updateIntersectionTypeNode: updateIntersectionTypeNode,
20223             createConditionalTypeNode: createConditionalTypeNode,
20224             updateConditionalTypeNode: updateConditionalTypeNode,
20225             createInferTypeNode: createInferTypeNode,
20226             updateInferTypeNode: updateInferTypeNode,
20227             createImportTypeNode: createImportTypeNode,
20228             updateImportTypeNode: updateImportTypeNode,
20229             createParenthesizedType: createParenthesizedType,
20230             updateParenthesizedType: updateParenthesizedType,
20231             createThisTypeNode: createThisTypeNode,
20232             createTypeOperatorNode: createTypeOperatorNode,
20233             updateTypeOperatorNode: updateTypeOperatorNode,
20234             createIndexedAccessTypeNode: createIndexedAccessTypeNode,
20235             updateIndexedAccessTypeNode: updateIndexedAccessTypeNode,
20236             createMappedTypeNode: createMappedTypeNode,
20237             updateMappedTypeNode: updateMappedTypeNode,
20238             createLiteralTypeNode: createLiteralTypeNode,
20239             updateLiteralTypeNode: updateLiteralTypeNode,
20240             createTemplateLiteralType: createTemplateLiteralType,
20241             updateTemplateLiteralType: updateTemplateLiteralType,
20242             createObjectBindingPattern: createObjectBindingPattern,
20243             updateObjectBindingPattern: updateObjectBindingPattern,
20244             createArrayBindingPattern: createArrayBindingPattern,
20245             updateArrayBindingPattern: updateArrayBindingPattern,
20246             createBindingElement: createBindingElement,
20247             updateBindingElement: updateBindingElement,
20248             createArrayLiteralExpression: createArrayLiteralExpression,
20249             updateArrayLiteralExpression: updateArrayLiteralExpression,
20250             createObjectLiteralExpression: createObjectLiteralExpression,
20251             updateObjectLiteralExpression: updateObjectLiteralExpression,
20252             createPropertyAccessExpression: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
20253                 function (expression, name) { return ts.setEmitFlags(createPropertyAccessExpression(expression, name), 131072 /* NoIndentation */); } :
20254                 createPropertyAccessExpression,
20255             updatePropertyAccessExpression: updatePropertyAccessExpression,
20256             createPropertyAccessChain: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
20257                 function (expression, questionDotToken, name) { return ts.setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), 131072 /* NoIndentation */); } :
20258                 createPropertyAccessChain,
20259             updatePropertyAccessChain: updatePropertyAccessChain,
20260             createElementAccessExpression: createElementAccessExpression,
20261             updateElementAccessExpression: updateElementAccessExpression,
20262             createElementAccessChain: createElementAccessChain,
20263             updateElementAccessChain: updateElementAccessChain,
20264             createCallExpression: createCallExpression,
20265             updateCallExpression: updateCallExpression,
20266             createCallChain: createCallChain,
20267             updateCallChain: updateCallChain,
20268             createNewExpression: createNewExpression,
20269             updateNewExpression: updateNewExpression,
20270             createTaggedTemplateExpression: createTaggedTemplateExpression,
20271             updateTaggedTemplateExpression: updateTaggedTemplateExpression,
20272             createTypeAssertion: createTypeAssertion,
20273             updateTypeAssertion: updateTypeAssertion,
20274             createParenthesizedExpression: createParenthesizedExpression,
20275             updateParenthesizedExpression: updateParenthesizedExpression,
20276             createFunctionExpression: createFunctionExpression,
20277             updateFunctionExpression: updateFunctionExpression,
20278             createArrowFunction: createArrowFunction,
20279             updateArrowFunction: updateArrowFunction,
20280             createDeleteExpression: createDeleteExpression,
20281             updateDeleteExpression: updateDeleteExpression,
20282             createTypeOfExpression: createTypeOfExpression,
20283             updateTypeOfExpression: updateTypeOfExpression,
20284             createVoidExpression: createVoidExpression,
20285             updateVoidExpression: updateVoidExpression,
20286             createAwaitExpression: createAwaitExpression,
20287             updateAwaitExpression: updateAwaitExpression,
20288             createPrefixUnaryExpression: createPrefixUnaryExpression,
20289             updatePrefixUnaryExpression: updatePrefixUnaryExpression,
20290             createPostfixUnaryExpression: createPostfixUnaryExpression,
20291             updatePostfixUnaryExpression: updatePostfixUnaryExpression,
20292             createBinaryExpression: createBinaryExpression,
20293             updateBinaryExpression: updateBinaryExpression,
20294             createConditionalExpression: createConditionalExpression,
20295             updateConditionalExpression: updateConditionalExpression,
20296             createTemplateExpression: createTemplateExpression,
20297             updateTemplateExpression: updateTemplateExpression,
20298             createTemplateHead: createTemplateHead,
20299             createTemplateMiddle: createTemplateMiddle,
20300             createTemplateTail: createTemplateTail,
20301             createNoSubstitutionTemplateLiteral: createNoSubstitutionTemplateLiteral,
20302             createTemplateLiteralLikeNode: createTemplateLiteralLikeNode,
20303             createYieldExpression: createYieldExpression,
20304             updateYieldExpression: updateYieldExpression,
20305             createSpreadElement: createSpreadElement,
20306             updateSpreadElement: updateSpreadElement,
20307             createClassExpression: createClassExpression,
20308             updateClassExpression: updateClassExpression,
20309             createOmittedExpression: createOmittedExpression,
20310             createExpressionWithTypeArguments: createExpressionWithTypeArguments,
20311             updateExpressionWithTypeArguments: updateExpressionWithTypeArguments,
20312             createAsExpression: createAsExpression,
20313             updateAsExpression: updateAsExpression,
20314             createNonNullExpression: createNonNullExpression,
20315             updateNonNullExpression: updateNonNullExpression,
20316             createNonNullChain: createNonNullChain,
20317             updateNonNullChain: updateNonNullChain,
20318             createMetaProperty: createMetaProperty,
20319             updateMetaProperty: updateMetaProperty,
20320             createTemplateSpan: createTemplateSpan,
20321             updateTemplateSpan: updateTemplateSpan,
20322             createSemicolonClassElement: createSemicolonClassElement,
20323             createBlock: createBlock,
20324             updateBlock: updateBlock,
20325             createVariableStatement: createVariableStatement,
20326             updateVariableStatement: updateVariableStatement,
20327             createEmptyStatement: createEmptyStatement,
20328             createExpressionStatement: createExpressionStatement,
20329             updateExpressionStatement: updateExpressionStatement,
20330             createIfStatement: createIfStatement,
20331             updateIfStatement: updateIfStatement,
20332             createDoStatement: createDoStatement,
20333             updateDoStatement: updateDoStatement,
20334             createWhileStatement: createWhileStatement,
20335             updateWhileStatement: updateWhileStatement,
20336             createForStatement: createForStatement,
20337             updateForStatement: updateForStatement,
20338             createForInStatement: createForInStatement,
20339             updateForInStatement: updateForInStatement,
20340             createForOfStatement: createForOfStatement,
20341             updateForOfStatement: updateForOfStatement,
20342             createContinueStatement: createContinueStatement,
20343             updateContinueStatement: updateContinueStatement,
20344             createBreakStatement: createBreakStatement,
20345             updateBreakStatement: updateBreakStatement,
20346             createReturnStatement: createReturnStatement,
20347             updateReturnStatement: updateReturnStatement,
20348             createWithStatement: createWithStatement,
20349             updateWithStatement: updateWithStatement,
20350             createSwitchStatement: createSwitchStatement,
20351             updateSwitchStatement: updateSwitchStatement,
20352             createLabeledStatement: createLabeledStatement,
20353             updateLabeledStatement: updateLabeledStatement,
20354             createThrowStatement: createThrowStatement,
20355             updateThrowStatement: updateThrowStatement,
20356             createTryStatement: createTryStatement,
20357             updateTryStatement: updateTryStatement,
20358             createDebuggerStatement: createDebuggerStatement,
20359             createVariableDeclaration: createVariableDeclaration,
20360             updateVariableDeclaration: updateVariableDeclaration,
20361             createVariableDeclarationList: createVariableDeclarationList,
20362             updateVariableDeclarationList: updateVariableDeclarationList,
20363             createFunctionDeclaration: createFunctionDeclaration,
20364             updateFunctionDeclaration: updateFunctionDeclaration,
20365             createClassDeclaration: createClassDeclaration,
20366             updateClassDeclaration: updateClassDeclaration,
20367             createInterfaceDeclaration: createInterfaceDeclaration,
20368             updateInterfaceDeclaration: updateInterfaceDeclaration,
20369             createTypeAliasDeclaration: createTypeAliasDeclaration,
20370             updateTypeAliasDeclaration: updateTypeAliasDeclaration,
20371             createEnumDeclaration: createEnumDeclaration,
20372             updateEnumDeclaration: updateEnumDeclaration,
20373             createModuleDeclaration: createModuleDeclaration,
20374             updateModuleDeclaration: updateModuleDeclaration,
20375             createModuleBlock: createModuleBlock,
20376             updateModuleBlock: updateModuleBlock,
20377             createCaseBlock: createCaseBlock,
20378             updateCaseBlock: updateCaseBlock,
20379             createNamespaceExportDeclaration: createNamespaceExportDeclaration,
20380             updateNamespaceExportDeclaration: updateNamespaceExportDeclaration,
20381             createImportEqualsDeclaration: createImportEqualsDeclaration,
20382             updateImportEqualsDeclaration: updateImportEqualsDeclaration,
20383             createImportDeclaration: createImportDeclaration,
20384             updateImportDeclaration: updateImportDeclaration,
20385             createImportClause: createImportClause,
20386             updateImportClause: updateImportClause,
20387             createNamespaceImport: createNamespaceImport,
20388             updateNamespaceImport: updateNamespaceImport,
20389             createNamespaceExport: createNamespaceExport,
20390             updateNamespaceExport: updateNamespaceExport,
20391             createNamedImports: createNamedImports,
20392             updateNamedImports: updateNamedImports,
20393             createImportSpecifier: createImportSpecifier,
20394             updateImportSpecifier: updateImportSpecifier,
20395             createExportAssignment: createExportAssignment,
20396             updateExportAssignment: updateExportAssignment,
20397             createExportDeclaration: createExportDeclaration,
20398             updateExportDeclaration: updateExportDeclaration,
20399             createNamedExports: createNamedExports,
20400             updateNamedExports: updateNamedExports,
20401             createExportSpecifier: createExportSpecifier,
20402             updateExportSpecifier: updateExportSpecifier,
20403             createMissingDeclaration: createMissingDeclaration,
20404             createExternalModuleReference: createExternalModuleReference,
20405             updateExternalModuleReference: updateExternalModuleReference,
20406             // lazily load factory members for JSDoc types with similar structure
20407             get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(303 /* JSDocAllType */); },
20408             get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocUnknownType */); },
20409             get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNonNullableType */); },
20410             get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNonNullableType */); },
20411             get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(305 /* JSDocNullableType */); },
20412             get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(305 /* JSDocNullableType */); },
20413             get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocOptionalType */); },
20414             get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocOptionalType */); },
20415             get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(309 /* JSDocVariadicType */); },
20416             get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(309 /* JSDocVariadicType */); },
20417             get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocNamepathType */); },
20418             get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocNamepathType */); },
20419             createJSDocFunctionType: createJSDocFunctionType,
20420             updateJSDocFunctionType: updateJSDocFunctionType,
20421             createJSDocTypeLiteral: createJSDocTypeLiteral,
20422             updateJSDocTypeLiteral: updateJSDocTypeLiteral,
20423             createJSDocTypeExpression: createJSDocTypeExpression,
20424             updateJSDocTypeExpression: updateJSDocTypeExpression,
20425             createJSDocSignature: createJSDocSignature,
20426             updateJSDocSignature: updateJSDocSignature,
20427             createJSDocTemplateTag: createJSDocTemplateTag,
20428             updateJSDocTemplateTag: updateJSDocTemplateTag,
20429             createJSDocTypedefTag: createJSDocTypedefTag,
20430             updateJSDocTypedefTag: updateJSDocTypedefTag,
20431             createJSDocParameterTag: createJSDocParameterTag,
20432             updateJSDocParameterTag: updateJSDocParameterTag,
20433             createJSDocPropertyTag: createJSDocPropertyTag,
20434             updateJSDocPropertyTag: updateJSDocPropertyTag,
20435             createJSDocCallbackTag: createJSDocCallbackTag,
20436             updateJSDocCallbackTag: updateJSDocCallbackTag,
20437             createJSDocAugmentsTag: createJSDocAugmentsTag,
20438             updateJSDocAugmentsTag: updateJSDocAugmentsTag,
20439             createJSDocImplementsTag: createJSDocImplementsTag,
20440             updateJSDocImplementsTag: updateJSDocImplementsTag,
20441             createJSDocSeeTag: createJSDocSeeTag,
20442             updateJSDocSeeTag: updateJSDocSeeTag,
20443             createJSDocNameReference: createJSDocNameReference,
20444             updateJSDocNameReference: updateJSDocNameReference,
20445             // lazily load factory members for JSDoc tags with similar structure
20446             get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocTypeTag */); },
20447             get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocTypeTag */); },
20448             get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(327 /* JSDocReturnTag */); },
20449             get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(327 /* JSDocReturnTag */); },
20450             get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(328 /* JSDocThisTag */); },
20451             get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(328 /* JSDocThisTag */); },
20452             get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(325 /* JSDocEnumTag */); },
20453             get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(325 /* JSDocEnumTag */); },
20454             get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(317 /* JSDocAuthorTag */); },
20455             get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(317 /* JSDocAuthorTag */); },
20456             get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(319 /* JSDocClassTag */); },
20457             get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(319 /* JSDocClassTag */); },
20458             get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocPublicTag */); },
20459             get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocPublicTag */); },
20460             get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocPrivateTag */); },
20461             get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocPrivateTag */); },
20462             get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocProtectedTag */); },
20463             get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocProtectedTag */); },
20464             get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocReadonlyTag */); },
20465             get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocReadonlyTag */); },
20466             get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(318 /* JSDocDeprecatedTag */); },
20467             get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(318 /* JSDocDeprecatedTag */); },
20468             createJSDocUnknownTag: createJSDocUnknownTag,
20469             updateJSDocUnknownTag: updateJSDocUnknownTag,
20470             createJSDocComment: createJSDocComment,
20471             updateJSDocComment: updateJSDocComment,
20472             createJsxElement: createJsxElement,
20473             updateJsxElement: updateJsxElement,
20474             createJsxSelfClosingElement: createJsxSelfClosingElement,
20475             updateJsxSelfClosingElement: updateJsxSelfClosingElement,
20476             createJsxOpeningElement: createJsxOpeningElement,
20477             updateJsxOpeningElement: updateJsxOpeningElement,
20478             createJsxClosingElement: createJsxClosingElement,
20479             updateJsxClosingElement: updateJsxClosingElement,
20480             createJsxFragment: createJsxFragment,
20481             createJsxText: createJsxText,
20482             updateJsxText: updateJsxText,
20483             createJsxOpeningFragment: createJsxOpeningFragment,
20484             createJsxJsxClosingFragment: createJsxJsxClosingFragment,
20485             updateJsxFragment: updateJsxFragment,
20486             createJsxAttribute: createJsxAttribute,
20487             updateJsxAttribute: updateJsxAttribute,
20488             createJsxAttributes: createJsxAttributes,
20489             updateJsxAttributes: updateJsxAttributes,
20490             createJsxSpreadAttribute: createJsxSpreadAttribute,
20491             updateJsxSpreadAttribute: updateJsxSpreadAttribute,
20492             createJsxExpression: createJsxExpression,
20493             updateJsxExpression: updateJsxExpression,
20494             createCaseClause: createCaseClause,
20495             updateCaseClause: updateCaseClause,
20496             createDefaultClause: createDefaultClause,
20497             updateDefaultClause: updateDefaultClause,
20498             createHeritageClause: createHeritageClause,
20499             updateHeritageClause: updateHeritageClause,
20500             createCatchClause: createCatchClause,
20501             updateCatchClause: updateCatchClause,
20502             createPropertyAssignment: createPropertyAssignment,
20503             updatePropertyAssignment: updatePropertyAssignment,
20504             createShorthandPropertyAssignment: createShorthandPropertyAssignment,
20505             updateShorthandPropertyAssignment: updateShorthandPropertyAssignment,
20506             createSpreadAssignment: createSpreadAssignment,
20507             updateSpreadAssignment: updateSpreadAssignment,
20508             createEnumMember: createEnumMember,
20509             updateEnumMember: updateEnumMember,
20510             createSourceFile: createSourceFile,
20511             updateSourceFile: updateSourceFile,
20512             createBundle: createBundle,
20513             updateBundle: updateBundle,
20514             createUnparsedSource: createUnparsedSource,
20515             createUnparsedPrologue: createUnparsedPrologue,
20516             createUnparsedPrepend: createUnparsedPrepend,
20517             createUnparsedTextLike: createUnparsedTextLike,
20518             createUnparsedSyntheticReference: createUnparsedSyntheticReference,
20519             createInputFiles: createInputFiles,
20520             createSyntheticExpression: createSyntheticExpression,
20521             createSyntaxList: createSyntaxList,
20522             createNotEmittedStatement: createNotEmittedStatement,
20523             createPartiallyEmittedExpression: createPartiallyEmittedExpression,
20524             updatePartiallyEmittedExpression: updatePartiallyEmittedExpression,
20525             createCommaListExpression: createCommaListExpression,
20526             updateCommaListExpression: updateCommaListExpression,
20527             createEndOfDeclarationMarker: createEndOfDeclarationMarker,
20528             createMergeDeclarationMarker: createMergeDeclarationMarker,
20529             createSyntheticReferenceExpression: createSyntheticReferenceExpression,
20530             updateSyntheticReferenceExpression: updateSyntheticReferenceExpression,
20531             cloneNode: cloneNode,
20532             // Lazily load factory methods for common operator factories and utilities
20533             get createComma() { return getBinaryCreateFunction(27 /* CommaToken */); },
20534             get createAssignment() { return getBinaryCreateFunction(62 /* EqualsToken */); },
20535             get createLogicalOr() { return getBinaryCreateFunction(56 /* BarBarToken */); },
20536             get createLogicalAnd() { return getBinaryCreateFunction(55 /* AmpersandAmpersandToken */); },
20537             get createBitwiseOr() { return getBinaryCreateFunction(51 /* BarToken */); },
20538             get createBitwiseXor() { return getBinaryCreateFunction(52 /* CaretToken */); },
20539             get createBitwiseAnd() { return getBinaryCreateFunction(50 /* AmpersandToken */); },
20540             get createStrictEquality() { return getBinaryCreateFunction(36 /* EqualsEqualsEqualsToken */); },
20541             get createStrictInequality() { return getBinaryCreateFunction(37 /* ExclamationEqualsEqualsToken */); },
20542             get createEquality() { return getBinaryCreateFunction(34 /* EqualsEqualsToken */); },
20543             get createInequality() { return getBinaryCreateFunction(35 /* ExclamationEqualsToken */); },
20544             get createLessThan() { return getBinaryCreateFunction(29 /* LessThanToken */); },
20545             get createLessThanEquals() { return getBinaryCreateFunction(32 /* LessThanEqualsToken */); },
20546             get createGreaterThan() { return getBinaryCreateFunction(31 /* GreaterThanToken */); },
20547             get createGreaterThanEquals() { return getBinaryCreateFunction(33 /* GreaterThanEqualsToken */); },
20548             get createLeftShift() { return getBinaryCreateFunction(47 /* LessThanLessThanToken */); },
20549             get createRightShift() { return getBinaryCreateFunction(48 /* GreaterThanGreaterThanToken */); },
20550             get createUnsignedRightShift() { return getBinaryCreateFunction(49 /* GreaterThanGreaterThanGreaterThanToken */); },
20551             get createAdd() { return getBinaryCreateFunction(39 /* PlusToken */); },
20552             get createSubtract() { return getBinaryCreateFunction(40 /* MinusToken */); },
20553             get createMultiply() { return getBinaryCreateFunction(41 /* AsteriskToken */); },
20554             get createDivide() { return getBinaryCreateFunction(43 /* SlashToken */); },
20555             get createModulo() { return getBinaryCreateFunction(44 /* PercentToken */); },
20556             get createExponent() { return getBinaryCreateFunction(42 /* AsteriskAsteriskToken */); },
20557             get createPrefixPlus() { return getPrefixUnaryCreateFunction(39 /* PlusToken */); },
20558             get createPrefixMinus() { return getPrefixUnaryCreateFunction(40 /* MinusToken */); },
20559             get createPrefixIncrement() { return getPrefixUnaryCreateFunction(45 /* PlusPlusToken */); },
20560             get createPrefixDecrement() { return getPrefixUnaryCreateFunction(46 /* MinusMinusToken */); },
20561             get createBitwiseNot() { return getPrefixUnaryCreateFunction(54 /* TildeToken */); },
20562             get createLogicalNot() { return getPrefixUnaryCreateFunction(53 /* ExclamationToken */); },
20563             get createPostfixIncrement() { return getPostfixUnaryCreateFunction(45 /* PlusPlusToken */); },
20564             get createPostfixDecrement() { return getPostfixUnaryCreateFunction(46 /* MinusMinusToken */); },
20565             // Compound nodes
20566             createImmediatelyInvokedFunctionExpression: createImmediatelyInvokedFunctionExpression,
20567             createImmediatelyInvokedArrowFunction: createImmediatelyInvokedArrowFunction,
20568             createVoidZero: createVoidZero,
20569             createExportDefault: createExportDefault,
20570             createExternalModuleExport: createExternalModuleExport,
20571             createTypeCheck: createTypeCheck,
20572             createMethodCall: createMethodCall,
20573             createGlobalMethodCall: createGlobalMethodCall,
20574             createFunctionBindCall: createFunctionBindCall,
20575             createFunctionCallCall: createFunctionCallCall,
20576             createFunctionApplyCall: createFunctionApplyCall,
20577             createArraySliceCall: createArraySliceCall,
20578             createArrayConcatCall: createArrayConcatCall,
20579             createObjectDefinePropertyCall: createObjectDefinePropertyCall,
20580             createPropertyDescriptor: createPropertyDescriptor,
20581             createCallBinding: createCallBinding,
20582             // Utilities
20583             inlineExpressions: inlineExpressions,
20584             getInternalName: getInternalName,
20585             getLocalName: getLocalName,
20586             getExportName: getExportName,
20587             getDeclarationName: getDeclarationName,
20588             getNamespaceMemberName: getNamespaceMemberName,
20589             getExternalModuleOrNamespaceExportName: getExternalModuleOrNamespaceExportName,
20590             restoreOuterExpressions: restoreOuterExpressions,
20591             restoreEnclosingLabel: restoreEnclosingLabel,
20592             createUseStrictPrologue: createUseStrictPrologue,
20593             copyPrologue: copyPrologue,
20594             copyStandardPrologue: copyStandardPrologue,
20595             copyCustomPrologue: copyCustomPrologue,
20596             ensureUseStrict: ensureUseStrict,
20597             liftToBlock: liftToBlock,
20598             mergeLexicalEnvironment: mergeLexicalEnvironment,
20599             updateModifiers: updateModifiers,
20600         };
20601         return factory;
20602         // @api
20603         function createNodeArray(elements, hasTrailingComma) {
20604             if (elements === undefined || elements === ts.emptyArray) {
20605                 elements = [];
20606             }
20607             else if (ts.isNodeArray(elements)) {
20608                 // Ensure the transform flags have been aggregated for this NodeArray
20609                 if (elements.transformFlags === undefined) {
20610                     aggregateChildrenFlags(elements);
20611                 }
20612                 ts.Debug.attachNodeArrayDebugInfo(elements);
20613                 return elements;
20614             }
20615             // Since the element list of a node array is typically created by starting with an empty array and
20616             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
20617             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
20618             var length = elements.length;
20619             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
20620             ts.setTextRangePosEnd(array, -1, -1);
20621             array.hasTrailingComma = !!hasTrailingComma;
20622             aggregateChildrenFlags(array);
20623             ts.Debug.attachNodeArrayDebugInfo(array);
20624             return array;
20625         }
20626         function createBaseNode(kind) {
20627             return baseFactory.createBaseNode(kind);
20628         }
20629         function createBaseDeclaration(kind, decorators, modifiers) {
20630             var node = createBaseNode(kind);
20631             node.decorators = asNodeArray(decorators);
20632             node.modifiers = asNodeArray(modifiers);
20633             node.transformFlags |=
20634                 propagateChildrenFlags(node.decorators) |
20635                     propagateChildrenFlags(node.modifiers);
20636             // NOTE: The following properties are commonly set by the binder and are added here to
20637             // ensure declarations have a stable shape.
20638             node.symbol = undefined; // initialized by binder
20639             node.localSymbol = undefined; // initialized by binder
20640             node.locals = undefined; // initialized by binder
20641             node.nextContainer = undefined; // initialized by binder
20642             return node;
20643         }
20644         function createBaseNamedDeclaration(kind, decorators, modifiers, name) {
20645             var node = createBaseDeclaration(kind, decorators, modifiers);
20646             name = asName(name);
20647             node.name = name;
20648             // The PropertyName of a member is allowed to be `await`.
20649             // We don't need to exclude `await` for type signatures since types
20650             // don't propagate child flags.
20651             if (name) {
20652                 switch (node.kind) {
20653                     case 165 /* MethodDeclaration */:
20654                     case 167 /* GetAccessor */:
20655                     case 168 /* SetAccessor */:
20656                     case 163 /* PropertyDeclaration */:
20657                     case 288 /* PropertyAssignment */:
20658                         if (ts.isIdentifier(name)) {
20659                             node.transformFlags |= propagateIdentifierNameFlags(name);
20660                             break;
20661                         }
20662                     // fall through
20663                     default:
20664                         node.transformFlags |= propagateChildFlags(name);
20665                         break;
20666                 }
20667             }
20668             return node;
20669         }
20670         function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) {
20671             var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
20672             node.typeParameters = asNodeArray(typeParameters);
20673             node.transformFlags |= propagateChildrenFlags(node.typeParameters);
20674             if (typeParameters)
20675                 node.transformFlags |= 1 /* ContainsTypeScript */;
20676             return node;
20677         }
20678         function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) {
20679             var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
20680             node.parameters = createNodeArray(parameters);
20681             node.type = type;
20682             node.transformFlags |=
20683                 propagateChildrenFlags(node.parameters) |
20684                     propagateChildFlags(node.type);
20685             if (type)
20686                 node.transformFlags |= 1 /* ContainsTypeScript */;
20687             return node;
20688         }
20689         function updateBaseSignatureDeclaration(updated, original) {
20690             // copy children used only for error reporting
20691             if (original.typeArguments)
20692                 updated.typeArguments = original.typeArguments;
20693             return update(updated, original);
20694         }
20695         function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) {
20696             var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type);
20697             node.body = body;
20698             node.transformFlags |= propagateChildFlags(node.body) & ~8388608 /* ContainsPossibleTopLevelAwait */;
20699             if (!body)
20700                 node.transformFlags |= 1 /* ContainsTypeScript */;
20701             return node;
20702         }
20703         function updateBaseFunctionLikeDeclaration(updated, original) {
20704             // copy children used only for error reporting
20705             if (original.exclamationToken)
20706                 updated.exclamationToken = original.exclamationToken;
20707             if (original.typeArguments)
20708                 updated.typeArguments = original.typeArguments;
20709             return updateBaseSignatureDeclaration(updated, original);
20710         }
20711         function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) {
20712             var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
20713             node.heritageClauses = asNodeArray(heritageClauses);
20714             node.transformFlags |= propagateChildrenFlags(node.heritageClauses);
20715             return node;
20716         }
20717         function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) {
20718             var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses);
20719             node.members = createNodeArray(members);
20720             node.transformFlags |= propagateChildrenFlags(node.members);
20721             return node;
20722         }
20723         function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) {
20724             var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
20725             node.initializer = initializer;
20726             node.transformFlags |= propagateChildFlags(node.initializer);
20727             return node;
20728         }
20729         function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) {
20730             var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer);
20731             node.type = type;
20732             node.transformFlags |= propagateChildFlags(type);
20733             if (type)
20734                 node.transformFlags |= 1 /* ContainsTypeScript */;
20735             return node;
20736         }
20737         //
20738         // Literals
20739         //
20740         function createBaseLiteral(kind, text) {
20741             var node = createBaseToken(kind);
20742             node.text = text;
20743             return node;
20744         }
20745         // @api
20746         function createNumericLiteral(value, numericLiteralFlags) {
20747             if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
20748             var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value);
20749             node.numericLiteralFlags = numericLiteralFlags;
20750             if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */)
20751                 node.transformFlags |= 256 /* ContainsES2015 */;
20752             return node;
20753         }
20754         // @api
20755         function createBigIntLiteral(value) {
20756             var node = createBaseLiteral(9 /* BigIntLiteral */, typeof value === "string" ? value : ts.pseudoBigIntToString(value) + "n");
20757             node.transformFlags |= 4 /* ContainsESNext */;
20758             return node;
20759         }
20760         function createBaseStringLiteral(text, isSingleQuote) {
20761             var node = createBaseLiteral(10 /* StringLiteral */, text);
20762             node.singleQuote = isSingleQuote;
20763             return node;
20764         }
20765         // @api
20766         function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) {
20767             var node = createBaseStringLiteral(text, isSingleQuote);
20768             node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
20769             if (hasExtendedUnicodeEscape)
20770                 node.transformFlags |= 256 /* ContainsES2015 */;
20771             return node;
20772         }
20773         // @api
20774         function createStringLiteralFromNode(sourceNode) {
20775             var node = createBaseStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode), /*isSingleQuote*/ undefined);
20776             node.textSourceNode = sourceNode;
20777             return node;
20778         }
20779         // @api
20780         function createRegularExpressionLiteral(text) {
20781             var node = createBaseLiteral(13 /* RegularExpressionLiteral */, text);
20782             return node;
20783         }
20784         // @api
20785         function createLiteralLikeNode(kind, text) {
20786             switch (kind) {
20787                 case 8 /* NumericLiteral */: return createNumericLiteral(text, /*numericLiteralFlags*/ 0);
20788                 case 9 /* BigIntLiteral */: return createBigIntLiteral(text);
20789                 case 10 /* StringLiteral */: return createStringLiteral(text, /*isSingleQuote*/ undefined);
20790                 case 11 /* JsxText */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false);
20791                 case 12 /* JsxTextAllWhiteSpaces */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true);
20792                 case 13 /* RegularExpressionLiteral */: return createRegularExpressionLiteral(text);
20793                 case 14 /* NoSubstitutionTemplateLiteral */: return createTemplateLiteralLikeNode(kind, text, /*rawText*/ undefined, /*templateFlags*/ 0);
20794             }
20795         }
20796         //
20797         // Identifiers
20798         //
20799         function createBaseIdentifier(text, originalKeywordKind) {
20800             if (originalKeywordKind === undefined && text) {
20801                 originalKeywordKind = ts.stringToToken(text);
20802             }
20803             if (originalKeywordKind === 78 /* Identifier */) {
20804                 originalKeywordKind = undefined;
20805             }
20806             var node = baseFactory.createBaseIdentifierNode(78 /* Identifier */);
20807             node.originalKeywordKind = originalKeywordKind;
20808             node.escapedText = ts.escapeLeadingUnderscores(text);
20809             return node;
20810         }
20811         function createBaseGeneratedIdentifier(text, autoGenerateFlags) {
20812             var node = createBaseIdentifier(text, /*originalKeywordKind*/ undefined);
20813             node.autoGenerateFlags = autoGenerateFlags;
20814             node.autoGenerateId = nextAutoGenerateId;
20815             nextAutoGenerateId++;
20816             return node;
20817         }
20818         // @api
20819         function createIdentifier(text, typeArguments, originalKeywordKind) {
20820             var node = createBaseIdentifier(text, originalKeywordKind);
20821             if (typeArguments) {
20822                 // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations
20823                 node.typeArguments = createNodeArray(typeArguments);
20824             }
20825             if (node.originalKeywordKind === 130 /* AwaitKeyword */) {
20826                 node.transformFlags |= 8388608 /* ContainsPossibleTopLevelAwait */;
20827             }
20828             return node;
20829         }
20830         // @api
20831         function updateIdentifier(node, typeArguments) {
20832             return node.typeArguments !== typeArguments
20833                 ? update(createIdentifier(ts.idText(node), typeArguments), node)
20834                 : node;
20835         }
20836         // @api
20837         function createTempVariable(recordTempVariable, reservedInNestedScopes) {
20838             var flags = 1 /* Auto */;
20839             if (reservedInNestedScopes)
20840                 flags |= 8 /* ReservedInNestedScopes */;
20841             var name = createBaseGeneratedIdentifier("", flags);
20842             if (recordTempVariable) {
20843                 recordTempVariable(name);
20844             }
20845             return name;
20846         }
20847         /** Create a unique temporary variable for use in a loop. */
20848         // @api
20849         function createLoopVariable() {
20850             return createBaseGeneratedIdentifier("", 2 /* Loop */);
20851         }
20852         /** Create a unique name based on the supplied text. */
20853         // @api
20854         function createUniqueName(text, flags) {
20855             if (flags === void 0) { flags = 0 /* None */; }
20856             ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
20857             ts.Debug.assert((flags & (16 /* Optimistic */ | 32 /* FileLevel */)) !== 32 /* FileLevel */, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic");
20858             return createBaseGeneratedIdentifier(text, 3 /* Unique */ | flags);
20859         }
20860         /** Create a unique name generated for a node. */
20861         // @api
20862         function getGeneratedNameForNode(node, flags) {
20863             if (flags === void 0) { flags = 0; }
20864             ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
20865             var name = createBaseGeneratedIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "", 4 /* Node */ | flags);
20866             name.original = node;
20867             return name;
20868         }
20869         // @api
20870         function createPrivateIdentifier(text) {
20871             if (!ts.startsWith(text, "#"))
20872                 ts.Debug.fail("First character of private identifier must be #: " + text);
20873             var node = baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */);
20874             node.escapedText = ts.escapeLeadingUnderscores(text);
20875             node.transformFlags |= 4194304 /* ContainsClassFields */;
20876             return node;
20877         }
20878         //
20879         // Punctuation
20880         //
20881         function createBaseToken(kind) {
20882             return baseFactory.createBaseTokenNode(kind);
20883         }
20884         function createToken(token) {
20885             ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 156 /* LastToken */, "Invalid token");
20886             ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals.");
20887             ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals.");
20888             ts.Debug.assert(token !== 78 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers");
20889             var node = createBaseToken(token);
20890             var transformFlags = 0 /* None */;
20891             switch (token) {
20892                 case 129 /* AsyncKeyword */:
20893                     // 'async' modifier is ES2017 (async functions) or ES2018 (async generators)
20894                     transformFlags =
20895                         64 /* ContainsES2017 */ |
20896                             32 /* ContainsES2018 */;
20897                     break;
20898                 case 122 /* PublicKeyword */:
20899                 case 120 /* PrivateKeyword */:
20900                 case 121 /* ProtectedKeyword */:
20901                 case 142 /* ReadonlyKeyword */:
20902                 case 125 /* AbstractKeyword */:
20903                 case 133 /* DeclareKeyword */:
20904                 case 84 /* ConstKeyword */:
20905                 case 128 /* AnyKeyword */:
20906                 case 144 /* NumberKeyword */:
20907                 case 155 /* BigIntKeyword */:
20908                 case 141 /* NeverKeyword */:
20909                 case 145 /* ObjectKeyword */:
20910                 case 147 /* StringKeyword */:
20911                 case 131 /* BooleanKeyword */:
20912                 case 148 /* SymbolKeyword */:
20913                 case 113 /* VoidKeyword */:
20914                 case 152 /* UnknownKeyword */:
20915                 case 150 /* UndefinedKeyword */: // `undefined` is an Identifier in the expression case.
20916                     transformFlags = 1 /* ContainsTypeScript */;
20917                     break;
20918                 case 123 /* StaticKeyword */:
20919                 case 105 /* SuperKeyword */:
20920                     transformFlags = 256 /* ContainsES2015 */;
20921                     break;
20922                 case 107 /* ThisKeyword */:
20923                     // 'this' indicates a lexical 'this'
20924                     transformFlags = 4096 /* ContainsLexicalThis */;
20925                     break;
20926             }
20927             if (transformFlags) {
20928                 node.transformFlags |= transformFlags;
20929             }
20930             return node;
20931         }
20932         //
20933         // Reserved words
20934         //
20935         // @api
20936         function createSuper() {
20937             return createToken(105 /* SuperKeyword */);
20938         }
20939         // @api
20940         function createThis() {
20941             return createToken(107 /* ThisKeyword */);
20942         }
20943         // @api
20944         function createNull() {
20945             return createToken(103 /* NullKeyword */);
20946         }
20947         // @api
20948         function createTrue() {
20949             return createToken(109 /* TrueKeyword */);
20950         }
20951         // @api
20952         function createFalse() {
20953             return createToken(94 /* FalseKeyword */);
20954         }
20955         //
20956         // Modifiers
20957         //
20958         // @api
20959         function createModifier(kind) {
20960             return createToken(kind);
20961         }
20962         // @api
20963         function createModifiersFromModifierFlags(flags) {
20964             var result = [];
20965             if (flags & 1 /* Export */) {
20966                 result.push(createModifier(92 /* ExportKeyword */));
20967             }
20968             if (flags & 2 /* Ambient */) {
20969                 result.push(createModifier(133 /* DeclareKeyword */));
20970             }
20971             if (flags & 512 /* Default */) {
20972                 result.push(createModifier(87 /* DefaultKeyword */));
20973             }
20974             if (flags & 2048 /* Const */) {
20975                 result.push(createModifier(84 /* ConstKeyword */));
20976             }
20977             if (flags & 4 /* Public */) {
20978                 result.push(createModifier(122 /* PublicKeyword */));
20979             }
20980             if (flags & 8 /* Private */) {
20981                 result.push(createModifier(120 /* PrivateKeyword */));
20982             }
20983             if (flags & 16 /* Protected */) {
20984                 result.push(createModifier(121 /* ProtectedKeyword */));
20985             }
20986             if (flags & 128 /* Abstract */) {
20987                 result.push(createModifier(125 /* AbstractKeyword */));
20988             }
20989             if (flags & 32 /* Static */) {
20990                 result.push(createModifier(123 /* StaticKeyword */));
20991             }
20992             if (flags & 64 /* Readonly */) {
20993                 result.push(createModifier(142 /* ReadonlyKeyword */));
20994             }
20995             if (flags & 256 /* Async */) {
20996                 result.push(createModifier(129 /* AsyncKeyword */));
20997             }
20998             return result;
20999         }
21000         //
21001         // Names
21002         //
21003         // @api
21004         function createQualifiedName(left, right) {
21005             var node = createBaseNode(157 /* QualifiedName */);
21006             node.left = left;
21007             node.right = asName(right);
21008             node.transformFlags |=
21009                 propagateChildFlags(node.left) |
21010                     propagateIdentifierNameFlags(node.right);
21011             return node;
21012         }
21013         // @api
21014         function updateQualifiedName(node, left, right) {
21015             return node.left !== left
21016                 || node.right !== right
21017                 ? update(createQualifiedName(left, right), node)
21018                 : node;
21019         }
21020         // @api
21021         function createComputedPropertyName(expression) {
21022             var node = createBaseNode(158 /* ComputedPropertyName */);
21023             node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression);
21024             node.transformFlags |=
21025                 propagateChildFlags(node.expression) |
21026                     256 /* ContainsES2015 */ |
21027                     32768 /* ContainsComputedPropertyName */;
21028             return node;
21029         }
21030         // @api
21031         function updateComputedPropertyName(node, expression) {
21032             return node.expression !== expression
21033                 ? update(createComputedPropertyName(expression), node)
21034                 : node;
21035         }
21036         //
21037         // Signature elements
21038         //
21039         // @api
21040         function createTypeParameterDeclaration(name, constraint, defaultType) {
21041             var node = createBaseNamedDeclaration(159 /* TypeParameter */, 
21042             /*decorators*/ undefined, 
21043             /*modifiers*/ undefined, name);
21044             node.constraint = constraint;
21045             node.default = defaultType;
21046             node.transformFlags = 1 /* ContainsTypeScript */;
21047             return node;
21048         }
21049         // @api
21050         function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
21051             return node.name !== name
21052                 || node.constraint !== constraint
21053                 || node.default !== defaultType
21054                 ? update(createTypeParameterDeclaration(name, constraint, defaultType), node)
21055                 : node;
21056         }
21057         // @api
21058         function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
21059             var node = createBaseVariableLikeDeclaration(160 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
21060             node.dotDotDotToken = dotDotDotToken;
21061             node.questionToken = questionToken;
21062             if (ts.isThisIdentifier(node.name)) {
21063                 node.transformFlags = 1 /* ContainsTypeScript */;
21064             }
21065             else {
21066                 node.transformFlags |=
21067                     propagateChildFlags(node.dotDotDotToken) |
21068                         propagateChildFlags(node.questionToken);
21069                 if (questionToken)
21070                     node.transformFlags |= 1 /* ContainsTypeScript */;
21071                 if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */)
21072                     node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
21073                 if (initializer || dotDotDotToken)
21074                     node.transformFlags |= 256 /* ContainsES2015 */;
21075             }
21076             return node;
21077         }
21078         // @api
21079         function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
21080             return node.decorators !== decorators
21081                 || node.modifiers !== modifiers
21082                 || node.dotDotDotToken !== dotDotDotToken
21083                 || node.name !== name
21084                 || node.questionToken !== questionToken
21085                 || node.type !== type
21086                 || node.initializer !== initializer
21087                 ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
21088                 : node;
21089         }
21090         // @api
21091         function createDecorator(expression) {
21092             var node = createBaseNode(161 /* Decorator */);
21093             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21094             node.transformFlags |=
21095                 propagateChildFlags(node.expression) |
21096                     1 /* ContainsTypeScript */ |
21097                     2048 /* ContainsTypeScriptClassSyntax */;
21098             return node;
21099         }
21100         // @api
21101         function updateDecorator(node, expression) {
21102             return node.expression !== expression
21103                 ? update(createDecorator(expression), node)
21104                 : node;
21105         }
21106         //
21107         // Type Elements
21108         //
21109         // @api
21110         function createPropertySignature(modifiers, name, questionToken, type) {
21111             var node = createBaseNamedDeclaration(162 /* PropertySignature */, 
21112             /*decorators*/ undefined, modifiers, name);
21113             node.type = type;
21114             node.questionToken = questionToken;
21115             node.transformFlags = 1 /* ContainsTypeScript */;
21116             return node;
21117         }
21118         // @api
21119         function updatePropertySignature(node, modifiers, name, questionToken, type) {
21120             return node.modifiers !== modifiers
21121                 || node.name !== name
21122                 || node.questionToken !== questionToken
21123                 || node.type !== type
21124                 ? update(createPropertySignature(modifiers, name, questionToken, type), node)
21125                 : node;
21126         }
21127         // @api
21128         function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
21129             var node = createBaseVariableLikeDeclaration(163 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer);
21130             node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
21131             node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
21132             node.transformFlags |=
21133                 propagateChildFlags(node.questionToken) |
21134                     propagateChildFlags(node.exclamationToken) |
21135                     4194304 /* ContainsClassFields */;
21136             if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
21137                 node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
21138             }
21139             if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
21140                 node.transformFlags |= 1 /* ContainsTypeScript */;
21141             }
21142             return node;
21143         }
21144         // @api
21145         function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
21146             return node.decorators !== decorators
21147                 || node.modifiers !== modifiers
21148                 || node.name !== name
21149                 || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
21150                 || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
21151                 || node.type !== type
21152                 || node.initializer !== initializer
21153                 ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
21154                 : node;
21155         }
21156         // @api
21157         function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) {
21158             var node = createBaseSignatureDeclaration(164 /* MethodSignature */, 
21159             /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type);
21160             node.questionToken = questionToken;
21161             node.transformFlags = 1 /* ContainsTypeScript */;
21162             return node;
21163         }
21164         // @api
21165         function updateMethodSignature(node, modifiers, name, questionToken, typeParameters, parameters, type) {
21166             return node.modifiers !== modifiers
21167                 || node.name !== name
21168                 || node.questionToken !== questionToken
21169                 || node.typeParameters !== typeParameters
21170                 || node.parameters !== parameters
21171                 || node.type !== type
21172                 ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node)
21173                 : node;
21174         }
21175         // @api
21176         function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
21177             var node = createBaseFunctionLikeDeclaration(165 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
21178             node.asteriskToken = asteriskToken;
21179             node.questionToken = questionToken;
21180             node.transformFlags |=
21181                 propagateChildFlags(node.asteriskToken) |
21182                     propagateChildFlags(node.questionToken) |
21183                     256 /* ContainsES2015 */;
21184             if (questionToken) {
21185                 node.transformFlags |= 1 /* ContainsTypeScript */;
21186             }
21187             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
21188                 if (asteriskToken) {
21189                     node.transformFlags |= 32 /* ContainsES2018 */;
21190                 }
21191                 else {
21192                     node.transformFlags |= 64 /* ContainsES2017 */;
21193                 }
21194             }
21195             else if (asteriskToken) {
21196                 node.transformFlags |= 512 /* ContainsGenerator */;
21197             }
21198             return node;
21199         }
21200         // @api
21201         function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
21202             return node.decorators !== decorators
21203                 || node.modifiers !== modifiers
21204                 || node.asteriskToken !== asteriskToken
21205                 || node.name !== name
21206                 || node.questionToken !== questionToken
21207                 || node.typeParameters !== typeParameters
21208                 || node.parameters !== parameters
21209                 || node.type !== type
21210                 || node.body !== body
21211                 ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
21212                 : node;
21213         }
21214         // @api
21215         function createConstructorDeclaration(decorators, modifiers, parameters, body) {
21216             var node = createBaseFunctionLikeDeclaration(166 /* Constructor */, decorators, modifiers, 
21217             /*name*/ undefined, 
21218             /*typeParameters*/ undefined, parameters, 
21219             /*type*/ undefined, body);
21220             node.transformFlags |= 256 /* ContainsES2015 */;
21221             return node;
21222         }
21223         // @api
21224         function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) {
21225             return node.decorators !== decorators
21226                 || node.modifiers !== modifiers
21227                 || node.parameters !== parameters
21228                 || node.body !== body
21229                 ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node)
21230                 : node;
21231         }
21232         // @api
21233         function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) {
21234             return createBaseFunctionLikeDeclaration(167 /* GetAccessor */, decorators, modifiers, name, 
21235             /*typeParameters*/ undefined, parameters, type, body);
21236         }
21237         // @api
21238         function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) {
21239             return node.decorators !== decorators
21240                 || node.modifiers !== modifiers
21241                 || node.name !== name
21242                 || node.parameters !== parameters
21243                 || node.type !== type
21244                 || node.body !== body
21245                 ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node)
21246                 : node;
21247         }
21248         // @api
21249         function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) {
21250             return createBaseFunctionLikeDeclaration(168 /* SetAccessor */, decorators, modifiers, name, 
21251             /*typeParameters*/ undefined, parameters, 
21252             /*type*/ undefined, body);
21253         }
21254         // @api
21255         function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) {
21256             return node.decorators !== decorators
21257                 || node.modifiers !== modifiers
21258                 || node.name !== name
21259                 || node.parameters !== parameters
21260                 || node.body !== body
21261                 ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node)
21262                 : node;
21263         }
21264         // @api
21265         function createCallSignature(typeParameters, parameters, type) {
21266             var node = createBaseSignatureDeclaration(169 /* CallSignature */, 
21267             /*decorators*/ undefined, 
21268             /*modifiers*/ undefined, 
21269             /*name*/ undefined, typeParameters, parameters, type);
21270             node.transformFlags = 1 /* ContainsTypeScript */;
21271             return node;
21272         }
21273         // @api
21274         function updateCallSignature(node, typeParameters, parameters, type) {
21275             return node.typeParameters !== typeParameters
21276                 || node.parameters !== parameters
21277                 || node.type !== type
21278                 ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node)
21279                 : node;
21280         }
21281         // @api
21282         function createConstructSignature(typeParameters, parameters, type) {
21283             var node = createBaseSignatureDeclaration(170 /* ConstructSignature */, 
21284             /*decorators*/ undefined, 
21285             /*modifiers*/ undefined, 
21286             /*name*/ undefined, typeParameters, parameters, type);
21287             node.transformFlags = 1 /* ContainsTypeScript */;
21288             return node;
21289         }
21290         // @api
21291         function updateConstructSignature(node, typeParameters, parameters, type) {
21292             return node.typeParameters !== typeParameters
21293                 || node.parameters !== parameters
21294                 || node.type !== type
21295                 ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node)
21296                 : node;
21297         }
21298         // @api
21299         function createIndexSignature(decorators, modifiers, parameters, type) {
21300             var node = createBaseSignatureDeclaration(171 /* IndexSignature */, decorators, modifiers, 
21301             /*name*/ undefined, 
21302             /*typeParameters*/ undefined, parameters, type);
21303             node.transformFlags = 1 /* ContainsTypeScript */;
21304             return node;
21305         }
21306         // @api
21307         function updateIndexSignature(node, decorators, modifiers, parameters, type) {
21308             return node.parameters !== parameters
21309                 || node.type !== type
21310                 || node.decorators !== decorators
21311                 || node.modifiers !== modifiers
21312                 ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node)
21313                 : node;
21314         }
21315         // @api
21316         function createTemplateLiteralTypeSpan(type, literal) {
21317             var node = createBaseNode(194 /* TemplateLiteralTypeSpan */);
21318             node.type = type;
21319             node.literal = literal;
21320             node.transformFlags = 1 /* ContainsTypeScript */;
21321             return node;
21322         }
21323         // @api
21324         function updateTemplateLiteralTypeSpan(node, type, literal) {
21325             return node.type !== type
21326                 || node.literal !== literal
21327                 ? update(createTemplateLiteralTypeSpan(type, literal), node)
21328                 : node;
21329         }
21330         //
21331         // Types
21332         //
21333         // @api
21334         function createKeywordTypeNode(kind) {
21335             return createToken(kind);
21336         }
21337         // @api
21338         function createTypePredicateNode(assertsModifier, parameterName, type) {
21339             var node = createBaseNode(172 /* TypePredicate */);
21340             node.assertsModifier = assertsModifier;
21341             node.parameterName = asName(parameterName);
21342             node.type = type;
21343             node.transformFlags = 1 /* ContainsTypeScript */;
21344             return node;
21345         }
21346         // @api
21347         function updateTypePredicateNode(node, assertsModifier, parameterName, type) {
21348             return node.assertsModifier !== assertsModifier
21349                 || node.parameterName !== parameterName
21350                 || node.type !== type
21351                 ? update(createTypePredicateNode(assertsModifier, parameterName, type), node)
21352                 : node;
21353         }
21354         // @api
21355         function createTypeReferenceNode(typeName, typeArguments) {
21356             var node = createBaseNode(173 /* TypeReference */);
21357             node.typeName = asName(typeName);
21358             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments));
21359             node.transformFlags = 1 /* ContainsTypeScript */;
21360             return node;
21361         }
21362         // @api
21363         function updateTypeReferenceNode(node, typeName, typeArguments) {
21364             return node.typeName !== typeName
21365                 || node.typeArguments !== typeArguments
21366                 ? update(createTypeReferenceNode(typeName, typeArguments), node)
21367                 : node;
21368         }
21369         // @api
21370         function createFunctionTypeNode(typeParameters, parameters, type) {
21371             var node = createBaseSignatureDeclaration(174 /* FunctionType */, 
21372             /*decorators*/ undefined, 
21373             /*modifiers*/ undefined, 
21374             /*name*/ undefined, typeParameters, parameters, type);
21375             node.transformFlags = 1 /* ContainsTypeScript */;
21376             return node;
21377         }
21378         // @api
21379         function updateFunctionTypeNode(node, typeParameters, parameters, type) {
21380             return node.typeParameters !== typeParameters
21381                 || node.parameters !== parameters
21382                 || node.type !== type
21383                 ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node)
21384                 : node;
21385         }
21386         // @api
21387         function createConstructorTypeNode(typeParameters, parameters, type) {
21388             var node = createBaseSignatureDeclaration(175 /* ConstructorType */, 
21389             /*decorators*/ undefined, 
21390             /*modifiers*/ undefined, 
21391             /*name*/ undefined, typeParameters, parameters, type);
21392             node.transformFlags = 1 /* ContainsTypeScript */;
21393             return node;
21394         }
21395         // @api
21396         function updateConstructorTypeNode(node, typeParameters, parameters, type) {
21397             return node.typeParameters !== typeParameters
21398                 || node.parameters !== parameters
21399                 || node.type !== type
21400                 ? updateBaseSignatureDeclaration(createConstructorTypeNode(typeParameters, parameters, type), node)
21401                 : node;
21402         }
21403         // @api
21404         function createTypeQueryNode(exprName) {
21405             var node = createBaseNode(176 /* TypeQuery */);
21406             node.exprName = exprName;
21407             node.transformFlags = 1 /* ContainsTypeScript */;
21408             return node;
21409         }
21410         // @api
21411         function updateTypeQueryNode(node, exprName) {
21412             return node.exprName !== exprName
21413                 ? update(createTypeQueryNode(exprName), node)
21414                 : node;
21415         }
21416         // @api
21417         function createTypeLiteralNode(members) {
21418             var node = createBaseNode(177 /* TypeLiteral */);
21419             node.members = createNodeArray(members);
21420             node.transformFlags = 1 /* ContainsTypeScript */;
21421             return node;
21422         }
21423         // @api
21424         function updateTypeLiteralNode(node, members) {
21425             return node.members !== members
21426                 ? update(createTypeLiteralNode(members), node)
21427                 : node;
21428         }
21429         // @api
21430         function createArrayTypeNode(elementType) {
21431             var node = createBaseNode(178 /* ArrayType */);
21432             node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType);
21433             node.transformFlags = 1 /* ContainsTypeScript */;
21434             return node;
21435         }
21436         // @api
21437         function updateArrayTypeNode(node, elementType) {
21438             return node.elementType !== elementType
21439                 ? update(createArrayTypeNode(elementType), node)
21440                 : node;
21441         }
21442         // @api
21443         function createTupleTypeNode(elements) {
21444             var node = createBaseNode(179 /* TupleType */);
21445             node.elements = createNodeArray(elements);
21446             node.transformFlags = 1 /* ContainsTypeScript */;
21447             return node;
21448         }
21449         // @api
21450         function updateTupleTypeNode(node, elements) {
21451             return node.elements !== elements
21452                 ? update(createTupleTypeNode(elements), node)
21453                 : node;
21454         }
21455         // @api
21456         function createNamedTupleMember(dotDotDotToken, name, questionToken, type) {
21457             var node = createBaseNode(192 /* NamedTupleMember */);
21458             node.dotDotDotToken = dotDotDotToken;
21459             node.name = name;
21460             node.questionToken = questionToken;
21461             node.type = type;
21462             node.transformFlags = 1 /* ContainsTypeScript */;
21463             return node;
21464         }
21465         // @api
21466         function updateNamedTupleMember(node, dotDotDotToken, name, questionToken, type) {
21467             return node.dotDotDotToken !== dotDotDotToken
21468                 || node.name !== name
21469                 || node.questionToken !== questionToken
21470                 || node.type !== type
21471                 ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node)
21472                 : node;
21473         }
21474         // @api
21475         function createOptionalTypeNode(type) {
21476             var node = createBaseNode(180 /* OptionalType */);
21477             node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type);
21478             node.transformFlags = 1 /* ContainsTypeScript */;
21479             return node;
21480         }
21481         // @api
21482         function updateOptionalTypeNode(node, type) {
21483             return node.type !== type
21484                 ? update(createOptionalTypeNode(type), node)
21485                 : node;
21486         }
21487         // @api
21488         function createRestTypeNode(type) {
21489             var node = createBaseNode(181 /* RestType */);
21490             node.type = type;
21491             node.transformFlags = 1 /* ContainsTypeScript */;
21492             return node;
21493         }
21494         // @api
21495         function updateRestTypeNode(node, type) {
21496             return node.type !== type
21497                 ? update(createRestTypeNode(type), node)
21498                 : node;
21499         }
21500         function createUnionOrIntersectionTypeNode(kind, types) {
21501             var node = createBaseNode(kind);
21502             node.types = parenthesizerRules().parenthesizeConstituentTypesOfUnionOrIntersectionType(types);
21503             node.transformFlags = 1 /* ContainsTypeScript */;
21504             return node;
21505         }
21506         function updateUnionOrIntersectionTypeNode(node, types) {
21507             return node.types !== types
21508                 ? update(createUnionOrIntersectionTypeNode(node.kind, types), node)
21509                 : node;
21510         }
21511         // @api
21512         function createUnionTypeNode(types) {
21513             return createUnionOrIntersectionTypeNode(182 /* UnionType */, types);
21514         }
21515         // @api
21516         function updateUnionTypeNode(node, types) {
21517             return updateUnionOrIntersectionTypeNode(node, types);
21518         }
21519         // @api
21520         function createIntersectionTypeNode(types) {
21521             return createUnionOrIntersectionTypeNode(183 /* IntersectionType */, types);
21522         }
21523         // @api
21524         function updateIntersectionTypeNode(node, types) {
21525             return updateUnionOrIntersectionTypeNode(node, types);
21526         }
21527         // @api
21528         function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
21529             var node = createBaseNode(184 /* ConditionalType */);
21530             node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType);
21531             node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType);
21532             node.trueType = trueType;
21533             node.falseType = falseType;
21534             node.transformFlags = 1 /* ContainsTypeScript */;
21535             return node;
21536         }
21537         // @api
21538         function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
21539             return node.checkType !== checkType
21540                 || node.extendsType !== extendsType
21541                 || node.trueType !== trueType
21542                 || node.falseType !== falseType
21543                 ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
21544                 : node;
21545         }
21546         // @api
21547         function createInferTypeNode(typeParameter) {
21548             var node = createBaseNode(185 /* InferType */);
21549             node.typeParameter = typeParameter;
21550             node.transformFlags = 1 /* ContainsTypeScript */;
21551             return node;
21552         }
21553         // @api
21554         function updateInferTypeNode(node, typeParameter) {
21555             return node.typeParameter !== typeParameter
21556                 ? update(createInferTypeNode(typeParameter), node)
21557                 : node;
21558         }
21559         // @api
21560         function createTemplateLiteralType(head, templateSpans) {
21561             var node = createBaseNode(193 /* TemplateLiteralType */);
21562             node.head = head;
21563             node.templateSpans = createNodeArray(templateSpans);
21564             node.transformFlags = 1 /* ContainsTypeScript */;
21565             return node;
21566         }
21567         // @api
21568         function updateTemplateLiteralType(node, head, templateSpans) {
21569             return node.head !== head
21570                 || node.templateSpans !== templateSpans
21571                 ? update(createTemplateLiteralType(head, templateSpans), node)
21572                 : node;
21573         }
21574         // @api
21575         function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
21576             if (isTypeOf === void 0) { isTypeOf = false; }
21577             var node = createBaseNode(195 /* ImportType */);
21578             node.argument = argument;
21579             node.qualifier = qualifier;
21580             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
21581             node.isTypeOf = isTypeOf;
21582             node.transformFlags = 1 /* ContainsTypeScript */;
21583             return node;
21584         }
21585         // @api
21586         function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
21587             if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; }
21588             return node.argument !== argument
21589                 || node.qualifier !== qualifier
21590                 || node.typeArguments !== typeArguments
21591                 || node.isTypeOf !== isTypeOf
21592                 ? update(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
21593                 : node;
21594         }
21595         // @api
21596         function createParenthesizedType(type) {
21597             var node = createBaseNode(186 /* ParenthesizedType */);
21598             node.type = type;
21599             node.transformFlags = 1 /* ContainsTypeScript */;
21600             return node;
21601         }
21602         // @api
21603         function updateParenthesizedType(node, type) {
21604             return node.type !== type
21605                 ? update(createParenthesizedType(type), node)
21606                 : node;
21607         }
21608         // @api
21609         function createThisTypeNode() {
21610             var node = createBaseNode(187 /* ThisType */);
21611             node.transformFlags = 1 /* ContainsTypeScript */;
21612             return node;
21613         }
21614         // @api
21615         function createTypeOperatorNode(operator, type) {
21616             var node = createBaseNode(188 /* TypeOperator */);
21617             node.operator = operator;
21618             node.type = parenthesizerRules().parenthesizeMemberOfElementType(type);
21619             node.transformFlags = 1 /* ContainsTypeScript */;
21620             return node;
21621         }
21622         // @api
21623         function updateTypeOperatorNode(node, type) {
21624             return node.type !== type
21625                 ? update(createTypeOperatorNode(node.operator, type), node)
21626                 : node;
21627         }
21628         // @api
21629         function createIndexedAccessTypeNode(objectType, indexType) {
21630             var node = createBaseNode(189 /* IndexedAccessType */);
21631             node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType);
21632             node.indexType = indexType;
21633             node.transformFlags = 1 /* ContainsTypeScript */;
21634             return node;
21635         }
21636         // @api
21637         function updateIndexedAccessTypeNode(node, objectType, indexType) {
21638             return node.objectType !== objectType
21639                 || node.indexType !== indexType
21640                 ? update(createIndexedAccessTypeNode(objectType, indexType), node)
21641                 : node;
21642         }
21643         // @api
21644         function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) {
21645             var node = createBaseNode(190 /* MappedType */);
21646             node.readonlyToken = readonlyToken;
21647             node.typeParameter = typeParameter;
21648             node.nameType = nameType;
21649             node.questionToken = questionToken;
21650             node.type = type;
21651             node.transformFlags = 1 /* ContainsTypeScript */;
21652             return node;
21653         }
21654         // @api
21655         function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type) {
21656             return node.readonlyToken !== readonlyToken
21657                 || node.typeParameter !== typeParameter
21658                 || node.nameType !== nameType
21659                 || node.questionToken !== questionToken
21660                 || node.type !== type
21661                 ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node)
21662                 : node;
21663         }
21664         // @api
21665         function createLiteralTypeNode(literal) {
21666             var node = createBaseNode(191 /* LiteralType */);
21667             node.literal = literal;
21668             node.transformFlags = 1 /* ContainsTypeScript */;
21669             return node;
21670         }
21671         // @api
21672         function updateLiteralTypeNode(node, literal) {
21673             return node.literal !== literal
21674                 ? update(createLiteralTypeNode(literal), node)
21675                 : node;
21676         }
21677         //
21678         // Binding Patterns
21679         //
21680         // @api
21681         function createObjectBindingPattern(elements) {
21682             var node = createBaseNode(196 /* ObjectBindingPattern */);
21683             node.elements = createNodeArray(elements);
21684             node.transformFlags |=
21685                 propagateChildrenFlags(node.elements) |
21686                     256 /* ContainsES2015 */ |
21687                     131072 /* ContainsBindingPattern */;
21688             if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
21689                 node.transformFlags |=
21690                     32 /* ContainsES2018 */ |
21691                         16384 /* ContainsObjectRestOrSpread */;
21692             }
21693             return node;
21694         }
21695         // @api
21696         function updateObjectBindingPattern(node, elements) {
21697             return node.elements !== elements
21698                 ? update(createObjectBindingPattern(elements), node)
21699                 : node;
21700         }
21701         // @api
21702         function createArrayBindingPattern(elements) {
21703             var node = createBaseNode(197 /* ArrayBindingPattern */);
21704             node.elements = createNodeArray(elements);
21705             node.transformFlags |=
21706                 propagateChildrenFlags(node.elements) |
21707                     256 /* ContainsES2015 */ |
21708                     131072 /* ContainsBindingPattern */;
21709             return node;
21710         }
21711         // @api
21712         function updateArrayBindingPattern(node, elements) {
21713             return node.elements !== elements
21714                 ? update(createArrayBindingPattern(elements), node)
21715                 : node;
21716         }
21717         // @api
21718         function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
21719             var node = createBaseBindingLikeDeclaration(198 /* BindingElement */, 
21720             /*decorators*/ undefined, 
21721             /*modifiers*/ undefined, name, initializer);
21722             node.propertyName = asName(propertyName);
21723             node.dotDotDotToken = dotDotDotToken;
21724             node.transformFlags |=
21725                 propagateChildFlags(node.dotDotDotToken) |
21726                     256 /* ContainsES2015 */;
21727             if (node.propertyName) {
21728                 node.transformFlags |= ts.isIdentifier(node.propertyName) ?
21729                     propagateIdentifierNameFlags(node.propertyName) :
21730                     propagateChildFlags(node.propertyName);
21731             }
21732             if (dotDotDotToken)
21733                 node.transformFlags |= 8192 /* ContainsRestOrSpread */;
21734             return node;
21735         }
21736         // @api
21737         function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
21738             return node.propertyName !== propertyName
21739                 || node.dotDotDotToken !== dotDotDotToken
21740                 || node.name !== name
21741                 || node.initializer !== initializer
21742                 ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
21743                 : node;
21744         }
21745         //
21746         // Expression
21747         //
21748         function createBaseExpression(kind) {
21749             var node = createBaseNode(kind);
21750             // the following properties are commonly set by the checker/binder
21751             return node;
21752         }
21753         // @api
21754         function createArrayLiteralExpression(elements, multiLine) {
21755             var node = createBaseExpression(199 /* ArrayLiteralExpression */);
21756             node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements));
21757             node.multiLine = multiLine;
21758             node.transformFlags |= propagateChildrenFlags(node.elements);
21759             return node;
21760         }
21761         // @api
21762         function updateArrayLiteralExpression(node, elements) {
21763             return node.elements !== elements
21764                 ? update(createArrayLiteralExpression(elements, node.multiLine), node)
21765                 : node;
21766         }
21767         // @api
21768         function createObjectLiteralExpression(properties, multiLine) {
21769             var node = createBaseExpression(200 /* ObjectLiteralExpression */);
21770             node.properties = createNodeArray(properties);
21771             node.multiLine = multiLine;
21772             node.transformFlags |= propagateChildrenFlags(node.properties);
21773             return node;
21774         }
21775         // @api
21776         function updateObjectLiteralExpression(node, properties) {
21777             return node.properties !== properties
21778                 ? update(createObjectLiteralExpression(properties, node.multiLine), node)
21779                 : node;
21780         }
21781         // @api
21782         function createPropertyAccessExpression(expression, name) {
21783             var node = createBaseExpression(201 /* PropertyAccessExpression */);
21784             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21785             node.name = asName(name);
21786             node.transformFlags =
21787                 propagateChildFlags(node.expression) |
21788                     (ts.isIdentifier(node.name) ?
21789                         propagateIdentifierNameFlags(node.name) :
21790                         propagateChildFlags(node.name));
21791             if (ts.isSuperKeyword(expression)) {
21792                 // super method calls require a lexical 'this'
21793                 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
21794                 node.transformFlags |=
21795                     64 /* ContainsES2017 */ |
21796                         32 /* ContainsES2018 */;
21797             }
21798             return node;
21799         }
21800         // @api
21801         function updatePropertyAccessExpression(node, expression, name) {
21802             if (ts.isPropertyAccessChain(node)) {
21803                 return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
21804             }
21805             return node.expression !== expression
21806                 || node.name !== name
21807                 ? update(createPropertyAccessExpression(expression, name), node)
21808                 : node;
21809         }
21810         // @api
21811         function createPropertyAccessChain(expression, questionDotToken, name) {
21812             var node = createBaseExpression(201 /* PropertyAccessExpression */);
21813             node.flags |= 32 /* OptionalChain */;
21814             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21815             node.questionDotToken = questionDotToken;
21816             node.name = asName(name);
21817             node.transformFlags |=
21818                 8 /* ContainsES2020 */ |
21819                     propagateChildFlags(node.expression) |
21820                     propagateChildFlags(node.questionDotToken) |
21821                     (ts.isIdentifier(node.name) ?
21822                         propagateIdentifierNameFlags(node.name) :
21823                         propagateChildFlags(node.name));
21824             return node;
21825         }
21826         // @api
21827         function updatePropertyAccessChain(node, expression, questionDotToken, name) {
21828             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
21829             // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
21830             // instead of using the default from createPropertyAccess
21831             return node.expression !== expression
21832                 || node.questionDotToken !== questionDotToken
21833                 || node.name !== name
21834                 ? update(createPropertyAccessChain(expression, questionDotToken, name), node)
21835                 : node;
21836         }
21837         // @api
21838         function createElementAccessExpression(expression, index) {
21839             var node = createBaseExpression(202 /* ElementAccessExpression */);
21840             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21841             node.argumentExpression = asExpression(index);
21842             node.transformFlags |=
21843                 propagateChildFlags(node.expression) |
21844                     propagateChildFlags(node.argumentExpression);
21845             if (ts.isSuperKeyword(expression)) {
21846                 // super method calls require a lexical 'this'
21847                 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
21848                 node.transformFlags |=
21849                     64 /* ContainsES2017 */ |
21850                         32 /* ContainsES2018 */;
21851             }
21852             return node;
21853         }
21854         // @api
21855         function updateElementAccessExpression(node, expression, argumentExpression) {
21856             if (ts.isElementAccessChain(node)) {
21857                 return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
21858             }
21859             return node.expression !== expression
21860                 || node.argumentExpression !== argumentExpression
21861                 ? update(createElementAccessExpression(expression, argumentExpression), node)
21862                 : node;
21863         }
21864         // @api
21865         function createElementAccessChain(expression, questionDotToken, index) {
21866             var node = createBaseExpression(202 /* ElementAccessExpression */);
21867             node.flags |= 32 /* OptionalChain */;
21868             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21869             node.questionDotToken = questionDotToken;
21870             node.argumentExpression = asExpression(index);
21871             node.transformFlags |=
21872                 propagateChildFlags(node.expression) |
21873                     propagateChildFlags(node.questionDotToken) |
21874                     propagateChildFlags(node.argumentExpression) |
21875                     8 /* ContainsES2020 */;
21876             return node;
21877         }
21878         // @api
21879         function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
21880             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
21881             // Because we are updating an existing ElementAccessChain we want to inherit its emitFlags
21882             // instead of using the default from createElementAccess
21883             return node.expression !== expression
21884                 || node.questionDotToken !== questionDotToken
21885                 || node.argumentExpression !== argumentExpression
21886                 ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
21887                 : node;
21888         }
21889         // @api
21890         function createCallExpression(expression, typeArguments, argumentsArray) {
21891             var node = createBaseExpression(203 /* CallExpression */);
21892             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21893             node.typeArguments = asNodeArray(typeArguments);
21894             node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
21895             node.transformFlags |=
21896                 propagateChildFlags(node.expression) |
21897                     propagateChildrenFlags(node.typeArguments) |
21898                     propagateChildrenFlags(node.arguments);
21899             if (node.typeArguments) {
21900                 node.transformFlags |= 1 /* ContainsTypeScript */;
21901             }
21902             if (ts.isImportKeyword(node.expression)) {
21903                 node.transformFlags |= 2097152 /* ContainsDynamicImport */;
21904             }
21905             else if (ts.isSuperProperty(node.expression)) {
21906                 node.transformFlags |= 4096 /* ContainsLexicalThis */;
21907             }
21908             return node;
21909         }
21910         // @api
21911         function updateCallExpression(node, expression, typeArguments, argumentsArray) {
21912             if (ts.isCallChain(node)) {
21913                 return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
21914             }
21915             return node.expression !== expression
21916                 || node.typeArguments !== typeArguments
21917                 || node.arguments !== argumentsArray
21918                 ? update(createCallExpression(expression, typeArguments, argumentsArray), node)
21919                 : node;
21920         }
21921         // @api
21922         function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
21923             var node = createBaseExpression(203 /* CallExpression */);
21924             node.flags |= 32 /* OptionalChain */;
21925             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21926             node.questionDotToken = questionDotToken;
21927             node.typeArguments = asNodeArray(typeArguments);
21928             node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
21929             node.transformFlags |=
21930                 propagateChildFlags(node.expression) |
21931                     propagateChildFlags(node.questionDotToken) |
21932                     propagateChildrenFlags(node.typeArguments) |
21933                     propagateChildrenFlags(node.arguments) |
21934                     8 /* ContainsES2020 */;
21935             if (node.typeArguments) {
21936                 node.transformFlags |= 1 /* ContainsTypeScript */;
21937             }
21938             if (ts.isSuperProperty(node.expression)) {
21939                 node.transformFlags |= 4096 /* ContainsLexicalThis */;
21940             }
21941             return node;
21942         }
21943         // @api
21944         function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
21945             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
21946             return node.expression !== expression
21947                 || node.questionDotToken !== questionDotToken
21948                 || node.typeArguments !== typeArguments
21949                 || node.arguments !== argumentsArray
21950                 ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
21951                 : node;
21952         }
21953         // @api
21954         function createNewExpression(expression, typeArguments, argumentsArray) {
21955             var node = createBaseExpression(204 /* NewExpression */);
21956             node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression);
21957             node.typeArguments = asNodeArray(typeArguments);
21958             node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined;
21959             node.transformFlags |=
21960                 propagateChildFlags(node.expression) |
21961                     propagateChildrenFlags(node.typeArguments) |
21962                     propagateChildrenFlags(node.arguments) |
21963                     8 /* ContainsES2020 */;
21964             if (node.typeArguments) {
21965                 node.transformFlags |= 1 /* ContainsTypeScript */;
21966             }
21967             return node;
21968         }
21969         // @api
21970         function updateNewExpression(node, expression, typeArguments, argumentsArray) {
21971             return node.expression !== expression
21972                 || node.typeArguments !== typeArguments
21973                 || node.arguments !== argumentsArray
21974                 ? update(createNewExpression(expression, typeArguments, argumentsArray), node)
21975                 : node;
21976         }
21977         // @api
21978         function createTaggedTemplateExpression(tag, typeArguments, template) {
21979             var node = createBaseExpression(205 /* TaggedTemplateExpression */);
21980             node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag);
21981             node.typeArguments = asNodeArray(typeArguments);
21982             node.template = template;
21983             node.transformFlags |=
21984                 propagateChildFlags(node.tag) |
21985                     propagateChildrenFlags(node.typeArguments) |
21986                     propagateChildFlags(node.template) |
21987                     256 /* ContainsES2015 */;
21988             if (node.typeArguments) {
21989                 node.transformFlags |= 1 /* ContainsTypeScript */;
21990             }
21991             if (ts.hasInvalidEscape(node.template)) {
21992                 node.transformFlags |= 32 /* ContainsES2018 */;
21993             }
21994             return node;
21995         }
21996         // @api
21997         function updateTaggedTemplateExpression(node, tag, typeArguments, template) {
21998             return node.tag !== tag
21999                 || node.typeArguments !== typeArguments
22000                 || node.template !== template
22001                 ? update(createTaggedTemplateExpression(tag, typeArguments, template), node)
22002                 : node;
22003         }
22004         // @api
22005         function createTypeAssertion(type, expression) {
22006             var node = createBaseExpression(206 /* TypeAssertionExpression */);
22007             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22008             node.type = type;
22009             node.transformFlags |=
22010                 propagateChildFlags(node.expression) |
22011                     propagateChildFlags(node.type) |
22012                     1 /* ContainsTypeScript */;
22013             return node;
22014         }
22015         // @api
22016         function updateTypeAssertion(node, type, expression) {
22017             return node.type !== type
22018                 || node.expression !== expression
22019                 ? update(createTypeAssertion(type, expression), node)
22020                 : node;
22021         }
22022         // @api
22023         function createParenthesizedExpression(expression) {
22024             var node = createBaseExpression(207 /* ParenthesizedExpression */);
22025             node.expression = expression;
22026             node.transformFlags = propagateChildFlags(node.expression);
22027             return node;
22028         }
22029         // @api
22030         function updateParenthesizedExpression(node, expression) {
22031             return node.expression !== expression
22032                 ? update(createParenthesizedExpression(expression), node)
22033                 : node;
22034         }
22035         // @api
22036         function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22037             var node = createBaseFunctionLikeDeclaration(208 /* FunctionExpression */, 
22038             /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body);
22039             node.asteriskToken = asteriskToken;
22040             node.transformFlags |= propagateChildFlags(node.asteriskToken);
22041             if (node.typeParameters) {
22042                 node.transformFlags |= 1 /* ContainsTypeScript */;
22043             }
22044             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22045                 if (node.asteriskToken) {
22046                     node.transformFlags |= 32 /* ContainsES2018 */;
22047                 }
22048                 else {
22049                     node.transformFlags |= 64 /* ContainsES2017 */;
22050                 }
22051             }
22052             else if (node.asteriskToken) {
22053                 node.transformFlags |= 512 /* ContainsGenerator */;
22054             }
22055             return node;
22056         }
22057         // @api
22058         function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22059             return node.name !== name
22060                 || node.modifiers !== modifiers
22061                 || node.asteriskToken !== asteriskToken
22062                 || node.typeParameters !== typeParameters
22063                 || node.parameters !== parameters
22064                 || node.type !== type
22065                 || node.body !== body
22066                 ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
22067                 : node;
22068         }
22069         // @api
22070         function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
22071             var node = createBaseFunctionLikeDeclaration(209 /* ArrowFunction */, 
22072             /*decorators*/ undefined, modifiers, 
22073             /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body));
22074             node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */);
22075             node.transformFlags |=
22076                 propagateChildFlags(node.equalsGreaterThanToken) |
22077                     256 /* ContainsES2015 */;
22078             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22079                 node.transformFlags |= 64 /* ContainsES2017 */;
22080             }
22081             return node;
22082         }
22083         // @api
22084         function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
22085             return node.modifiers !== modifiers
22086                 || node.typeParameters !== typeParameters
22087                 || node.parameters !== parameters
22088                 || node.type !== type
22089                 || node.equalsGreaterThanToken !== equalsGreaterThanToken
22090                 || node.body !== body
22091                 ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
22092                 : node;
22093         }
22094         // @api
22095         function createDeleteExpression(expression) {
22096             var node = createBaseExpression(210 /* DeleteExpression */);
22097             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22098             node.transformFlags |= propagateChildFlags(node.expression);
22099             return node;
22100         }
22101         // @api
22102         function updateDeleteExpression(node, expression) {
22103             return node.expression !== expression
22104                 ? update(createDeleteExpression(expression), node)
22105                 : node;
22106         }
22107         // @api
22108         function createTypeOfExpression(expression) {
22109             var node = createBaseExpression(211 /* TypeOfExpression */);
22110             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22111             node.transformFlags |= propagateChildFlags(node.expression);
22112             return node;
22113         }
22114         // @api
22115         function updateTypeOfExpression(node, expression) {
22116             return node.expression !== expression
22117                 ? update(createTypeOfExpression(expression), node)
22118                 : node;
22119         }
22120         // @api
22121         function createVoidExpression(expression) {
22122             var node = createBaseExpression(212 /* VoidExpression */);
22123             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22124             node.transformFlags |= propagateChildFlags(node.expression);
22125             return node;
22126         }
22127         // @api
22128         function updateVoidExpression(node, expression) {
22129             return node.expression !== expression
22130                 ? update(createVoidExpression(expression), node)
22131                 : node;
22132         }
22133         // @api
22134         function createAwaitExpression(expression) {
22135             var node = createBaseExpression(213 /* AwaitExpression */);
22136             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22137             node.transformFlags |=
22138                 propagateChildFlags(node.expression) |
22139                     64 /* ContainsES2017 */ |
22140                     32 /* ContainsES2018 */ |
22141                     524288 /* ContainsAwait */;
22142             return node;
22143         }
22144         // @api
22145         function updateAwaitExpression(node, expression) {
22146             return node.expression !== expression
22147                 ? update(createAwaitExpression(expression), node)
22148                 : node;
22149         }
22150         // @api
22151         function createPrefixUnaryExpression(operator, operand) {
22152             var node = createBaseExpression(214 /* PrefixUnaryExpression */);
22153             node.operator = operator;
22154             node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand);
22155             node.transformFlags |= propagateChildFlags(node.operand);
22156             return node;
22157         }
22158         // @api
22159         function updatePrefixUnaryExpression(node, operand) {
22160             return node.operand !== operand
22161                 ? update(createPrefixUnaryExpression(node.operator, operand), node)
22162                 : node;
22163         }
22164         // @api
22165         function createPostfixUnaryExpression(operand, operator) {
22166             var node = createBaseExpression(215 /* PostfixUnaryExpression */);
22167             node.operator = operator;
22168             node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand);
22169             node.transformFlags = propagateChildFlags(node.operand);
22170             return node;
22171         }
22172         // @api
22173         function updatePostfixUnaryExpression(node, operand) {
22174             return node.operand !== operand
22175                 ? update(createPostfixUnaryExpression(operand, node.operator), node)
22176                 : node;
22177         }
22178         // @api
22179         function createBinaryExpression(left, operator, right) {
22180             var node = createBaseExpression(216 /* BinaryExpression */);
22181             var operatorToken = asToken(operator);
22182             var operatorKind = operatorToken.kind;
22183             node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left);
22184             node.operatorToken = operatorToken;
22185             node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right);
22186             node.transformFlags |=
22187                 propagateChildFlags(node.left) |
22188                     propagateChildFlags(node.operatorToken) |
22189                     propagateChildFlags(node.right);
22190             if (operatorKind === 60 /* QuestionQuestionToken */) {
22191                 node.transformFlags |= 8 /* ContainsES2020 */;
22192             }
22193             else if (operatorKind === 62 /* EqualsToken */) {
22194                 if (ts.isObjectLiteralExpression(node.left)) {
22195                     node.transformFlags |=
22196                         256 /* ContainsES2015 */ |
22197                             32 /* ContainsES2018 */ |
22198                             1024 /* ContainsDestructuringAssignment */ |
22199                             propagateAssignmentPatternFlags(node.left);
22200                 }
22201                 else if (ts.isArrayLiteralExpression(node.left)) {
22202                     node.transformFlags |=
22203                         256 /* ContainsES2015 */ |
22204                             1024 /* ContainsDestructuringAssignment */ |
22205                             propagateAssignmentPatternFlags(node.left);
22206                 }
22207             }
22208             else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 66 /* AsteriskAsteriskEqualsToken */) {
22209                 node.transformFlags |= 128 /* ContainsES2016 */;
22210             }
22211             else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) {
22212                 node.transformFlags |= 4 /* ContainsESNext */;
22213             }
22214             return node;
22215         }
22216         function propagateAssignmentPatternFlags(node) {
22217             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */)
22218                 return 16384 /* ContainsObjectRestOrSpread */;
22219             if (node.transformFlags & 32 /* ContainsES2018 */) {
22220                 // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c'
22221                 // will not be correctly interpreted by the ES2018 transformer
22222                 for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) {
22223                     var element = _a[_i];
22224                     var target = ts.getTargetOfBindingOrAssignmentElement(element);
22225                     if (target && ts.isAssignmentPattern(target)) {
22226                         if (target.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
22227                             return 16384 /* ContainsObjectRestOrSpread */;
22228                         }
22229                         if (target.transformFlags & 32 /* ContainsES2018 */) {
22230                             var flags_1 = propagateAssignmentPatternFlags(target);
22231                             if (flags_1)
22232                                 return flags_1;
22233                         }
22234                     }
22235                 }
22236             }
22237             return 0 /* None */;
22238         }
22239         // @api
22240         function updateBinaryExpression(node, left, operator, right) {
22241             return node.left !== left
22242                 || node.operatorToken !== operator
22243                 || node.right !== right
22244                 ? update(createBinaryExpression(left, operator, right), node)
22245                 : node;
22246         }
22247         // @api
22248         function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) {
22249             var node = createBaseExpression(217 /* ConditionalExpression */);
22250             node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition);
22251             node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */);
22252             node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue);
22253             node.colonToken = colonToken !== null && colonToken !== void 0 ? colonToken : createToken(58 /* ColonToken */);
22254             node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse);
22255             node.transformFlags |=
22256                 propagateChildFlags(node.condition) |
22257                     propagateChildFlags(node.questionToken) |
22258                     propagateChildFlags(node.whenTrue) |
22259                     propagateChildFlags(node.colonToken) |
22260                     propagateChildFlags(node.whenFalse);
22261             return node;
22262         }
22263         // @api
22264         function updateConditionalExpression(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
22265             return node.condition !== condition
22266                 || node.questionToken !== questionToken
22267                 || node.whenTrue !== whenTrue
22268                 || node.colonToken !== colonToken
22269                 || node.whenFalse !== whenFalse
22270                 ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node)
22271                 : node;
22272         }
22273         // @api
22274         function createTemplateExpression(head, templateSpans) {
22275             var node = createBaseExpression(218 /* TemplateExpression */);
22276             node.head = head;
22277             node.templateSpans = createNodeArray(templateSpans);
22278             node.transformFlags |=
22279                 propagateChildFlags(node.head) |
22280                     propagateChildrenFlags(node.templateSpans) |
22281                     256 /* ContainsES2015 */;
22282             return node;
22283         }
22284         // @api
22285         function updateTemplateExpression(node, head, templateSpans) {
22286             return node.head !== head
22287                 || node.templateSpans !== templateSpans
22288                 ? update(createTemplateExpression(head, templateSpans), node)
22289                 : node;
22290         }
22291         function createTemplateLiteralLikeNodeChecked(kind, text, rawText, templateFlags) {
22292             if (templateFlags === void 0) { templateFlags = 0 /* None */; }
22293             ts.Debug.assert(!(templateFlags & ~2048 /* TemplateLiteralLikeFlags */), "Unsupported template flags.");
22294             // NOTE: without the assignment to `undefined`, we don't narrow the initial type of `cooked`.
22295             // eslint-disable-next-line no-undef-init
22296             var cooked = undefined;
22297             if (rawText !== undefined && rawText !== text) {
22298                 cooked = getCookedText(kind, rawText);
22299                 if (typeof cooked === "object") {
22300                     return ts.Debug.fail("Invalid raw text");
22301                 }
22302             }
22303             if (text === undefined) {
22304                 if (cooked === undefined) {
22305                     return ts.Debug.fail("Arguments 'text' and 'rawText' may not both be undefined.");
22306                 }
22307                 text = cooked;
22308             }
22309             else if (cooked !== undefined) {
22310                 ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
22311             }
22312             return createTemplateLiteralLikeNode(kind, text, rawText, templateFlags);
22313         }
22314         // @api
22315         function createTemplateLiteralLikeNode(kind, text, rawText, templateFlags) {
22316             var node = createBaseToken(kind);
22317             node.text = text;
22318             node.rawText = rawText;
22319             node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */;
22320             node.transformFlags |= 256 /* ContainsES2015 */;
22321             if (node.templateFlags) {
22322                 node.transformFlags |= 32 /* ContainsES2018 */;
22323             }
22324             return node;
22325         }
22326         // @api
22327         function createTemplateHead(text, rawText, templateFlags) {
22328             return createTemplateLiteralLikeNodeChecked(15 /* TemplateHead */, text, rawText, templateFlags);
22329         }
22330         // @api
22331         function createTemplateMiddle(text, rawText, templateFlags) {
22332             return createTemplateLiteralLikeNodeChecked(16 /* TemplateMiddle */, text, rawText, templateFlags);
22333         }
22334         // @api
22335         function createTemplateTail(text, rawText, templateFlags) {
22336             return createTemplateLiteralLikeNodeChecked(17 /* TemplateTail */, text, rawText, templateFlags);
22337         }
22338         // @api
22339         function createNoSubstitutionTemplateLiteral(text, rawText, templateFlags) {
22340             return createTemplateLiteralLikeNodeChecked(14 /* NoSubstitutionTemplateLiteral */, text, rawText, templateFlags);
22341         }
22342         // @api
22343         function createYieldExpression(asteriskToken, expression) {
22344             ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression.");
22345             var node = createBaseExpression(219 /* YieldExpression */);
22346             node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22347             node.asteriskToken = asteriskToken;
22348             node.transformFlags |=
22349                 propagateChildFlags(node.expression) |
22350                     propagateChildFlags(node.asteriskToken) |
22351                     256 /* ContainsES2015 */ |
22352                     32 /* ContainsES2018 */ |
22353                     262144 /* ContainsYield */;
22354             return node;
22355         }
22356         // @api
22357         function updateYieldExpression(node, asteriskToken, expression) {
22358             return node.expression !== expression
22359                 || node.asteriskToken !== asteriskToken
22360                 ? update(createYieldExpression(asteriskToken, expression), node)
22361                 : node;
22362         }
22363         // @api
22364         function createSpreadElement(expression) {
22365             var node = createBaseExpression(220 /* SpreadElement */);
22366             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22367             node.transformFlags |=
22368                 propagateChildFlags(node.expression) |
22369                     256 /* ContainsES2015 */ |
22370                     8192 /* ContainsRestOrSpread */;
22371             return node;
22372         }
22373         // @api
22374         function updateSpreadElement(node, expression) {
22375             return node.expression !== expression
22376                 ? update(createSpreadElement(expression), node)
22377                 : node;
22378         }
22379         // @api
22380         function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) {
22381             var node = createBaseClassLikeDeclaration(221 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members);
22382             node.transformFlags |= 256 /* ContainsES2015 */;
22383             return node;
22384         }
22385         // @api
22386         function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
22387             return node.decorators !== decorators
22388                 || node.modifiers !== modifiers
22389                 || node.name !== name
22390                 || node.typeParameters !== typeParameters
22391                 || node.heritageClauses !== heritageClauses
22392                 || node.members !== members
22393                 ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
22394                 : node;
22395         }
22396         // @api
22397         function createOmittedExpression() {
22398             return createBaseExpression(222 /* OmittedExpression */);
22399         }
22400         // @api
22401         function createExpressionWithTypeArguments(expression, typeArguments) {
22402             var node = createBaseNode(223 /* ExpressionWithTypeArguments */);
22403             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22404             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
22405             node.transformFlags |=
22406                 propagateChildFlags(node.expression) |
22407                     propagateChildrenFlags(node.typeArguments) |
22408                     256 /* ContainsES2015 */;
22409             return node;
22410         }
22411         // @api
22412         function updateExpressionWithTypeArguments(node, expression, typeArguments) {
22413             return node.expression !== expression
22414                 || node.typeArguments !== typeArguments
22415                 ? update(createExpressionWithTypeArguments(expression, typeArguments), node)
22416                 : node;
22417         }
22418         // @api
22419         function createAsExpression(expression, type) {
22420             var node = createBaseExpression(224 /* AsExpression */);
22421             node.expression = expression;
22422             node.type = type;
22423             node.transformFlags |=
22424                 propagateChildFlags(node.expression) |
22425                     propagateChildFlags(node.type) |
22426                     1 /* ContainsTypeScript */;
22427             return node;
22428         }
22429         // @api
22430         function updateAsExpression(node, expression, type) {
22431             return node.expression !== expression
22432                 || node.type !== type
22433                 ? update(createAsExpression(expression, type), node)
22434                 : node;
22435         }
22436         // @api
22437         function createNonNullExpression(expression) {
22438             var node = createBaseExpression(225 /* NonNullExpression */);
22439             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22440             node.transformFlags |=
22441                 propagateChildFlags(node.expression) |
22442                     1 /* ContainsTypeScript */;
22443             return node;
22444         }
22445         // @api
22446         function updateNonNullExpression(node, expression) {
22447             if (ts.isNonNullChain(node)) {
22448                 return updateNonNullChain(node, expression);
22449             }
22450             return node.expression !== expression
22451                 ? update(createNonNullExpression(expression), node)
22452                 : node;
22453         }
22454         // @api
22455         function createNonNullChain(expression) {
22456             var node = createBaseExpression(225 /* NonNullExpression */);
22457             node.flags |= 32 /* OptionalChain */;
22458             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22459             node.transformFlags |=
22460                 propagateChildFlags(node.expression) |
22461                     1 /* ContainsTypeScript */;
22462             return node;
22463         }
22464         // @api
22465         function updateNonNullChain(node, expression) {
22466             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
22467             return node.expression !== expression
22468                 ? update(createNonNullChain(expression), node)
22469                 : node;
22470         }
22471         // @api
22472         function createMetaProperty(keywordToken, name) {
22473             var node = createBaseExpression(226 /* MetaProperty */);
22474             node.keywordToken = keywordToken;
22475             node.name = name;
22476             node.transformFlags |= propagateChildFlags(node.name);
22477             switch (keywordToken) {
22478                 case 102 /* NewKeyword */:
22479                     node.transformFlags |= 256 /* ContainsES2015 */;
22480                     break;
22481                 case 99 /* ImportKeyword */:
22482                     node.transformFlags |= 4 /* ContainsESNext */;
22483                     break;
22484                 default:
22485                     return ts.Debug.assertNever(keywordToken);
22486             }
22487             return node;
22488         }
22489         // @api
22490         function updateMetaProperty(node, name) {
22491             return node.name !== name
22492                 ? update(createMetaProperty(node.keywordToken, name), node)
22493                 : node;
22494         }
22495         //
22496         // Misc
22497         //
22498         // @api
22499         function createTemplateSpan(expression, literal) {
22500             var node = createBaseNode(228 /* TemplateSpan */);
22501             node.expression = expression;
22502             node.literal = literal;
22503             node.transformFlags |=
22504                 propagateChildFlags(node.expression) |
22505                     propagateChildFlags(node.literal) |
22506                     256 /* ContainsES2015 */;
22507             return node;
22508         }
22509         // @api
22510         function updateTemplateSpan(node, expression, literal) {
22511             return node.expression !== expression
22512                 || node.literal !== literal
22513                 ? update(createTemplateSpan(expression, literal), node)
22514                 : node;
22515         }
22516         // @api
22517         function createSemicolonClassElement() {
22518             var node = createBaseNode(229 /* SemicolonClassElement */);
22519             node.transformFlags |= 256 /* ContainsES2015 */;
22520             return node;
22521         }
22522         //
22523         // Element
22524         //
22525         // @api
22526         function createBlock(statements, multiLine) {
22527             var node = createBaseNode(230 /* Block */);
22528             node.statements = createNodeArray(statements);
22529             node.multiLine = multiLine;
22530             node.transformFlags |= propagateChildrenFlags(node.statements);
22531             return node;
22532         }
22533         // @api
22534         function updateBlock(node, statements) {
22535             return node.statements !== statements
22536                 ? update(createBlock(statements, node.multiLine), node)
22537                 : node;
22538         }
22539         // @api
22540         function createVariableStatement(modifiers, declarationList) {
22541             var node = createBaseDeclaration(232 /* VariableStatement */, /*decorators*/ undefined, modifiers);
22542             node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
22543             node.transformFlags |=
22544                 propagateChildFlags(node.declarationList);
22545             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22546                 node.transformFlags = 1 /* ContainsTypeScript */;
22547             }
22548             return node;
22549         }
22550         // @api
22551         function updateVariableStatement(node, modifiers, declarationList) {
22552             return node.modifiers !== modifiers
22553                 || node.declarationList !== declarationList
22554                 ? update(createVariableStatement(modifiers, declarationList), node)
22555                 : node;
22556         }
22557         // @api
22558         function createEmptyStatement() {
22559             return createBaseNode(231 /* EmptyStatement */);
22560         }
22561         // @api
22562         function createExpressionStatement(expression) {
22563             var node = createBaseNode(233 /* ExpressionStatement */);
22564             node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression);
22565             node.transformFlags |= propagateChildFlags(node.expression);
22566             return node;
22567         }
22568         // @api
22569         function updateExpressionStatement(node, expression) {
22570             return node.expression !== expression
22571                 ? update(createExpressionStatement(expression), node)
22572                 : node;
22573         }
22574         // @api
22575         function createIfStatement(expression, thenStatement, elseStatement) {
22576             var node = createBaseNode(234 /* IfStatement */);
22577             node.expression = expression;
22578             node.thenStatement = asEmbeddedStatement(thenStatement);
22579             node.elseStatement = asEmbeddedStatement(elseStatement);
22580             node.transformFlags |=
22581                 propagateChildFlags(node.expression) |
22582                     propagateChildFlags(node.thenStatement) |
22583                     propagateChildFlags(node.elseStatement);
22584             return node;
22585         }
22586         // @api
22587         function updateIfStatement(node, expression, thenStatement, elseStatement) {
22588             return node.expression !== expression
22589                 || node.thenStatement !== thenStatement
22590                 || node.elseStatement !== elseStatement
22591                 ? update(createIfStatement(expression, thenStatement, elseStatement), node)
22592                 : node;
22593         }
22594         // @api
22595         function createDoStatement(statement, expression) {
22596             var node = createBaseNode(235 /* DoStatement */);
22597             node.statement = asEmbeddedStatement(statement);
22598             node.expression = expression;
22599             node.transformFlags |=
22600                 propagateChildFlags(node.statement) |
22601                     propagateChildFlags(node.expression);
22602             return node;
22603         }
22604         // @api
22605         function updateDoStatement(node, statement, expression) {
22606             return node.statement !== statement
22607                 || node.expression !== expression
22608                 ? update(createDoStatement(statement, expression), node)
22609                 : node;
22610         }
22611         // @api
22612         function createWhileStatement(expression, statement) {
22613             var node = createBaseNode(236 /* WhileStatement */);
22614             node.expression = expression;
22615             node.statement = asEmbeddedStatement(statement);
22616             node.transformFlags |=
22617                 propagateChildFlags(node.expression) |
22618                     propagateChildFlags(node.statement);
22619             return node;
22620         }
22621         // @api
22622         function updateWhileStatement(node, expression, statement) {
22623             return node.expression !== expression
22624                 || node.statement !== statement
22625                 ? update(createWhileStatement(expression, statement), node)
22626                 : node;
22627         }
22628         // @api
22629         function createForStatement(initializer, condition, incrementor, statement) {
22630             var node = createBaseNode(237 /* ForStatement */);
22631             node.initializer = initializer;
22632             node.condition = condition;
22633             node.incrementor = incrementor;
22634             node.statement = asEmbeddedStatement(statement);
22635             node.transformFlags |=
22636                 propagateChildFlags(node.initializer) |
22637                     propagateChildFlags(node.condition) |
22638                     propagateChildFlags(node.incrementor) |
22639                     propagateChildFlags(node.statement);
22640             return node;
22641         }
22642         // @api
22643         function updateForStatement(node, initializer, condition, incrementor, statement) {
22644             return node.initializer !== initializer
22645                 || node.condition !== condition
22646                 || node.incrementor !== incrementor
22647                 || node.statement !== statement
22648                 ? update(createForStatement(initializer, condition, incrementor, statement), node)
22649                 : node;
22650         }
22651         // @api
22652         function createForInStatement(initializer, expression, statement) {
22653             var node = createBaseNode(238 /* ForInStatement */);
22654             node.initializer = initializer;
22655             node.expression = expression;
22656             node.statement = asEmbeddedStatement(statement);
22657             node.transformFlags |=
22658                 propagateChildFlags(node.initializer) |
22659                     propagateChildFlags(node.expression) |
22660                     propagateChildFlags(node.statement);
22661             return node;
22662         }
22663         // @api
22664         function updateForInStatement(node, initializer, expression, statement) {
22665             return node.initializer !== initializer
22666                 || node.expression !== expression
22667                 || node.statement !== statement
22668                 ? update(createForInStatement(initializer, expression, statement), node)
22669                 : node;
22670         }
22671         // @api
22672         function createForOfStatement(awaitModifier, initializer, expression, statement) {
22673             var node = createBaseNode(239 /* ForOfStatement */);
22674             node.awaitModifier = awaitModifier;
22675             node.initializer = initializer;
22676             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22677             node.statement = asEmbeddedStatement(statement);
22678             node.transformFlags |=
22679                 propagateChildFlags(node.awaitModifier) |
22680                     propagateChildFlags(node.initializer) |
22681                     propagateChildFlags(node.expression) |
22682                     propagateChildFlags(node.statement) |
22683                     256 /* ContainsES2015 */;
22684             if (awaitModifier)
22685                 node.transformFlags |= 32 /* ContainsES2018 */;
22686             return node;
22687         }
22688         // @api
22689         function updateForOfStatement(node, awaitModifier, initializer, expression, statement) {
22690             return node.awaitModifier !== awaitModifier
22691                 || node.initializer !== initializer
22692                 || node.expression !== expression
22693                 || node.statement !== statement
22694                 ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node)
22695                 : node;
22696         }
22697         // @api
22698         function createContinueStatement(label) {
22699             var node = createBaseNode(240 /* ContinueStatement */);
22700             node.label = asName(label);
22701             node.transformFlags |=
22702                 propagateChildFlags(node.label) |
22703                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
22704             return node;
22705         }
22706         // @api
22707         function updateContinueStatement(node, label) {
22708             return node.label !== label
22709                 ? update(createContinueStatement(label), node)
22710                 : node;
22711         }
22712         // @api
22713         function createBreakStatement(label) {
22714             var node = createBaseNode(241 /* BreakStatement */);
22715             node.label = asName(label);
22716             node.transformFlags |=
22717                 propagateChildFlags(node.label) |
22718                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
22719             return node;
22720         }
22721         // @api
22722         function updateBreakStatement(node, label) {
22723             return node.label !== label
22724                 ? update(createBreakStatement(label), node)
22725                 : node;
22726         }
22727         // @api
22728         function createReturnStatement(expression) {
22729             var node = createBaseNode(242 /* ReturnStatement */);
22730             node.expression = expression;
22731             // return in an ES2018 async generator must be awaited
22732             node.transformFlags |=
22733                 propagateChildFlags(node.expression) |
22734                     32 /* ContainsES2018 */ |
22735                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
22736             return node;
22737         }
22738         // @api
22739         function updateReturnStatement(node, expression) {
22740             return node.expression !== expression
22741                 ? update(createReturnStatement(expression), node)
22742                 : node;
22743         }
22744         // @api
22745         function createWithStatement(expression, statement) {
22746             var node = createBaseNode(243 /* WithStatement */);
22747             node.expression = expression;
22748             node.statement = asEmbeddedStatement(statement);
22749             node.transformFlags |=
22750                 propagateChildFlags(node.expression) |
22751                     propagateChildFlags(node.statement);
22752             return node;
22753         }
22754         // @api
22755         function updateWithStatement(node, expression, statement) {
22756             return node.expression !== expression
22757                 || node.statement !== statement
22758                 ? update(createWithStatement(expression, statement), node)
22759                 : node;
22760         }
22761         // @api
22762         function createSwitchStatement(expression, caseBlock) {
22763             var node = createBaseNode(244 /* SwitchStatement */);
22764             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22765             node.caseBlock = caseBlock;
22766             node.transformFlags |=
22767                 propagateChildFlags(node.expression) |
22768                     propagateChildFlags(node.caseBlock);
22769             return node;
22770         }
22771         // @api
22772         function updateSwitchStatement(node, expression, caseBlock) {
22773             return node.expression !== expression
22774                 || node.caseBlock !== caseBlock
22775                 ? update(createSwitchStatement(expression, caseBlock), node)
22776                 : node;
22777         }
22778         // @api
22779         function createLabeledStatement(label, statement) {
22780             var node = createBaseNode(245 /* LabeledStatement */);
22781             node.label = asName(label);
22782             node.statement = asEmbeddedStatement(statement);
22783             node.transformFlags |=
22784                 propagateChildFlags(node.label) |
22785                     propagateChildFlags(node.statement);
22786             return node;
22787         }
22788         // @api
22789         function updateLabeledStatement(node, label, statement) {
22790             return node.label !== label
22791                 || node.statement !== statement
22792                 ? update(createLabeledStatement(label, statement), node)
22793                 : node;
22794         }
22795         // @api
22796         function createThrowStatement(expression) {
22797             var node = createBaseNode(246 /* ThrowStatement */);
22798             node.expression = expression;
22799             node.transformFlags |= propagateChildFlags(node.expression);
22800             return node;
22801         }
22802         // @api
22803         function updateThrowStatement(node, expression) {
22804             return node.expression !== expression
22805                 ? update(createThrowStatement(expression), node)
22806                 : node;
22807         }
22808         // @api
22809         function createTryStatement(tryBlock, catchClause, finallyBlock) {
22810             var node = createBaseNode(247 /* TryStatement */);
22811             node.tryBlock = tryBlock;
22812             node.catchClause = catchClause;
22813             node.finallyBlock = finallyBlock;
22814             node.transformFlags |=
22815                 propagateChildFlags(node.tryBlock) |
22816                     propagateChildFlags(node.catchClause) |
22817                     propagateChildFlags(node.finallyBlock);
22818             return node;
22819         }
22820         // @api
22821         function updateTryStatement(node, tryBlock, catchClause, finallyBlock) {
22822             return node.tryBlock !== tryBlock
22823                 || node.catchClause !== catchClause
22824                 || node.finallyBlock !== finallyBlock
22825                 ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node)
22826                 : node;
22827         }
22828         // @api
22829         function createDebuggerStatement() {
22830             return createBaseNode(248 /* DebuggerStatement */);
22831         }
22832         // @api
22833         function createVariableDeclaration(name, exclamationToken, type, initializer) {
22834             var node = createBaseVariableLikeDeclaration(249 /* VariableDeclaration */, 
22835             /*decorators*/ undefined, 
22836             /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
22837             node.exclamationToken = exclamationToken;
22838             node.transformFlags |= propagateChildFlags(node.exclamationToken);
22839             if (exclamationToken) {
22840                 node.transformFlags |= 1 /* ContainsTypeScript */;
22841             }
22842             return node;
22843         }
22844         // @api
22845         function updateVariableDeclaration(node, name, exclamationToken, type, initializer) {
22846             return node.name !== name
22847                 || node.type !== type
22848                 || node.exclamationToken !== exclamationToken
22849                 || node.initializer !== initializer
22850                 ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node)
22851                 : node;
22852         }
22853         // @api
22854         function createVariableDeclarationList(declarations, flags) {
22855             if (flags === void 0) { flags = 0 /* None */; }
22856             var node = createBaseNode(250 /* VariableDeclarationList */);
22857             node.flags |= flags & 3 /* BlockScoped */;
22858             node.declarations = createNodeArray(declarations);
22859             node.transformFlags |=
22860                 propagateChildrenFlags(node.declarations) |
22861                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
22862             if (flags & 3 /* BlockScoped */) {
22863                 node.transformFlags |=
22864                     256 /* ContainsES2015 */ |
22865                         65536 /* ContainsBlockScopedBinding */;
22866             }
22867             return node;
22868         }
22869         // @api
22870         function updateVariableDeclarationList(node, declarations) {
22871             return node.declarations !== declarations
22872                 ? update(createVariableDeclarationList(declarations, node.flags), node)
22873                 : node;
22874         }
22875         // @api
22876         function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22877             var node = createBaseFunctionLikeDeclaration(251 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
22878             node.asteriskToken = asteriskToken;
22879             if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22880                 node.transformFlags = 1 /* ContainsTypeScript */;
22881             }
22882             else {
22883                 node.transformFlags |=
22884                     propagateChildFlags(node.asteriskToken) |
22885                         1048576 /* ContainsHoistedDeclarationOrCompletion */;
22886                 if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22887                     if (node.asteriskToken) {
22888                         node.transformFlags |= 32 /* ContainsES2018 */;
22889                     }
22890                     else {
22891                         node.transformFlags |= 64 /* ContainsES2017 */;
22892                     }
22893                 }
22894                 else if (node.asteriskToken) {
22895                     node.transformFlags |= 512 /* ContainsGenerator */;
22896                 }
22897             }
22898             return node;
22899         }
22900         // @api
22901         function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22902             return node.decorators !== decorators
22903                 || node.modifiers !== modifiers
22904                 || node.asteriskToken !== asteriskToken
22905                 || node.name !== name
22906                 || node.typeParameters !== typeParameters
22907                 || node.parameters !== parameters
22908                 || node.type !== type
22909                 || node.body !== body
22910                 ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
22911                 : node;
22912         }
22913         // @api
22914         function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
22915             var node = createBaseClassLikeDeclaration(252 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members);
22916             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22917                 node.transformFlags = 1 /* ContainsTypeScript */;
22918             }
22919             else {
22920                 node.transformFlags |= 256 /* ContainsES2015 */;
22921                 if (node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */) {
22922                     node.transformFlags |= 1 /* ContainsTypeScript */;
22923                 }
22924             }
22925             return node;
22926         }
22927         // @api
22928         function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
22929             return node.decorators !== decorators
22930                 || node.modifiers !== modifiers
22931                 || node.name !== name
22932                 || node.typeParameters !== typeParameters
22933                 || node.heritageClauses !== heritageClauses
22934                 || node.members !== members
22935                 ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
22936                 : node;
22937         }
22938         // @api
22939         function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
22940             var node = createBaseInterfaceOrClassLikeDeclaration(253 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses);
22941             node.members = createNodeArray(members);
22942             node.transformFlags = 1 /* ContainsTypeScript */;
22943             return node;
22944         }
22945         // @api
22946         function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
22947             return node.decorators !== decorators
22948                 || node.modifiers !== modifiers
22949                 || node.name !== name
22950                 || node.typeParameters !== typeParameters
22951                 || node.heritageClauses !== heritageClauses
22952                 || node.members !== members
22953                 ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
22954                 : node;
22955         }
22956         // @api
22957         function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
22958             var node = createBaseGenericNamedDeclaration(254 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters);
22959             node.type = type;
22960             node.transformFlags = 1 /* ContainsTypeScript */;
22961             return node;
22962         }
22963         // @api
22964         function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
22965             return node.decorators !== decorators
22966                 || node.modifiers !== modifiers
22967                 || node.name !== name
22968                 || node.typeParameters !== typeParameters
22969                 || node.type !== type
22970                 ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
22971                 : node;
22972         }
22973         // @api
22974         function createEnumDeclaration(decorators, modifiers, name, members) {
22975             var node = createBaseNamedDeclaration(255 /* EnumDeclaration */, decorators, modifiers, name);
22976             node.members = createNodeArray(members);
22977             node.transformFlags |=
22978                 propagateChildrenFlags(node.members) |
22979                     1 /* ContainsTypeScript */;
22980             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await`
22981             return node;
22982         }
22983         // @api
22984         function updateEnumDeclaration(node, decorators, modifiers, name, members) {
22985             return node.decorators !== decorators
22986                 || node.modifiers !== modifiers
22987                 || node.name !== name
22988                 || node.members !== members
22989                 ? update(createEnumDeclaration(decorators, modifiers, name, members), node)
22990                 : node;
22991         }
22992         // @api
22993         function createModuleDeclaration(decorators, modifiers, name, body, flags) {
22994             if (flags === void 0) { flags = 0 /* None */; }
22995             var node = createBaseDeclaration(256 /* ModuleDeclaration */, decorators, modifiers);
22996             node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
22997             node.name = name;
22998             node.body = body;
22999             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
23000                 node.transformFlags = 1 /* ContainsTypeScript */;
23001             }
23002             else {
23003                 node.transformFlags |=
23004                     propagateChildFlags(node.name) |
23005                         propagateChildFlags(node.body) |
23006                         1 /* ContainsTypeScript */;
23007             }
23008             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`.
23009             return node;
23010         }
23011         // @api
23012         function updateModuleDeclaration(node, decorators, modifiers, name, body) {
23013             return node.decorators !== decorators
23014                 || node.modifiers !== modifiers
23015                 || node.name !== name
23016                 || node.body !== body
23017                 ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
23018                 : node;
23019         }
23020         // @api
23021         function createModuleBlock(statements) {
23022             var node = createBaseNode(257 /* ModuleBlock */);
23023             node.statements = createNodeArray(statements);
23024             node.transformFlags |= propagateChildrenFlags(node.statements);
23025             return node;
23026         }
23027         // @api
23028         function updateModuleBlock(node, statements) {
23029             return node.statements !== statements
23030                 ? update(createModuleBlock(statements), node)
23031                 : node;
23032         }
23033         // @api
23034         function createCaseBlock(clauses) {
23035             var node = createBaseNode(258 /* CaseBlock */);
23036             node.clauses = createNodeArray(clauses);
23037             node.transformFlags |= propagateChildrenFlags(node.clauses);
23038             return node;
23039         }
23040         // @api
23041         function updateCaseBlock(node, clauses) {
23042             return node.clauses !== clauses
23043                 ? update(createCaseBlock(clauses), node)
23044                 : node;
23045         }
23046         // @api
23047         function createNamespaceExportDeclaration(name) {
23048             var node = createBaseNamedDeclaration(259 /* NamespaceExportDeclaration */, 
23049             /*decorators*/ undefined, 
23050             /*modifiers*/ undefined, name);
23051             node.transformFlags = 1 /* ContainsTypeScript */;
23052             return node;
23053         }
23054         // @api
23055         function updateNamespaceExportDeclaration(node, name) {
23056             return node.name !== name
23057                 ? update(createNamespaceExportDeclaration(name), node)
23058                 : node;
23059         }
23060         // @api
23061         function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
23062             var node = createBaseNamedDeclaration(260 /* ImportEqualsDeclaration */, decorators, modifiers, name);
23063             node.moduleReference = moduleReference;
23064             node.transformFlags |= propagateChildFlags(node.moduleReference);
23065             if (!ts.isExternalModuleReference(node.moduleReference))
23066                 node.transformFlags |= 1 /* ContainsTypeScript */;
23067             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context
23068             return node;
23069         }
23070         // @api
23071         function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
23072             return node.decorators !== decorators
23073                 || node.modifiers !== modifiers
23074                 || node.name !== name
23075                 || node.moduleReference !== moduleReference
23076                 ? update(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
23077                 : node;
23078         }
23079         // @api
23080         function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
23081             var node = createBaseDeclaration(261 /* ImportDeclaration */, decorators, modifiers);
23082             node.importClause = importClause;
23083             node.moduleSpecifier = moduleSpecifier;
23084             node.transformFlags |=
23085                 propagateChildFlags(node.importClause) |
23086                     propagateChildFlags(node.moduleSpecifier);
23087             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23088             return node;
23089         }
23090         // @api
23091         function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
23092             return node.decorators !== decorators
23093                 || node.modifiers !== modifiers
23094                 || node.importClause !== importClause
23095                 || node.moduleSpecifier !== moduleSpecifier
23096                 ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
23097                 : node;
23098         }
23099         // @api
23100         function createImportClause(isTypeOnly, name, namedBindings) {
23101             var node = createBaseNode(262 /* ImportClause */);
23102             node.isTypeOnly = isTypeOnly;
23103             node.name = name;
23104             node.namedBindings = namedBindings;
23105             node.transformFlags |=
23106                 propagateChildFlags(node.name) |
23107                     propagateChildFlags(node.namedBindings);
23108             if (isTypeOnly) {
23109                 node.transformFlags |= 1 /* ContainsTypeScript */;
23110             }
23111             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23112             return node;
23113         }
23114         // @api
23115         function updateImportClause(node, isTypeOnly, name, namedBindings) {
23116             return node.isTypeOnly !== isTypeOnly
23117                 || node.name !== name
23118                 || node.namedBindings !== namedBindings
23119                 ? update(createImportClause(isTypeOnly, name, namedBindings), node)
23120                 : node;
23121         }
23122         // @api
23123         function createNamespaceImport(name) {
23124             var node = createBaseNode(263 /* NamespaceImport */);
23125             node.name = name;
23126             node.transformFlags |= propagateChildFlags(node.name);
23127             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23128             return node;
23129         }
23130         // @api
23131         function updateNamespaceImport(node, name) {
23132             return node.name !== name
23133                 ? update(createNamespaceImport(name), node)
23134                 : node;
23135         }
23136         // @api
23137         function createNamespaceExport(name) {
23138             var node = createBaseNode(269 /* NamespaceExport */);
23139             node.name = name;
23140             node.transformFlags |=
23141                 propagateChildFlags(node.name) |
23142                     4 /* ContainsESNext */;
23143             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23144             return node;
23145         }
23146         // @api
23147         function updateNamespaceExport(node, name) {
23148             return node.name !== name
23149                 ? update(createNamespaceExport(name), node)
23150                 : node;
23151         }
23152         // @api
23153         function createNamedImports(elements) {
23154             var node = createBaseNode(264 /* NamedImports */);
23155             node.elements = createNodeArray(elements);
23156             node.transformFlags |= propagateChildrenFlags(node.elements);
23157             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23158             return node;
23159         }
23160         // @api
23161         function updateNamedImports(node, elements) {
23162             return node.elements !== elements
23163                 ? update(createNamedImports(elements), node)
23164                 : node;
23165         }
23166         // @api
23167         function createImportSpecifier(propertyName, name) {
23168             var node = createBaseNode(265 /* ImportSpecifier */);
23169             node.propertyName = propertyName;
23170             node.name = name;
23171             node.transformFlags |=
23172                 propagateChildFlags(node.propertyName) |
23173                     propagateChildFlags(node.name);
23174             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23175             return node;
23176         }
23177         // @api
23178         function updateImportSpecifier(node, propertyName, name) {
23179             return node.propertyName !== propertyName
23180                 || node.name !== name
23181                 ? update(createImportSpecifier(propertyName, name), node)
23182                 : node;
23183         }
23184         // @api
23185         function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
23186             var node = createBaseDeclaration(266 /* ExportAssignment */, decorators, modifiers);
23187             node.isExportEquals = isExportEquals;
23188             node.expression = isExportEquals
23189                 ? parenthesizerRules().parenthesizeRightSideOfBinary(62 /* EqualsToken */, /*leftSide*/ undefined, expression)
23190                 : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression);
23191             node.transformFlags |= propagateChildFlags(node.expression);
23192             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23193             return node;
23194         }
23195         // @api
23196         function updateExportAssignment(node, decorators, modifiers, expression) {
23197             return node.decorators !== decorators
23198                 || node.modifiers !== modifiers
23199                 || node.expression !== expression
23200                 ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
23201                 : node;
23202         }
23203         // @api
23204         function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) {
23205             var node = createBaseDeclaration(267 /* ExportDeclaration */, decorators, modifiers);
23206             node.isTypeOnly = isTypeOnly;
23207             node.exportClause = exportClause;
23208             node.moduleSpecifier = moduleSpecifier;
23209             node.transformFlags |=
23210                 propagateChildFlags(node.exportClause) |
23211                     propagateChildFlags(node.moduleSpecifier);
23212             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23213             return node;
23214         }
23215         // @api
23216         function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) {
23217             return node.decorators !== decorators
23218                 || node.modifiers !== modifiers
23219                 || node.isTypeOnly !== isTypeOnly
23220                 || node.exportClause !== exportClause
23221                 || node.moduleSpecifier !== moduleSpecifier
23222                 ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier), node)
23223                 : node;
23224         }
23225         // @api
23226         function createNamedExports(elements) {
23227             var node = createBaseNode(268 /* NamedExports */);
23228             node.elements = createNodeArray(elements);
23229             node.transformFlags |= propagateChildrenFlags(node.elements);
23230             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23231             return node;
23232         }
23233         // @api
23234         function updateNamedExports(node, elements) {
23235             return node.elements !== elements
23236                 ? update(createNamedExports(elements), node)
23237                 : node;
23238         }
23239         // @api
23240         function createExportSpecifier(propertyName, name) {
23241             var node = createBaseNode(270 /* ExportSpecifier */);
23242             node.propertyName = asName(propertyName);
23243             node.name = asName(name);
23244             node.transformFlags |=
23245                 propagateChildFlags(node.propertyName) |
23246                     propagateChildFlags(node.name);
23247             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23248             return node;
23249         }
23250         // @api
23251         function updateExportSpecifier(node, propertyName, name) {
23252             return node.propertyName !== propertyName
23253                 || node.name !== name
23254                 ? update(createExportSpecifier(propertyName, name), node)
23255                 : node;
23256         }
23257         // @api
23258         function createMissingDeclaration() {
23259             var node = createBaseDeclaration(271 /* MissingDeclaration */, 
23260             /*decorators*/ undefined, 
23261             /*modifiers*/ undefined);
23262             return node;
23263         }
23264         //
23265         // Module references
23266         //
23267         // @api
23268         function createExternalModuleReference(expression) {
23269             var node = createBaseNode(272 /* ExternalModuleReference */);
23270             node.expression = expression;
23271             node.transformFlags |= propagateChildFlags(node.expression);
23272             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23273             return node;
23274         }
23275         // @api
23276         function updateExternalModuleReference(node, expression) {
23277             return node.expression !== expression
23278                 ? update(createExternalModuleReference(expression), node)
23279                 : node;
23280         }
23281         //
23282         // JSDoc
23283         //
23284         // @api
23285         // createJSDocAllType
23286         // createJSDocUnknownType
23287         function createJSDocPrimaryTypeWorker(kind) {
23288             return createBaseNode(kind);
23289         }
23290         // @api
23291         // createJSDocNonNullableType
23292         // createJSDocNullableType
23293         // createJSDocOptionalType
23294         // createJSDocVariadicType
23295         // createJSDocNamepathType
23296         function createJSDocUnaryTypeWorker(kind, type) {
23297             var node = createBaseNode(kind);
23298             node.type = type;
23299             return node;
23300         }
23301         // @api
23302         // updateJSDocNonNullableType
23303         // updateJSDocNullableType
23304         // updateJSDocOptionalType
23305         // updateJSDocVariadicType
23306         // updateJSDocNamepathType
23307         function updateJSDocUnaryTypeWorker(kind, node, type) {
23308             return node.type !== type
23309                 ? update(createJSDocUnaryTypeWorker(kind, type), node)
23310                 : node;
23311         }
23312         // @api
23313         function createJSDocFunctionType(parameters, type) {
23314             var node = createBaseSignatureDeclaration(308 /* JSDocFunctionType */, 
23315             /*decorators*/ undefined, 
23316             /*modifiers*/ undefined, 
23317             /*name*/ undefined, 
23318             /*typeParameters*/ undefined, parameters, type);
23319             return node;
23320         }
23321         // @api
23322         function updateJSDocFunctionType(node, parameters, type) {
23323             return node.parameters !== parameters
23324                 || node.type !== type
23325                 ? update(createJSDocFunctionType(parameters, type), node)
23326                 : node;
23327         }
23328         // @api
23329         function createJSDocTypeLiteral(propertyTags, isArrayType) {
23330             if (isArrayType === void 0) { isArrayType = false; }
23331             var node = createBaseNode(312 /* JSDocTypeLiteral */);
23332             node.jsDocPropertyTags = asNodeArray(propertyTags);
23333             node.isArrayType = isArrayType;
23334             return node;
23335         }
23336         // @api
23337         function updateJSDocTypeLiteral(node, propertyTags, isArrayType) {
23338             return node.jsDocPropertyTags !== propertyTags
23339                 || node.isArrayType !== isArrayType
23340                 ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node)
23341                 : node;
23342         }
23343         // @api
23344         function createJSDocTypeExpression(type) {
23345             var node = createBaseNode(301 /* JSDocTypeExpression */);
23346             node.type = type;
23347             return node;
23348         }
23349         // @api
23350         function updateJSDocTypeExpression(node, type) {
23351             return node.type !== type
23352                 ? update(createJSDocTypeExpression(type), node)
23353                 : node;
23354         }
23355         // @api
23356         function createJSDocSignature(typeParameters, parameters, type) {
23357             var node = createBaseNode(313 /* JSDocSignature */);
23358             node.typeParameters = asNodeArray(typeParameters);
23359             node.parameters = createNodeArray(parameters);
23360             node.type = type;
23361             return node;
23362         }
23363         // @api
23364         function updateJSDocSignature(node, typeParameters, parameters, type) {
23365             return node.typeParameters !== typeParameters
23366                 || node.parameters !== parameters
23367                 || node.type !== type
23368                 ? update(createJSDocSignature(typeParameters, parameters, type), node)
23369                 : node;
23370         }
23371         function getDefaultTagName(node) {
23372             var defaultTagName = getDefaultTagNameForKind(node.kind);
23373             return node.tagName.escapedText === ts.escapeLeadingUnderscores(defaultTagName)
23374                 ? node.tagName
23375                 : createIdentifier(defaultTagName);
23376         }
23377         // @api
23378         function createBaseJSDocTag(kind, tagName, comment) {
23379             var node = createBaseNode(kind);
23380             node.tagName = tagName;
23381             node.comment = comment;
23382             return node;
23383         }
23384         // @api
23385         function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) {
23386             var node = createBaseJSDocTag(330 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment);
23387             node.constraint = constraint;
23388             node.typeParameters = createNodeArray(typeParameters);
23389             return node;
23390         }
23391         // @api
23392         function updateJSDocTemplateTag(node, tagName, constraint, typeParameters, comment) {
23393             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23394             return node.tagName !== tagName
23395                 || node.constraint !== constraint
23396                 || node.typeParameters !== typeParameters
23397                 || node.comment !== comment
23398                 ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node)
23399                 : node;
23400         }
23401         // @api
23402         function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) {
23403             var node = createBaseJSDocTag(331 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment);
23404             node.typeExpression = typeExpression;
23405             node.fullName = fullName;
23406             node.name = ts.getJSDocTypeAliasName(fullName);
23407             return node;
23408         }
23409         // @api
23410         function updateJSDocTypedefTag(node, tagName, typeExpression, fullName, comment) {
23411             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23412             return node.tagName !== tagName
23413                 || node.typeExpression !== typeExpression
23414                 || node.fullName !== fullName
23415                 || node.comment !== comment
23416                 ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node)
23417                 : node;
23418         }
23419         // @api
23420         function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23421             var node = createBaseJSDocTag(326 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment);
23422             node.typeExpression = typeExpression;
23423             node.name = name;
23424             node.isNameFirst = !!isNameFirst;
23425             node.isBracketed = isBracketed;
23426             return node;
23427         }
23428         // @api
23429         function updateJSDocParameterTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23430             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23431             return node.tagName !== tagName
23432                 || node.name !== name
23433                 || node.isBracketed !== isBracketed
23434                 || node.typeExpression !== typeExpression
23435                 || node.isNameFirst !== isNameFirst
23436                 || node.comment !== comment
23437                 ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
23438                 : node;
23439         }
23440         // @api
23441         function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23442             var node = createBaseJSDocTag(333 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment);
23443             node.typeExpression = typeExpression;
23444             node.name = name;
23445             node.isNameFirst = !!isNameFirst;
23446             node.isBracketed = isBracketed;
23447             return node;
23448         }
23449         // @api
23450         function updateJSDocPropertyTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23451             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23452             return node.tagName !== tagName
23453                 || node.name !== name
23454                 || node.isBracketed !== isBracketed
23455                 || node.typeExpression !== typeExpression
23456                 || node.isNameFirst !== isNameFirst
23457                 || node.comment !== comment
23458                 ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
23459                 : node;
23460         }
23461         // @api
23462         function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) {
23463             var node = createBaseJSDocTag(324 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment);
23464             node.typeExpression = typeExpression;
23465             node.fullName = fullName;
23466             node.name = ts.getJSDocTypeAliasName(fullName);
23467             return node;
23468         }
23469         // @api
23470         function updateJSDocCallbackTag(node, tagName, typeExpression, fullName, comment) {
23471             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23472             return node.tagName !== tagName
23473                 || node.typeExpression !== typeExpression
23474                 || node.fullName !== fullName
23475                 || node.comment !== comment
23476                 ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node)
23477                 : node;
23478         }
23479         // @api
23480         function createJSDocAugmentsTag(tagName, className, comment) {
23481             var node = createBaseJSDocTag(315 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment);
23482             node.class = className;
23483             return node;
23484         }
23485         // @api
23486         function updateJSDocAugmentsTag(node, tagName, className, comment) {
23487             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23488             return node.tagName !== tagName
23489                 || node.class !== className
23490                 || node.comment !== comment
23491                 ? update(createJSDocAugmentsTag(tagName, className, comment), node)
23492                 : node;
23493         }
23494         // @api
23495         function createJSDocImplementsTag(tagName, className, comment) {
23496             var node = createBaseJSDocTag(316 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment);
23497             node.class = className;
23498             return node;
23499         }
23500         // @api
23501         function createJSDocSeeTag(tagName, name, comment) {
23502             var node = createBaseJSDocTag(332 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment);
23503             node.name = name;
23504             return node;
23505         }
23506         // @api
23507         function updateJSDocSeeTag(node, tagName, name, comment) {
23508             return node.tagName !== tagName
23509                 || node.name !== name
23510                 || node.comment !== comment
23511                 ? update(createJSDocSeeTag(tagName, name, comment), node)
23512                 : node;
23513         }
23514         // @api
23515         function createJSDocNameReference(name) {
23516             var node = createBaseNode(302 /* JSDocNameReference */);
23517             node.name = name;
23518             return node;
23519         }
23520         // @api
23521         function updateJSDocNameReference(node, name) {
23522             return node.name !== name
23523                 ? update(createJSDocNameReference(name), node)
23524                 : node;
23525         }
23526         // @api
23527         function updateJSDocImplementsTag(node, tagName, className, comment) {
23528             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23529             return node.tagName !== tagName
23530                 || node.class !== className
23531                 || node.comment !== comment
23532                 ? update(createJSDocImplementsTag(tagName, className, comment), node)
23533                 : node;
23534         }
23535         // @api
23536         // createJSDocAuthorTag
23537         // createJSDocClassTag
23538         // createJSDocPublicTag
23539         // createJSDocPrivateTag
23540         // createJSDocProtectedTag
23541         // createJSDocReadonlyTag
23542         // createJSDocDeprecatedTag
23543         function createJSDocSimpleTagWorker(kind, tagName, comment) {
23544             var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
23545             return node;
23546         }
23547         // @api
23548         // updateJSDocAuthorTag
23549         // updateJSDocClassTag
23550         // updateJSDocPublicTag
23551         // updateJSDocPrivateTag
23552         // updateJSDocProtectedTag
23553         // updateJSDocReadonlyTag
23554         // updateJSDocDeprecatedTag
23555         function updateJSDocSimpleTagWorker(kind, node, tagName, comment) {
23556             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23557             return node.tagName !== tagName
23558                 || node.comment !== comment
23559                 ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) :
23560                 node;
23561         }
23562         // @api
23563         // createJSDocTypeTag
23564         // createJSDocReturnTag
23565         // createJSDocThisTag
23566         // createJSDocEnumTag
23567         function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) {
23568             var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
23569             node.typeExpression = typeExpression;
23570             return node;
23571         }
23572         // @api
23573         // updateJSDocTypeTag
23574         // updateJSDocReturnTag
23575         // updateJSDocThisTag
23576         // updateJSDocEnumTag
23577         function updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment) {
23578             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23579             return node.tagName !== tagName
23580                 || node.typeExpression !== typeExpression
23581                 || node.comment !== comment
23582                 ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node)
23583                 : node;
23584         }
23585         // @api
23586         function createJSDocUnknownTag(tagName, comment) {
23587             var node = createBaseJSDocTag(314 /* JSDocTag */, tagName, comment);
23588             return node;
23589         }
23590         // @api
23591         function updateJSDocUnknownTag(node, tagName, comment) {
23592             return node.tagName !== tagName
23593                 || node.comment !== comment
23594                 ? update(createJSDocUnknownTag(tagName, comment), node)
23595                 : node;
23596         }
23597         // @api
23598         function createJSDocComment(comment, tags) {
23599             var node = createBaseNode(311 /* JSDocComment */);
23600             node.comment = comment;
23601             node.tags = asNodeArray(tags);
23602             return node;
23603         }
23604         // @api
23605         function updateJSDocComment(node, comment, tags) {
23606             return node.comment !== comment
23607                 || node.tags !== tags
23608                 ? update(createJSDocComment(comment, tags), node)
23609                 : node;
23610         }
23611         //
23612         // JSX
23613         //
23614         // @api
23615         function createJsxElement(openingElement, children, closingElement) {
23616             var node = createBaseNode(273 /* JsxElement */);
23617             node.openingElement = openingElement;
23618             node.children = createNodeArray(children);
23619             node.closingElement = closingElement;
23620             node.transformFlags |=
23621                 propagateChildFlags(node.openingElement) |
23622                     propagateChildrenFlags(node.children) |
23623                     propagateChildFlags(node.closingElement) |
23624                     2 /* ContainsJsx */;
23625             return node;
23626         }
23627         // @api
23628         function updateJsxElement(node, openingElement, children, closingElement) {
23629             return node.openingElement !== openingElement
23630                 || node.children !== children
23631                 || node.closingElement !== closingElement
23632                 ? update(createJsxElement(openingElement, children, closingElement), node)
23633                 : node;
23634         }
23635         // @api
23636         function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
23637             var node = createBaseNode(274 /* JsxSelfClosingElement */);
23638             node.tagName = tagName;
23639             node.typeArguments = asNodeArray(typeArguments);
23640             node.attributes = attributes;
23641             node.transformFlags |=
23642                 propagateChildFlags(node.tagName) |
23643                     propagateChildrenFlags(node.typeArguments) |
23644                     propagateChildFlags(node.attributes) |
23645                     2 /* ContainsJsx */;
23646             if (node.typeArguments) {
23647                 node.transformFlags |= 1 /* ContainsTypeScript */;
23648             }
23649             return node;
23650         }
23651         // @api
23652         function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
23653             return node.tagName !== tagName
23654                 || node.typeArguments !== typeArguments
23655                 || node.attributes !== attributes
23656                 ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
23657                 : node;
23658         }
23659         // @api
23660         function createJsxOpeningElement(tagName, typeArguments, attributes) {
23661             var node = createBaseNode(275 /* JsxOpeningElement */);
23662             node.tagName = tagName;
23663             node.typeArguments = asNodeArray(typeArguments);
23664             node.attributes = attributes;
23665             node.transformFlags |=
23666                 propagateChildFlags(node.tagName) |
23667                     propagateChildrenFlags(node.typeArguments) |
23668                     propagateChildFlags(node.attributes) |
23669                     2 /* ContainsJsx */;
23670             if (typeArguments) {
23671                 node.transformFlags |= 1 /* ContainsTypeScript */;
23672             }
23673             return node;
23674         }
23675         // @api
23676         function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
23677             return node.tagName !== tagName
23678                 || node.typeArguments !== typeArguments
23679                 || node.attributes !== attributes
23680                 ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node)
23681                 : node;
23682         }
23683         // @api
23684         function createJsxClosingElement(tagName) {
23685             var node = createBaseNode(276 /* JsxClosingElement */);
23686             node.tagName = tagName;
23687             node.transformFlags |=
23688                 propagateChildFlags(node.tagName) |
23689                     2 /* ContainsJsx */;
23690             return node;
23691         }
23692         // @api
23693         function updateJsxClosingElement(node, tagName) {
23694             return node.tagName !== tagName
23695                 ? update(createJsxClosingElement(tagName), node)
23696                 : node;
23697         }
23698         // @api
23699         function createJsxFragment(openingFragment, children, closingFragment) {
23700             var node = createBaseNode(277 /* JsxFragment */);
23701             node.openingFragment = openingFragment;
23702             node.children = createNodeArray(children);
23703             node.closingFragment = closingFragment;
23704             node.transformFlags |=
23705                 propagateChildFlags(node.openingFragment) |
23706                     propagateChildrenFlags(node.children) |
23707                     propagateChildFlags(node.closingFragment) |
23708                     2 /* ContainsJsx */;
23709             return node;
23710         }
23711         // @api
23712         function updateJsxFragment(node, openingFragment, children, closingFragment) {
23713             return node.openingFragment !== openingFragment
23714                 || node.children !== children
23715                 || node.closingFragment !== closingFragment
23716                 ? update(createJsxFragment(openingFragment, children, closingFragment), node)
23717                 : node;
23718         }
23719         // @api
23720         function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
23721             var node = createBaseNode(11 /* JsxText */);
23722             node.text = text;
23723             node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
23724             node.transformFlags |= 2 /* ContainsJsx */;
23725             return node;
23726         }
23727         // @api
23728         function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
23729             return node.text !== text
23730                 || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
23731                 ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
23732                 : node;
23733         }
23734         // @api
23735         function createJsxOpeningFragment() {
23736             var node = createBaseNode(278 /* JsxOpeningFragment */);
23737             node.transformFlags |= 2 /* ContainsJsx */;
23738             return node;
23739         }
23740         // @api
23741         function createJsxJsxClosingFragment() {
23742             var node = createBaseNode(279 /* JsxClosingFragment */);
23743             node.transformFlags |= 2 /* ContainsJsx */;
23744             return node;
23745         }
23746         // @api
23747         function createJsxAttribute(name, initializer) {
23748             var node = createBaseNode(280 /* JsxAttribute */);
23749             node.name = name;
23750             node.initializer = initializer;
23751             node.transformFlags |=
23752                 propagateChildFlags(node.name) |
23753                     propagateChildFlags(node.initializer) |
23754                     2 /* ContainsJsx */;
23755             return node;
23756         }
23757         // @api
23758         function updateJsxAttribute(node, name, initializer) {
23759             return node.name !== name
23760                 || node.initializer !== initializer
23761                 ? update(createJsxAttribute(name, initializer), node)
23762                 : node;
23763         }
23764         // @api
23765         function createJsxAttributes(properties) {
23766             var node = createBaseNode(281 /* JsxAttributes */);
23767             node.properties = createNodeArray(properties);
23768             node.transformFlags |=
23769                 propagateChildrenFlags(node.properties) |
23770                     2 /* ContainsJsx */;
23771             return node;
23772         }
23773         // @api
23774         function updateJsxAttributes(node, properties) {
23775             return node.properties !== properties
23776                 ? update(createJsxAttributes(properties), node)
23777                 : node;
23778         }
23779         // @api
23780         function createJsxSpreadAttribute(expression) {
23781             var node = createBaseNode(282 /* JsxSpreadAttribute */);
23782             node.expression = expression;
23783             node.transformFlags |=
23784                 propagateChildFlags(node.expression) |
23785                     2 /* ContainsJsx */;
23786             return node;
23787         }
23788         // @api
23789         function updateJsxSpreadAttribute(node, expression) {
23790             return node.expression !== expression
23791                 ? update(createJsxSpreadAttribute(expression), node)
23792                 : node;
23793         }
23794         // @api
23795         function createJsxExpression(dotDotDotToken, expression) {
23796             var node = createBaseNode(283 /* JsxExpression */);
23797             node.dotDotDotToken = dotDotDotToken;
23798             node.expression = expression;
23799             node.transformFlags |=
23800                 propagateChildFlags(node.dotDotDotToken) |
23801                     propagateChildFlags(node.expression) |
23802                     2 /* ContainsJsx */;
23803             return node;
23804         }
23805         // @api
23806         function updateJsxExpression(node, expression) {
23807             return node.expression !== expression
23808                 ? update(createJsxExpression(node.dotDotDotToken, expression), node)
23809                 : node;
23810         }
23811         //
23812         // Clauses
23813         //
23814         // @api
23815         function createCaseClause(expression, statements) {
23816             var node = createBaseNode(284 /* CaseClause */);
23817             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23818             node.statements = createNodeArray(statements);
23819             node.transformFlags |=
23820                 propagateChildFlags(node.expression) |
23821                     propagateChildrenFlags(node.statements);
23822             return node;
23823         }
23824         // @api
23825         function updateCaseClause(node, expression, statements) {
23826             return node.expression !== expression
23827                 || node.statements !== statements
23828                 ? update(createCaseClause(expression, statements), node)
23829                 : node;
23830         }
23831         // @api
23832         function createDefaultClause(statements) {
23833             var node = createBaseNode(285 /* DefaultClause */);
23834             node.statements = createNodeArray(statements);
23835             node.transformFlags = propagateChildrenFlags(node.statements);
23836             return node;
23837         }
23838         // @api
23839         function updateDefaultClause(node, statements) {
23840             return node.statements !== statements
23841                 ? update(createDefaultClause(statements), node)
23842                 : node;
23843         }
23844         // @api
23845         function createHeritageClause(token, types) {
23846             var node = createBaseNode(286 /* HeritageClause */);
23847             node.token = token;
23848             node.types = createNodeArray(types);
23849             node.transformFlags |= propagateChildrenFlags(node.types);
23850             switch (token) {
23851                 case 93 /* ExtendsKeyword */:
23852                     node.transformFlags |= 256 /* ContainsES2015 */;
23853                     break;
23854                 case 116 /* ImplementsKeyword */:
23855                     node.transformFlags |= 1 /* ContainsTypeScript */;
23856                     break;
23857                 default:
23858                     return ts.Debug.assertNever(token);
23859             }
23860             return node;
23861         }
23862         // @api
23863         function updateHeritageClause(node, types) {
23864             return node.types !== types
23865                 ? update(createHeritageClause(node.token, types), node)
23866                 : node;
23867         }
23868         // @api
23869         function createCatchClause(variableDeclaration, block) {
23870             var node = createBaseNode(287 /* CatchClause */);
23871             variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration, 
23872             /*exclamationToken*/ undefined, 
23873             /*type*/ undefined, 
23874             /*initializer*/ undefined);
23875             node.variableDeclaration = variableDeclaration;
23876             node.block = block;
23877             node.transformFlags |=
23878                 propagateChildFlags(node.variableDeclaration) |
23879                     propagateChildFlags(node.block);
23880             if (!variableDeclaration)
23881                 node.transformFlags |= 16 /* ContainsES2019 */;
23882             return node;
23883         }
23884         // @api
23885         function updateCatchClause(node, variableDeclaration, block) {
23886             return node.variableDeclaration !== variableDeclaration
23887                 || node.block !== block
23888                 ? update(createCatchClause(variableDeclaration, block), node)
23889                 : node;
23890         }
23891         //
23892         // Property assignments
23893         //
23894         // @api
23895         function createPropertyAssignment(name, initializer) {
23896             var node = createBaseNamedDeclaration(288 /* PropertyAssignment */, 
23897             /*decorators*/ undefined, 
23898             /*modifiers*/ undefined, name);
23899             node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
23900             node.transformFlags |=
23901                 propagateChildFlags(node.name) |
23902                     propagateChildFlags(node.initializer);
23903             return node;
23904         }
23905         function finishUpdatePropertyAssignment(updated, original) {
23906             // copy children used only for error reporting
23907             if (original.decorators)
23908                 updated.decorators = original.decorators;
23909             if (original.modifiers)
23910                 updated.modifiers = original.modifiers;
23911             if (original.questionToken)
23912                 updated.questionToken = original.questionToken;
23913             if (original.exclamationToken)
23914                 updated.exclamationToken = original.exclamationToken;
23915             return update(updated, original);
23916         }
23917         // @api
23918         function updatePropertyAssignment(node, name, initializer) {
23919             return node.name !== name
23920                 || node.initializer !== initializer
23921                 ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node)
23922                 : node;
23923         }
23924         // @api
23925         function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
23926             var node = createBaseNamedDeclaration(289 /* ShorthandPropertyAssignment */, 
23927             /*decorators*/ undefined, 
23928             /*modifiers*/ undefined, name);
23929             node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer);
23930             node.transformFlags |=
23931                 propagateChildFlags(node.objectAssignmentInitializer) |
23932                     256 /* ContainsES2015 */;
23933             return node;
23934         }
23935         function finishUpdateShorthandPropertyAssignment(updated, original) {
23936             // copy children used only for error reporting
23937             if (original.decorators)
23938                 updated.decorators = original.decorators;
23939             if (original.modifiers)
23940                 updated.modifiers = original.modifiers;
23941             if (original.equalsToken)
23942                 updated.equalsToken = original.equalsToken;
23943             if (original.questionToken)
23944                 updated.questionToken = original.questionToken;
23945             if (original.exclamationToken)
23946                 updated.exclamationToken = original.exclamationToken;
23947             return update(updated, original);
23948         }
23949         // @api
23950         function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
23951             return node.name !== name
23952                 || node.objectAssignmentInitializer !== objectAssignmentInitializer
23953                 ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
23954                 : node;
23955         }
23956         // @api
23957         function createSpreadAssignment(expression) {
23958             var node = createBaseNode(290 /* SpreadAssignment */);
23959             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23960             node.transformFlags |=
23961                 propagateChildFlags(node.expression) |
23962                     32 /* ContainsES2018 */ |
23963                     16384 /* ContainsObjectRestOrSpread */;
23964             return node;
23965         }
23966         // @api
23967         function updateSpreadAssignment(node, expression) {
23968             return node.expression !== expression
23969                 ? update(createSpreadAssignment(expression), node)
23970                 : node;
23971         }
23972         //
23973         // Enum
23974         //
23975         // @api
23976         function createEnumMember(name, initializer) {
23977             var node = createBaseNode(291 /* EnumMember */);
23978             node.name = asName(name);
23979             node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
23980             node.transformFlags |=
23981                 propagateChildFlags(node.name) |
23982                     propagateChildFlags(node.initializer) |
23983                     1 /* ContainsTypeScript */;
23984             return node;
23985         }
23986         // @api
23987         function updateEnumMember(node, name, initializer) {
23988             return node.name !== name
23989                 || node.initializer !== initializer
23990                 ? update(createEnumMember(name, initializer), node)
23991                 : node;
23992         }
23993         //
23994         // Top-level nodes
23995         //
23996         // @api
23997         function createSourceFile(statements, endOfFileToken, flags) {
23998             var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */);
23999             node.statements = createNodeArray(statements);
24000             node.endOfFileToken = endOfFileToken;
24001             node.flags |= flags;
24002             node.fileName = "";
24003             node.text = "";
24004             node.languageVersion = 0;
24005             node.languageVariant = 0;
24006             node.scriptKind = 0;
24007             node.isDeclarationFile = false;
24008             node.hasNoDefaultLib = false;
24009             node.transformFlags |=
24010                 propagateChildrenFlags(node.statements) |
24011                     propagateChildFlags(node.endOfFileToken);
24012             return node;
24013         }
24014         function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
24015             var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */);
24016             for (var p in source) {
24017                 if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p))
24018                     continue;
24019                 node[p] = source[p];
24020             }
24021             node.flags |= source.flags;
24022             node.statements = createNodeArray(statements);
24023             node.endOfFileToken = source.endOfFileToken;
24024             node.isDeclarationFile = isDeclarationFile;
24025             node.referencedFiles = referencedFiles;
24026             node.typeReferenceDirectives = typeReferences;
24027             node.hasNoDefaultLib = hasNoDefaultLib;
24028             node.libReferenceDirectives = libReferences;
24029             node.transformFlags =
24030                 propagateChildrenFlags(node.statements) |
24031                     propagateChildFlags(node.endOfFileToken);
24032             return node;
24033         }
24034         // @api
24035         function updateSourceFile(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives) {
24036             if (isDeclarationFile === void 0) { isDeclarationFile = node.isDeclarationFile; }
24037             if (referencedFiles === void 0) { referencedFiles = node.referencedFiles; }
24038             if (typeReferenceDirectives === void 0) { typeReferenceDirectives = node.typeReferenceDirectives; }
24039             if (hasNoDefaultLib === void 0) { hasNoDefaultLib = node.hasNoDefaultLib; }
24040             if (libReferenceDirectives === void 0) { libReferenceDirectives = node.libReferenceDirectives; }
24041             return node.statements !== statements
24042                 || node.isDeclarationFile !== isDeclarationFile
24043                 || node.referencedFiles !== referencedFiles
24044                 || node.typeReferenceDirectives !== typeReferenceDirectives
24045                 || node.hasNoDefaultLib !== hasNoDefaultLib
24046                 || node.libReferenceDirectives !== libReferenceDirectives
24047                 ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node)
24048                 : node;
24049         }
24050         // @api
24051         function createBundle(sourceFiles, prepends) {
24052             if (prepends === void 0) { prepends = ts.emptyArray; }
24053             var node = createBaseNode(298 /* Bundle */);
24054             node.prepends = prepends;
24055             node.sourceFiles = sourceFiles;
24056             return node;
24057         }
24058         // @api
24059         function updateBundle(node, sourceFiles, prepends) {
24060             if (prepends === void 0) { prepends = ts.emptyArray; }
24061             return node.sourceFiles !== sourceFiles
24062                 || node.prepends !== prepends
24063                 ? update(createBundle(sourceFiles, prepends), node)
24064                 : node;
24065         }
24066         // @api
24067         function createUnparsedSource(prologues, syntheticReferences, texts) {
24068             var node = createBaseNode(299 /* UnparsedSource */);
24069             node.prologues = prologues;
24070             node.syntheticReferences = syntheticReferences;
24071             node.texts = texts;
24072             node.fileName = "";
24073             node.text = "";
24074             node.referencedFiles = ts.emptyArray;
24075             node.libReferenceDirectives = ts.emptyArray;
24076             node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
24077             return node;
24078         }
24079         function createBaseUnparsedNode(kind, data) {
24080             var node = createBaseNode(kind);
24081             node.data = data;
24082             return node;
24083         }
24084         // @api
24085         function createUnparsedPrologue(data) {
24086             return createBaseUnparsedNode(292 /* UnparsedPrologue */, data);
24087         }
24088         // @api
24089         function createUnparsedPrepend(data, texts) {
24090             var node = createBaseUnparsedNode(293 /* UnparsedPrepend */, data);
24091             node.texts = texts;
24092             return node;
24093         }
24094         // @api
24095         function createUnparsedTextLike(data, internal) {
24096             return createBaseUnparsedNode(internal ? 295 /* UnparsedInternalText */ : 294 /* UnparsedText */, data);
24097         }
24098         // @api
24099         function createUnparsedSyntheticReference(section) {
24100             var node = createBaseNode(296 /* UnparsedSyntheticReference */);
24101             node.data = section.data;
24102             node.section = section;
24103             return node;
24104         }
24105         // @api
24106         function createInputFiles() {
24107             var node = createBaseNode(300 /* InputFiles */);
24108             node.javascriptText = "";
24109             node.declarationText = "";
24110             return node;
24111         }
24112         //
24113         // Synthetic Nodes (used by checker)
24114         //
24115         // @api
24116         function createSyntheticExpression(type, isSpread, tupleNameSource) {
24117             if (isSpread === void 0) { isSpread = false; }
24118             var node = createBaseNode(227 /* SyntheticExpression */);
24119             node.type = type;
24120             node.isSpread = isSpread;
24121             node.tupleNameSource = tupleNameSource;
24122             return node;
24123         }
24124         // @api
24125         function createSyntaxList(children) {
24126             var node = createBaseNode(334 /* SyntaxList */);
24127             node._children = children;
24128             return node;
24129         }
24130         //
24131         // Transformation nodes
24132         //
24133         /**
24134          * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
24135          * order to preserve comments.
24136          *
24137          * @param original The original statement.
24138          */
24139         // @api
24140         function createNotEmittedStatement(original) {
24141             var node = createBaseNode(335 /* NotEmittedStatement */);
24142             node.original = original;
24143             ts.setTextRange(node, original);
24144             return node;
24145         }
24146         /**
24147          * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
24148          * order to preserve comments or sourcemap positions.
24149          *
24150          * @param expression The inner expression to emit.
24151          * @param original The original outer expression.
24152          */
24153         // @api
24154         function createPartiallyEmittedExpression(expression, original) {
24155             var node = createBaseNode(336 /* PartiallyEmittedExpression */);
24156             node.expression = expression;
24157             node.original = original;
24158             node.transformFlags |=
24159                 propagateChildFlags(node.expression) |
24160                     1 /* ContainsTypeScript */;
24161             ts.setTextRange(node, original);
24162             return node;
24163         }
24164         // @api
24165         function updatePartiallyEmittedExpression(node, expression) {
24166             return node.expression !== expression
24167                 ? update(createPartiallyEmittedExpression(expression, node.original), node)
24168                 : node;
24169         }
24170         function flattenCommaElements(node) {
24171             if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
24172                 if (ts.isCommaListExpression(node)) {
24173                     return node.elements;
24174                 }
24175                 if (ts.isBinaryExpression(node) && ts.isCommaToken(node.operatorToken)) {
24176                     return [node.left, node.right];
24177                 }
24178             }
24179             return node;
24180         }
24181         // @api
24182         function createCommaListExpression(elements) {
24183             var node = createBaseNode(337 /* CommaListExpression */);
24184             node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
24185             node.transformFlags |= propagateChildrenFlags(node.elements);
24186             return node;
24187         }
24188         // @api
24189         function updateCommaListExpression(node, elements) {
24190             return node.elements !== elements
24191                 ? update(createCommaListExpression(elements), node)
24192                 : node;
24193         }
24194         /**
24195          * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
24196          * order to properly emit exports.
24197          */
24198         // @api
24199         function createEndOfDeclarationMarker(original) {
24200             var node = createBaseNode(339 /* EndOfDeclarationMarker */);
24201             node.emitNode = {};
24202             node.original = original;
24203             return node;
24204         }
24205         /**
24206          * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
24207          * order to properly emit exports.
24208          */
24209         // @api
24210         function createMergeDeclarationMarker(original) {
24211             var node = createBaseNode(338 /* MergeDeclarationMarker */);
24212             node.emitNode = {};
24213             node.original = original;
24214             return node;
24215         }
24216         // @api
24217         function createSyntheticReferenceExpression(expression, thisArg) {
24218             var node = createBaseNode(340 /* SyntheticReferenceExpression */);
24219             node.expression = expression;
24220             node.thisArg = thisArg;
24221             node.transformFlags |=
24222                 propagateChildFlags(node.expression) |
24223                     propagateChildFlags(node.thisArg);
24224             return node;
24225         }
24226         // @api
24227         function updateSyntheticReferenceExpression(node, expression, thisArg) {
24228             return node.expression !== expression
24229                 || node.thisArg !== thisArg
24230                 ? update(createSyntheticReferenceExpression(expression, thisArg), node)
24231                 : node;
24232         }
24233         function cloneNode(node) {
24234             // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
24235             // the original node. We also need to exclude specific properties and only include own-
24236             // properties (to skip members already defined on the shared prototype).
24237             if (node === undefined) {
24238                 return node;
24239             }
24240             var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(297 /* SourceFile */) :
24241                 ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78 /* Identifier */) :
24242                     ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */) :
24243                         !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) :
24244                             baseFactory.createBaseNode(node.kind);
24245             clone.flags |= (node.flags & ~8 /* Synthesized */);
24246             clone.transformFlags = node.transformFlags;
24247             setOriginalNode(clone, node);
24248             for (var key in node) {
24249                 if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
24250                     continue;
24251                 }
24252                 clone[key] = node[key];
24253             }
24254             return clone;
24255         }
24256         function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
24257             return createCallExpression(createFunctionExpression(
24258             /*modifiers*/ undefined, 
24259             /*asteriskToken*/ undefined, 
24260             /*name*/ undefined, 
24261             /*typeParameters*/ undefined, 
24262             /*parameters*/ param ? [param] : [], 
24263             /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
24264             /*typeArguments*/ undefined, 
24265             /*argumentsArray*/ paramValue ? [paramValue] : []);
24266         }
24267         function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
24268             return createCallExpression(createArrowFunction(
24269             /*modifiers*/ undefined, 
24270             /*typeParameters*/ undefined, 
24271             /*parameters*/ param ? [param] : [], 
24272             /*type*/ undefined, 
24273             /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
24274             /*typeArguments*/ undefined, 
24275             /*argumentsArray*/ paramValue ? [paramValue] : []);
24276         }
24277         function createVoidZero() {
24278             return createVoidExpression(createNumericLiteral("0"));
24279         }
24280         function createExportDefault(expression) {
24281             return createExportAssignment(
24282             /*decorators*/ undefined, 
24283             /*modifiers*/ undefined, 
24284             /*isExportEquals*/ false, expression);
24285         }
24286         function createExternalModuleExport(exportName) {
24287             return createExportDeclaration(
24288             /*decorators*/ undefined, 
24289             /*modifiers*/ undefined, 
24290             /*isTypeOnly*/ false, createNamedExports([
24291                 createExportSpecifier(/*propertyName*/ undefined, exportName)
24292             ]));
24293         }
24294         //
24295         // Utilities
24296         //
24297         function createTypeCheck(value, tag) {
24298             return tag === "undefined"
24299                 ? factory.createStrictEquality(value, createVoidZero())
24300                 : factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag));
24301         }
24302         function createMethodCall(object, methodName, argumentsList) {
24303             return createCallExpression(createPropertyAccessExpression(object, methodName), 
24304             /*typeArguments*/ undefined, argumentsList);
24305         }
24306         function createFunctionBindCall(target, thisArg, argumentsList) {
24307             return createMethodCall(target, "bind", __spreadArrays([thisArg], argumentsList));
24308         }
24309         function createFunctionCallCall(target, thisArg, argumentsList) {
24310             return createMethodCall(target, "call", __spreadArrays([thisArg], argumentsList));
24311         }
24312         function createFunctionApplyCall(target, thisArg, argumentsExpression) {
24313             return createMethodCall(target, "apply", [thisArg, argumentsExpression]);
24314         }
24315         function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
24316             return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
24317         }
24318         function createArraySliceCall(array, start) {
24319             return createMethodCall(array, "slice", start === undefined ? [] : [asExpression(start)]);
24320         }
24321         function createArrayConcatCall(array, argumentsList) {
24322             return createMethodCall(array, "concat", argumentsList);
24323         }
24324         function createObjectDefinePropertyCall(target, propertyName, attributes) {
24325             return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
24326         }
24327         function tryAddPropertyAssignment(properties, propertyName, expression) {
24328             if (expression) {
24329                 properties.push(createPropertyAssignment(propertyName, expression));
24330                 return true;
24331             }
24332             return false;
24333         }
24334         function createPropertyDescriptor(attributes, singleLine) {
24335             var properties = [];
24336             tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
24337             tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
24338             var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
24339             isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
24340             var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
24341             isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
24342             ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
24343             return createObjectLiteralExpression(properties, !singleLine);
24344         }
24345         function updateOuterExpression(outerExpression, expression) {
24346             switch (outerExpression.kind) {
24347                 case 207 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression);
24348                 case 206 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression);
24349                 case 224 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type);
24350                 case 225 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression);
24351                 case 336 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression);
24352             }
24353         }
24354         /**
24355          * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
24356          *
24357          * A parenthesized expression can be ignored when all of the following are true:
24358          *
24359          * - It's `pos` and `end` are not -1
24360          * - It does not have a custom source map range
24361          * - It does not have a custom comment range
24362          * - It does not have synthetic leading or trailing comments
24363          *
24364          * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
24365          * the expression to maintain precedence, a new parenthesized expression should be created automatically when
24366          * the containing expression is created/updated.
24367          */
24368         function isIgnorableParen(node) {
24369             return ts.isParenthesizedExpression(node)
24370                 && ts.nodeIsSynthesized(node)
24371                 && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
24372                 && ts.nodeIsSynthesized(ts.getCommentRange(node))
24373                 && !ts.some(ts.getSyntheticLeadingComments(node))
24374                 && !ts.some(ts.getSyntheticTrailingComments(node));
24375         }
24376         function restoreOuterExpressions(outerExpression, innerExpression, kinds) {
24377             if (kinds === void 0) { kinds = 15 /* All */; }
24378             if (outerExpression && ts.isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
24379                 return updateOuterExpression(outerExpression, restoreOuterExpressions(outerExpression.expression, innerExpression));
24380             }
24381             return innerExpression;
24382         }
24383         function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
24384             if (!outermostLabeledStatement) {
24385                 return node;
24386             }
24387             var updated = updateLabeledStatement(outermostLabeledStatement, outermostLabeledStatement.label, ts.isLabeledStatement(outermostLabeledStatement.statement)
24388                 ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
24389                 : node);
24390             if (afterRestoreLabelCallback) {
24391                 afterRestoreLabelCallback(outermostLabeledStatement);
24392             }
24393             return updated;
24394         }
24395         function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
24396             var target = ts.skipParentheses(node);
24397             switch (target.kind) {
24398                 case 78 /* Identifier */:
24399                     return cacheIdentifiers;
24400                 case 107 /* ThisKeyword */:
24401                 case 8 /* NumericLiteral */:
24402                 case 9 /* BigIntLiteral */:
24403                 case 10 /* StringLiteral */:
24404                     return false;
24405                 case 199 /* ArrayLiteralExpression */:
24406                     var elements = target.elements;
24407                     if (elements.length === 0) {
24408                         return false;
24409                     }
24410                     return true;
24411                 case 200 /* ObjectLiteralExpression */:
24412                     return target.properties.length > 0;
24413                 default:
24414                     return true;
24415             }
24416         }
24417         function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
24418             if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
24419             var callee = ts.skipOuterExpressions(expression, 15 /* All */);
24420             var thisArg;
24421             var target;
24422             if (ts.isSuperProperty(callee)) {
24423                 thisArg = createThis();
24424                 target = callee;
24425             }
24426             else if (ts.isSuperKeyword(callee)) {
24427                 thisArg = createThis();
24428                 target = languageVersion !== undefined && languageVersion < 2 /* ES2015 */
24429                     ? ts.setTextRange(createIdentifier("_super"), callee)
24430                     : callee;
24431             }
24432             else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
24433                 thisArg = createVoidZero();
24434                 target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee);
24435             }
24436             else if (ts.isPropertyAccessExpression(callee)) {
24437                 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
24438                     // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
24439                     thisArg = createTempVariable(recordTempVariable);
24440                     target = createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
24441                     ts.setTextRange(target, callee);
24442                 }
24443                 else {
24444                     thisArg = callee.expression;
24445                     target = callee;
24446                 }
24447             }
24448             else if (ts.isElementAccessExpression(callee)) {
24449                 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
24450                     // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
24451                     thisArg = createTempVariable(recordTempVariable);
24452                     target = createElementAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
24453                     ts.setTextRange(target, callee);
24454                 }
24455                 else {
24456                     thisArg = callee.expression;
24457                     target = callee;
24458                 }
24459             }
24460             else {
24461                 // for `a()` target is `a` and thisArg is `void 0`
24462                 thisArg = createVoidZero();
24463                 target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
24464             }
24465             return { target: target, thisArg: thisArg };
24466         }
24467         function inlineExpressions(expressions) {
24468             // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
24469             // stack size exceeded" errors.
24470             return expressions.length > 10
24471                 ? createCommaListExpression(expressions)
24472                 : ts.reduceLeft(expressions, factory.createComma);
24473         }
24474         function getName(node, allowComments, allowSourceMaps, emitFlags) {
24475             if (emitFlags === void 0) { emitFlags = 0; }
24476             var nodeName = ts.getNameOfDeclaration(node);
24477             if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
24478                 // TODO(rbuckton): Does this need to be parented?
24479                 var name = ts.setParent(ts.setTextRange(cloneNode(nodeName), nodeName), nodeName.parent);
24480                 emitFlags |= ts.getEmitFlags(nodeName);
24481                 if (!allowSourceMaps)
24482                     emitFlags |= 48 /* NoSourceMap */;
24483                 if (!allowComments)
24484                     emitFlags |= 1536 /* NoComments */;
24485                 if (emitFlags)
24486                     ts.setEmitFlags(name, emitFlags);
24487                 return name;
24488             }
24489             return getGeneratedNameForNode(node);
24490         }
24491         /**
24492          * Gets the internal name of a declaration. This is primarily used for declarations that can be
24493          * referred to by name in the body of an ES5 class function body. An internal name will *never*
24494          * be prefixed with an module or namespace export modifier like "exports." when emitted as an
24495          * expression. An internal name will also *never* be renamed due to a collision with a block
24496          * scoped variable.
24497          *
24498          * @param node The declaration.
24499          * @param allowComments A value indicating whether comments may be emitted for the name.
24500          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24501          */
24502         function getInternalName(node, allowComments, allowSourceMaps) {
24503             return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
24504         }
24505         /**
24506          * Gets the local name of a declaration. This is primarily used for declarations that can be
24507          * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
24508          * local name will *never* be prefixed with an module or namespace export modifier like
24509          * "exports." when emitted as an expression.
24510          *
24511          * @param node The declaration.
24512          * @param allowComments A value indicating whether comments may be emitted for the name.
24513          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24514          */
24515         function getLocalName(node, allowComments, allowSourceMaps) {
24516             return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
24517         }
24518         /**
24519          * Gets the export name of a declaration. This is primarily used for declarations that can be
24520          * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
24521          * export name will *always* be prefixed with an module or namespace export modifier like
24522          * `"exports."` when emitted as an expression if the name points to an exported symbol.
24523          *
24524          * @param node The declaration.
24525          * @param allowComments A value indicating whether comments may be emitted for the name.
24526          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24527          */
24528         function getExportName(node, allowComments, allowSourceMaps) {
24529             return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
24530         }
24531         /**
24532          * Gets the name of a declaration for use in declarations.
24533          *
24534          * @param node The declaration.
24535          * @param allowComments A value indicating whether comments may be emitted for the name.
24536          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24537          */
24538         function getDeclarationName(node, allowComments, allowSourceMaps) {
24539             return getName(node, allowComments, allowSourceMaps);
24540         }
24541         /**
24542          * Gets a namespace-qualified name for use in expressions.
24543          *
24544          * @param ns The namespace identifier.
24545          * @param name The name.
24546          * @param allowComments A value indicating whether comments may be emitted for the name.
24547          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24548          */
24549         function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
24550             var qualifiedName = createPropertyAccessExpression(ns, ts.nodeIsSynthesized(name) ? name : cloneNode(name));
24551             ts.setTextRange(qualifiedName, name);
24552             var emitFlags = 0;
24553             if (!allowSourceMaps)
24554                 emitFlags |= 48 /* NoSourceMap */;
24555             if (!allowComments)
24556                 emitFlags |= 1536 /* NoComments */;
24557             if (emitFlags)
24558                 ts.setEmitFlags(qualifiedName, emitFlags);
24559             return qualifiedName;
24560         }
24561         /**
24562          * Gets the exported name of a declaration for use in expressions.
24563          *
24564          * An exported name will *always* be prefixed with an module or namespace export modifier like
24565          * "exports." if the name points to an exported symbol.
24566          *
24567          * @param ns The namespace identifier.
24568          * @param node The declaration.
24569          * @param allowComments A value indicating whether comments may be emitted for the name.
24570          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24571          */
24572         function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
24573             if (ns && ts.hasSyntacticModifier(node, 1 /* Export */)) {
24574                 return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
24575             }
24576             return getExportName(node, allowComments, allowSourceMaps);
24577         }
24578         /**
24579          * Copies any necessary standard and custom prologue-directives into target array.
24580          * @param source origin statements array
24581          * @param target result statements array
24582          * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
24583          * @param visitor Optional callback used to visit any custom prologue directives.
24584          */
24585         function copyPrologue(source, target, ensureUseStrict, visitor) {
24586             var offset = copyStandardPrologue(source, target, ensureUseStrict);
24587             return copyCustomPrologue(source, target, offset, visitor);
24588         }
24589         function isUseStrictPrologue(node) {
24590             return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
24591         }
24592         function createUseStrictPrologue() {
24593             return ts.startOnNewLine(createExpressionStatement(createStringLiteral("use strict")));
24594         }
24595         /**
24596          * Copies only the standard (string-expression) prologue-directives into the target statement-array.
24597          * @param source origin statements array
24598          * @param target result statements array
24599          * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
24600          */
24601         function copyStandardPrologue(source, target, ensureUseStrict) {
24602             ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
24603             var foundUseStrict = false;
24604             var statementOffset = 0;
24605             var numStatements = source.length;
24606             while (statementOffset < numStatements) {
24607                 var statement = source[statementOffset];
24608                 if (ts.isPrologueDirective(statement)) {
24609                     if (isUseStrictPrologue(statement)) {
24610                         foundUseStrict = true;
24611                     }
24612                     target.push(statement);
24613                 }
24614                 else {
24615                     break;
24616                 }
24617                 statementOffset++;
24618             }
24619             if (ensureUseStrict && !foundUseStrict) {
24620                 target.push(createUseStrictPrologue());
24621             }
24622             return statementOffset;
24623         }
24624         function copyCustomPrologue(source, target, statementOffset, visitor, filter) {
24625             if (filter === void 0) { filter = ts.returnTrue; }
24626             var numStatements = source.length;
24627             while (statementOffset !== undefined && statementOffset < numStatements) {
24628                 var statement = source[statementOffset];
24629                 if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
24630                     ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
24631                 }
24632                 else {
24633                     break;
24634                 }
24635                 statementOffset++;
24636             }
24637             return statementOffset;
24638         }
24639         /**
24640          * Ensures "use strict" directive is added
24641          *
24642          * @param statements An array of statements
24643          */
24644         function ensureUseStrict(statements) {
24645             var foundUseStrict = ts.findUseStrictPrologue(statements);
24646             if (!foundUseStrict) {
24647                 return ts.setTextRange(createNodeArray(__spreadArrays([createUseStrictPrologue()], statements)), statements);
24648             }
24649             return statements;
24650         }
24651         /**
24652          * Lifts a NodeArray containing only Statement nodes to a block.
24653          *
24654          * @param nodes The NodeArray.
24655          */
24656         function liftToBlock(nodes) {
24657             ts.Debug.assert(ts.every(nodes, ts.isStatementOrBlock), "Cannot lift nodes to a Block.");
24658             return ts.singleOrUndefined(nodes) || createBlock(nodes);
24659         }
24660         function findSpanEnd(array, test, start) {
24661             var i = start;
24662             while (i < array.length && test(array[i])) {
24663                 i++;
24664             }
24665             return i;
24666         }
24667         function mergeLexicalEnvironment(statements, declarations) {
24668             if (!ts.some(declarations)) {
24669                 return statements;
24670             }
24671             // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
24672             //
24673             // Given:
24674             //
24675             // | Left                               | Right                               |
24676             // |------------------------------------|-------------------------------------|
24677             // | [standard prologues (left)]        | [standard prologues (right)]        |
24678             // | [hoisted functions (left)]         | [hoisted functions (right)]         |
24679             // | [hoisted variables (left)]         | [hoisted variables (right)]         |
24680             // | [lexical init statements (left)]   | [lexical init statements (right)]   |
24681             // | [other statements (left)]          |                                     |
24682             //
24683             // The resulting statement list will be:
24684             //
24685             // | Result                              |
24686             // |-------------------------------------|
24687             // | [standard prologues (right)]        |
24688             // | [standard prologues (left)]         |
24689             // | [hoisted functions (right)]         |
24690             // | [hoisted functions (left)]          |
24691             // | [hoisted variables (right)]         |
24692             // | [hoisted variables (left)]          |
24693             // | [lexical init statements (right)]   |
24694             // | [lexical init statements (left)]    |
24695             // | [other statements (left)]           |
24696             //
24697             // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
24698             // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
24699             // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
24700             var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
24701             var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
24702             var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
24703             // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
24704             var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
24705             var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
24706             var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
24707             var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
24708             ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
24709             // splice prologues from the right into the left. We do this in reverse order
24710             // so that we don't need to recompute the index on the left when we insert items.
24711             var left = ts.isNodeArray(statements) ? statements.slice() : statements;
24712             // splice other custom prologues from right into left
24713             if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
24714                 left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
24715             }
24716             // splice hoisted variables from right into left
24717             if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
24718                 left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
24719             }
24720             // splice hoisted functions from right into left
24721             if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
24722                 left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
24723             }
24724             // splice standard prologues from right into left (that are not already in left)
24725             if (rightStandardPrologueEnd > 0) {
24726                 if (leftStandardPrologueEnd === 0) {
24727                     left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
24728                 }
24729                 else {
24730                     var leftPrologues = new ts.Map();
24731                     for (var i = 0; i < leftStandardPrologueEnd; i++) {
24732                         var leftPrologue = statements[i];
24733                         leftPrologues.set(leftPrologue.expression.text, true);
24734                     }
24735                     for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
24736                         var rightPrologue = declarations[i];
24737                         if (!leftPrologues.has(rightPrologue.expression.text)) {
24738                             left.unshift(rightPrologue);
24739                         }
24740                     }
24741                 }
24742             }
24743             if (ts.isNodeArray(statements)) {
24744                 return ts.setTextRange(createNodeArray(left, statements.hasTrailingComma), statements);
24745             }
24746             return statements;
24747         }
24748         function updateModifiers(node, modifiers) {
24749             var _a;
24750             if (typeof modifiers === "number") {
24751                 modifiers = createModifiersFromModifierFlags(modifiers);
24752             }
24753             return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) :
24754                 ts.isPropertySignature(node) ? updatePropertySignature(node, modifiers, node.name, node.questionToken, node.type) :
24755                     ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifiers, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) :
24756                         ts.isMethodSignature(node) ? updateMethodSignature(node, modifiers, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) :
24757                             ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) :
24758                                 ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifiers, node.parameters, node.body) :
24759                                     ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.type, node.body) :
24760                                         ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.body) :
24761                                             ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifiers, node.parameters, node.type) :
24762                                                 ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
24763                                                     ts.isArrowFunction(node) ? updateArrowFunction(node, modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) :
24764                                                         ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
24765                                                             ts.isVariableStatement(node) ? updateVariableStatement(node, modifiers, node.declarationList) :
24766                                                                 ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
24767                                                                     ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
24768                                                                         ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
24769                                                                             ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) :
24770                                                                                 ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) :
24771                                                                                     ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) :
24772                                                                                         ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.name, node.moduleReference) :
24773                                                                                             ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier) :
24774                                                                                                 ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) :
24775                                                                                                     ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier) :
24776                                                                                                         ts.Debug.assertNever(node);
24777         }
24778         function asNodeArray(array) {
24779             return array ? createNodeArray(array) : undefined;
24780         }
24781         function asName(name) {
24782             return typeof name === "string" ? createIdentifier(name) :
24783                 name;
24784         }
24785         function asExpression(value) {
24786             return typeof value === "string" ? createStringLiteral(value) :
24787                 typeof value === "number" ? createNumericLiteral(value) :
24788                     typeof value === "boolean" ? value ? createTrue() : createFalse() :
24789                         value;
24790         }
24791         function asToken(value) {
24792             return typeof value === "number" ? createToken(value) : value;
24793         }
24794         function asEmbeddedStatement(statement) {
24795             return statement && ts.isNotEmittedStatement(statement) ? ts.setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
24796         }
24797     }
24798     ts.createNodeFactory = createNodeFactory;
24799     function updateWithoutOriginal(updated, original) {
24800         if (updated !== original) {
24801             ts.setTextRange(updated, original);
24802         }
24803         return updated;
24804     }
24805     function updateWithOriginal(updated, original) {
24806         if (updated !== original) {
24807             setOriginalNode(updated, original);
24808             ts.setTextRange(updated, original);
24809         }
24810         return updated;
24811     }
24812     function getDefaultTagNameForKind(kind) {
24813         switch (kind) {
24814             case 329 /* JSDocTypeTag */: return "type";
24815             case 327 /* JSDocReturnTag */: return "returns";
24816             case 328 /* JSDocThisTag */: return "this";
24817             case 325 /* JSDocEnumTag */: return "enum";
24818             case 317 /* JSDocAuthorTag */: return "author";
24819             case 319 /* JSDocClassTag */: return "class";
24820             case 320 /* JSDocPublicTag */: return "public";
24821             case 321 /* JSDocPrivateTag */: return "private";
24822             case 322 /* JSDocProtectedTag */: return "protected";
24823             case 323 /* JSDocReadonlyTag */: return "readonly";
24824             case 330 /* JSDocTemplateTag */: return "template";
24825             case 331 /* JSDocTypedefTag */: return "typedef";
24826             case 326 /* JSDocParameterTag */: return "param";
24827             case 333 /* JSDocPropertyTag */: return "prop";
24828             case 324 /* JSDocCallbackTag */: return "callback";
24829             case 315 /* JSDocAugmentsTag */: return "augments";
24830             case 316 /* JSDocImplementsTag */: return "implements";
24831             default:
24832                 return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind));
24833         }
24834     }
24835     var rawTextScanner;
24836     var invalidValueSentinel = {};
24837     function getCookedText(kind, rawText) {
24838         if (!rawTextScanner) {
24839             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
24840         }
24841         switch (kind) {
24842             case 14 /* NoSubstitutionTemplateLiteral */:
24843                 rawTextScanner.setText("`" + rawText + "`");
24844                 break;
24845             case 15 /* TemplateHead */:
24846                 // tslint:disable-next-line no-invalid-template-strings
24847                 rawTextScanner.setText("`" + rawText + "${");
24848                 break;
24849             case 16 /* TemplateMiddle */:
24850                 // tslint:disable-next-line no-invalid-template-strings
24851                 rawTextScanner.setText("}" + rawText + "${");
24852                 break;
24853             case 17 /* TemplateTail */:
24854                 rawTextScanner.setText("}" + rawText + "`");
24855                 break;
24856         }
24857         var token = rawTextScanner.scan();
24858         if (token === 23 /* CloseBracketToken */) {
24859             token = rawTextScanner.reScanTemplateToken(/*isTaggedTemplate*/ false);
24860         }
24861         if (rawTextScanner.isUnterminated()) {
24862             rawTextScanner.setText(undefined);
24863             return invalidValueSentinel;
24864         }
24865         var tokenValue;
24866         switch (token) {
24867             case 14 /* NoSubstitutionTemplateLiteral */:
24868             case 15 /* TemplateHead */:
24869             case 16 /* TemplateMiddle */:
24870             case 17 /* TemplateTail */:
24871                 tokenValue = rawTextScanner.getTokenValue();
24872                 break;
24873         }
24874         if (tokenValue === undefined || rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
24875             rawTextScanner.setText(undefined);
24876             return invalidValueSentinel;
24877         }
24878         rawTextScanner.setText(undefined);
24879         return tokenValue;
24880     }
24881     function propagateIdentifierNameFlags(node) {
24882         // An IdentifierName is allowed to be `await`
24883         return propagateChildFlags(node) & ~8388608 /* ContainsPossibleTopLevelAwait */;
24884     }
24885     function propagatePropertyNameFlagsOfChild(node, transformFlags) {
24886         return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
24887     }
24888     function propagateChildFlags(child) {
24889         if (!child)
24890             return 0 /* None */;
24891         var childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind);
24892         return ts.isNamedDeclaration(child) && ts.isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags;
24893     }
24894     function propagateChildrenFlags(children) {
24895         return children ? children.transformFlags : 0 /* None */;
24896     }
24897     function aggregateChildrenFlags(children) {
24898         var subtreeFlags = 0 /* None */;
24899         for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
24900             var child = children_2[_i];
24901             subtreeFlags |= propagateChildFlags(child);
24902         }
24903         children.transformFlags = subtreeFlags;
24904     }
24905     /**
24906      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
24907      */
24908     /* @internal */
24909     function getTransformFlagsSubtreeExclusions(kind) {
24910         if (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) {
24911             return -2 /* TypeExcludes */;
24912         }
24913         switch (kind) {
24914             case 203 /* CallExpression */:
24915             case 204 /* NewExpression */:
24916             case 199 /* ArrayLiteralExpression */:
24917                 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
24918             case 256 /* ModuleDeclaration */:
24919                 return 546379776 /* ModuleExcludes */;
24920             case 160 /* Parameter */:
24921                 return 536870912 /* ParameterExcludes */;
24922             case 209 /* ArrowFunction */:
24923                 return 547309568 /* ArrowFunctionExcludes */;
24924             case 208 /* FunctionExpression */:
24925             case 251 /* FunctionDeclaration */:
24926                 return 547313664 /* FunctionExcludes */;
24927             case 250 /* VariableDeclarationList */:
24928                 return 537018368 /* VariableDeclarationListExcludes */;
24929             case 252 /* ClassDeclaration */:
24930             case 221 /* ClassExpression */:
24931                 return 536905728 /* ClassExcludes */;
24932             case 166 /* Constructor */:
24933                 return 547311616 /* ConstructorExcludes */;
24934             case 163 /* PropertyDeclaration */:
24935                 return 536875008 /* PropertyExcludes */;
24936             case 165 /* MethodDeclaration */:
24937             case 167 /* GetAccessor */:
24938             case 168 /* SetAccessor */:
24939                 return 538923008 /* MethodOrAccessorExcludes */;
24940             case 128 /* AnyKeyword */:
24941             case 144 /* NumberKeyword */:
24942             case 155 /* BigIntKeyword */:
24943             case 141 /* NeverKeyword */:
24944             case 147 /* StringKeyword */:
24945             case 145 /* ObjectKeyword */:
24946             case 131 /* BooleanKeyword */:
24947             case 148 /* SymbolKeyword */:
24948             case 113 /* VoidKeyword */:
24949             case 159 /* TypeParameter */:
24950             case 162 /* PropertySignature */:
24951             case 164 /* MethodSignature */:
24952             case 169 /* CallSignature */:
24953             case 170 /* ConstructSignature */:
24954             case 171 /* IndexSignature */:
24955             case 253 /* InterfaceDeclaration */:
24956             case 254 /* TypeAliasDeclaration */:
24957                 return -2 /* TypeExcludes */;
24958             case 200 /* ObjectLiteralExpression */:
24959                 return 536922112 /* ObjectLiteralExcludes */;
24960             case 287 /* CatchClause */:
24961                 return 536887296 /* CatchClauseExcludes */;
24962             case 196 /* ObjectBindingPattern */:
24963             case 197 /* ArrayBindingPattern */:
24964                 return 536879104 /* BindingPatternExcludes */;
24965             case 206 /* TypeAssertionExpression */:
24966             case 224 /* AsExpression */:
24967             case 336 /* PartiallyEmittedExpression */:
24968             case 207 /* ParenthesizedExpression */:
24969             case 105 /* SuperKeyword */:
24970                 return 536870912 /* OuterExpressionExcludes */;
24971             case 201 /* PropertyAccessExpression */:
24972             case 202 /* ElementAccessExpression */:
24973                 return 536870912 /* PropertyAccessExcludes */;
24974             default:
24975                 return 536870912 /* NodeExcludes */;
24976         }
24977     }
24978     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
24979     var baseFactory = ts.createBaseNodeFactory();
24980     function makeSynthetic(node) {
24981         node.flags |= 8 /* Synthesized */;
24982         return node;
24983     }
24984     var syntheticFactory = {
24985         createBaseSourceFileNode: function (kind) { return makeSynthetic(baseFactory.createBaseSourceFileNode(kind)); },
24986         createBaseIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBaseIdentifierNode(kind)); },
24987         createBasePrivateIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)); },
24988         createBaseTokenNode: function (kind) { return makeSynthetic(baseFactory.createBaseTokenNode(kind)); },
24989         createBaseNode: function (kind) { return makeSynthetic(baseFactory.createBaseNode(kind)); },
24990     };
24991     ts.factory = createNodeFactory(4 /* NoIndentationOnFreshPropertyAccess */, syntheticFactory);
24992     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
24993         var stripInternal;
24994         var bundleFileInfo;
24995         var fileName;
24996         var text;
24997         var length;
24998         var sourceMapPath;
24999         var sourceMapText;
25000         var getText;
25001         var getSourceMapText;
25002         var oldFileOfCurrentEmit;
25003         if (!ts.isString(textOrInputFiles)) {
25004             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
25005             fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
25006             sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
25007             getText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; };
25008             getSourceMapText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; };
25009             length = function () { return getText().length; };
25010             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
25011                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
25012                 stripInternal = mapTextOrStripInternal;
25013                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
25014                 oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
25015             }
25016         }
25017         else {
25018             fileName = "";
25019             text = textOrInputFiles;
25020             length = textOrInputFiles.length;
25021             sourceMapPath = mapPathOrType;
25022             sourceMapText = mapTextOrStripInternal;
25023         }
25024         var node = oldFileOfCurrentEmit ?
25025             parseOldFileOfCurrentEmit(ts.Debug.assertDefined(bundleFileInfo)) :
25026             parseUnparsedSourceFile(bundleFileInfo, stripInternal, length);
25027         node.fileName = fileName;
25028         node.sourceMapPath = sourceMapPath;
25029         node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
25030         if (getText && getSourceMapText) {
25031             Object.defineProperty(node, "text", { get: getText });
25032             Object.defineProperty(node, "sourceMapText", { get: getSourceMapText });
25033         }
25034         else {
25035             ts.Debug.assert(!oldFileOfCurrentEmit);
25036             node.text = text !== null && text !== void 0 ? text : "";
25037             node.sourceMapText = sourceMapText;
25038         }
25039         return node;
25040     }
25041     ts.createUnparsedSourceFile = createUnparsedSourceFile;
25042     function parseUnparsedSourceFile(bundleFileInfo, stripInternal, length) {
25043         var prologues;
25044         var helpers;
25045         var referencedFiles;
25046         var typeReferenceDirectives;
25047         var libReferenceDirectives;
25048         var prependChildren;
25049         var texts;
25050         var hasNoDefaultLib;
25051         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
25052             var section = _a[_i];
25053             switch (section.kind) {
25054                 case "prologue" /* Prologue */:
25055                     prologues = ts.append(prologues, ts.setTextRange(ts.factory.createUnparsedPrologue(section.data), section));
25056                     break;
25057                 case "emitHelpers" /* EmitHelpers */:
25058                     helpers = ts.append(helpers, ts.getAllUnscopedEmitHelpers().get(section.data));
25059                     break;
25060                 case "no-default-lib" /* NoDefaultLib */:
25061                     hasNoDefaultLib = true;
25062                     break;
25063                 case "reference" /* Reference */:
25064                     referencedFiles = ts.append(referencedFiles, { pos: -1, end: -1, fileName: section.data });
25065                     break;
25066                 case "type" /* Type */:
25067                     typeReferenceDirectives = ts.append(typeReferenceDirectives, section.data);
25068                     break;
25069                 case "lib" /* Lib */:
25070                     libReferenceDirectives = ts.append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
25071                     break;
25072                 case "prepend" /* Prepend */:
25073                     var prependTexts = void 0;
25074                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
25075                         var text = _c[_b];
25076                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
25077                             prependTexts = ts.append(prependTexts, ts.setTextRange(ts.factory.createUnparsedTextLike(text.data, text.kind === "internal" /* Internal */), text));
25078                         }
25079                     }
25080                     prependChildren = ts.addRange(prependChildren, prependTexts);
25081                     texts = ts.append(texts, ts.factory.createUnparsedPrepend(section.data, prependTexts !== null && prependTexts !== void 0 ? prependTexts : ts.emptyArray));
25082                     break;
25083                 case "internal" /* Internal */:
25084                     if (stripInternal) {
25085                         if (!texts)
25086                             texts = [];
25087                         break;
25088                     }
25089                 // falls through
25090                 case "text" /* Text */:
25091                     texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
25092                     break;
25093                 default:
25094                     ts.Debug.assertNever(section);
25095             }
25096         }
25097         if (!texts) {
25098             var textNode = ts.factory.createUnparsedTextLike(/*data*/ undefined, /*internal*/ false);
25099             ts.setTextRangePosWidth(textNode, 0, typeof length === "function" ? length() : length);
25100             texts = [textNode];
25101         }
25102         var node = ts.parseNodeFactory.createUnparsedSource(prologues !== null && prologues !== void 0 ? prologues : ts.emptyArray, /*syntheticReferences*/ undefined, texts);
25103         ts.setEachParent(prologues, node);
25104         ts.setEachParent(texts, node);
25105         ts.setEachParent(prependChildren, node);
25106         node.hasNoDefaultLib = hasNoDefaultLib;
25107         node.helpers = helpers;
25108         node.referencedFiles = referencedFiles || ts.emptyArray;
25109         node.typeReferenceDirectives = typeReferenceDirectives;
25110         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
25111         return node;
25112     }
25113     function parseOldFileOfCurrentEmit(bundleFileInfo) {
25114         var texts;
25115         var syntheticReferences;
25116         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
25117             var section = _a[_i];
25118             switch (section.kind) {
25119                 case "internal" /* Internal */:
25120                 case "text" /* Text */:
25121                     texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
25122                     break;
25123                 case "no-default-lib" /* NoDefaultLib */:
25124                 case "reference" /* Reference */:
25125                 case "type" /* Type */:
25126                 case "lib" /* Lib */:
25127                     syntheticReferences = ts.append(syntheticReferences, ts.setTextRange(ts.factory.createUnparsedSyntheticReference(section), section));
25128                     break;
25129                 // Ignore
25130                 case "prologue" /* Prologue */:
25131                 case "emitHelpers" /* EmitHelpers */:
25132                 case "prepend" /* Prepend */:
25133                     break;
25134                 default:
25135                     ts.Debug.assertNever(section);
25136             }
25137         }
25138         var node = ts.factory.createUnparsedSource(ts.emptyArray, syntheticReferences, texts !== null && texts !== void 0 ? texts : ts.emptyArray);
25139         ts.setEachParent(syntheticReferences, node);
25140         ts.setEachParent(texts, node);
25141         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return ts.getAllUnscopedEmitHelpers().get(name); });
25142         return node;
25143     }
25144     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
25145         var node = ts.parseNodeFactory.createInputFiles();
25146         if (!ts.isString(javascriptTextOrReadFileText)) {
25147             var cache_1 = new ts.Map();
25148             var textGetter_1 = function (path) {
25149                 if (path === undefined)
25150                     return undefined;
25151                 var value = cache_1.get(path);
25152                 if (value === undefined) {
25153                     value = javascriptTextOrReadFileText(path);
25154                     cache_1.set(path, value !== undefined ? value : false);
25155                 }
25156                 return value !== false ? value : undefined;
25157             };
25158             var definedTextGetter_1 = function (path) {
25159                 var result = textGetter_1(path);
25160                 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
25161             };
25162             var buildInfo_1;
25163             var getAndCacheBuildInfo_1 = function (getText) {
25164                 if (buildInfo_1 === undefined) {
25165                     var result = getText();
25166                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
25167                 }
25168                 return buildInfo_1 || undefined;
25169             };
25170             node.javascriptPath = declarationTextOrJavascriptPath;
25171             node.javascriptMapPath = javascriptMapPath;
25172             node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
25173             node.declarationMapPath = declarationMapPath;
25174             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
25175             Object.defineProperties(node, {
25176                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
25177                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
25178                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
25179                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
25180                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
25181             });
25182         }
25183         else {
25184             node.javascriptText = javascriptTextOrReadFileText;
25185             node.javascriptMapPath = javascriptMapPath;
25186             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
25187             node.declarationText = declarationTextOrJavascriptPath;
25188             node.declarationMapPath = declarationMapPath;
25189             node.declarationMapText = declarationMapTextOrBuildInfoPath;
25190             node.javascriptPath = javascriptPath;
25191             node.declarationPath = declarationPath;
25192             node.buildInfoPath = buildInfoPath;
25193             node.buildInfo = buildInfo;
25194             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
25195         }
25196         return node;
25197     }
25198     ts.createInputFiles = createInputFiles;
25199     // tslint:disable-next-line variable-name
25200     var SourceMapSource;
25201     /**
25202      * Create an external source map source file reference
25203      */
25204     function createSourceMapSource(fileName, text, skipTrivia) {
25205         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
25206     }
25207     ts.createSourceMapSource = createSourceMapSource;
25208     // Utilities
25209     function setOriginalNode(node, original) {
25210         node.original = original;
25211         if (original) {
25212             var emitNode = original.emitNode;
25213             if (emitNode)
25214                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
25215         }
25216         return node;
25217     }
25218     ts.setOriginalNode = setOriginalNode;
25219     function mergeEmitNode(sourceEmitNode, destEmitNode) {
25220         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;
25221         if (!destEmitNode)
25222             destEmitNode = {};
25223         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
25224         if (leadingComments)
25225             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
25226         if (trailingComments)
25227             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
25228         if (flags)
25229             destEmitNode.flags = flags;
25230         if (commentRange)
25231             destEmitNode.commentRange = commentRange;
25232         if (sourceMapRange)
25233             destEmitNode.sourceMapRange = sourceMapRange;
25234         if (tokenSourceMapRanges)
25235             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
25236         if (constantValue !== undefined)
25237             destEmitNode.constantValue = constantValue;
25238         if (helpers) {
25239             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
25240                 var helper = helpers_1[_i];
25241                 destEmitNode.helpers = ts.appendIfUnique(destEmitNode.helpers, helper);
25242             }
25243         }
25244         if (startsOnNewLine !== undefined)
25245             destEmitNode.startsOnNewLine = startsOnNewLine;
25246         return destEmitNode;
25247     }
25248     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
25249         if (!destRanges)
25250             destRanges = [];
25251         for (var key in sourceRanges) {
25252             destRanges[key] = sourceRanges[key];
25253         }
25254         return destRanges;
25255     }
25256 })(ts || (ts = {}));
25257 var ts;
25258 (function (ts) {
25259     /**
25260      * Associates a node with the current transformation, initializing
25261      * various transient transformation properties.
25262      * @internal
25263      */
25264     function getOrCreateEmitNode(node) {
25265         var _a;
25266         if (!node.emitNode) {
25267             if (ts.isParseTreeNode(node)) {
25268                 // To avoid holding onto transformation artifacts, we keep track of any
25269                 // parse tree node we are annotating. This allows us to clean them up after
25270                 // all transformations have completed.
25271                 if (node.kind === 297 /* SourceFile */) {
25272                     return node.emitNode = { annotatedNodes: [node] };
25273                 }
25274                 var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file.");
25275                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
25276             }
25277             node.emitNode = {};
25278         }
25279         return node.emitNode;
25280     }
25281     ts.getOrCreateEmitNode = getOrCreateEmitNode;
25282     /**
25283      * Clears any `EmitNode` entries from parse-tree nodes.
25284      * @param sourceFile A source file.
25285      */
25286     function disposeEmitNodes(sourceFile) {
25287         var _a, _b;
25288         // During transformation we may need to annotate a parse tree node with transient
25289         // transformation properties. As parse tree nodes live longer than transformation
25290         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
25291         // from these nodes to ensure we do not hold onto entire subtrees just for position
25292         // information. We also need to reset these nodes to a pre-transformation state
25293         // for incremental parsing scenarios so that we do not impact later emit.
25294         var annotatedNodes = (_b = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile))) === null || _a === void 0 ? void 0 : _a.emitNode) === null || _b === void 0 ? void 0 : _b.annotatedNodes;
25295         if (annotatedNodes) {
25296             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
25297                 var node = annotatedNodes_1[_i];
25298                 node.emitNode = undefined;
25299             }
25300         }
25301     }
25302     ts.disposeEmitNodes = disposeEmitNodes;
25303     /**
25304      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
25305      * @internal
25306      */
25307     function removeAllComments(node) {
25308         var emitNode = getOrCreateEmitNode(node);
25309         emitNode.flags |= 1536 /* NoComments */;
25310         emitNode.leadingComments = undefined;
25311         emitNode.trailingComments = undefined;
25312         return node;
25313     }
25314     ts.removeAllComments = removeAllComments;
25315     /**
25316      * Sets flags that control emit behavior of a node.
25317      */
25318     function setEmitFlags(node, emitFlags) {
25319         getOrCreateEmitNode(node).flags = emitFlags;
25320         return node;
25321     }
25322     ts.setEmitFlags = setEmitFlags;
25323     /**
25324      * Sets flags that control emit behavior of a node.
25325      */
25326     /* @internal */
25327     function addEmitFlags(node, emitFlags) {
25328         var emitNode = getOrCreateEmitNode(node);
25329         emitNode.flags = emitNode.flags | emitFlags;
25330         return node;
25331     }
25332     ts.addEmitFlags = addEmitFlags;
25333     /**
25334      * Gets a custom text range to use when emitting source maps.
25335      */
25336     function getSourceMapRange(node) {
25337         var _a, _b;
25338         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.sourceMapRange) !== null && _b !== void 0 ? _b : node;
25339     }
25340     ts.getSourceMapRange = getSourceMapRange;
25341     /**
25342      * Sets a custom text range to use when emitting source maps.
25343      */
25344     function setSourceMapRange(node, range) {
25345         getOrCreateEmitNode(node).sourceMapRange = range;
25346         return node;
25347     }
25348     ts.setSourceMapRange = setSourceMapRange;
25349     /**
25350      * Gets the TextRange to use for source maps for a token of a node.
25351      */
25352     function getTokenSourceMapRange(node, token) {
25353         var _a, _b;
25354         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.tokenSourceMapRanges) === null || _b === void 0 ? void 0 : _b[token];
25355     }
25356     ts.getTokenSourceMapRange = getTokenSourceMapRange;
25357     /**
25358      * Sets the TextRange to use for source maps for a token of a node.
25359      */
25360     function setTokenSourceMapRange(node, token, range) {
25361         var _a;
25362         var emitNode = getOrCreateEmitNode(node);
25363         var tokenSourceMapRanges = (_a = emitNode.tokenSourceMapRanges) !== null && _a !== void 0 ? _a : (emitNode.tokenSourceMapRanges = []);
25364         tokenSourceMapRanges[token] = range;
25365         return node;
25366     }
25367     ts.setTokenSourceMapRange = setTokenSourceMapRange;
25368     /**
25369      * Gets a custom text range to use when emitting comments.
25370      */
25371     /*@internal*/
25372     function getStartsOnNewLine(node) {
25373         var _a;
25374         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.startsOnNewLine;
25375     }
25376     ts.getStartsOnNewLine = getStartsOnNewLine;
25377     /**
25378      * Sets a custom text range to use when emitting comments.
25379      */
25380     /*@internal*/
25381     function setStartsOnNewLine(node, newLine) {
25382         getOrCreateEmitNode(node).startsOnNewLine = newLine;
25383         return node;
25384     }
25385     ts.setStartsOnNewLine = setStartsOnNewLine;
25386     /**
25387      * Gets a custom text range to use when emitting comments.
25388      */
25389     function getCommentRange(node) {
25390         var _a, _b;
25391         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.commentRange) !== null && _b !== void 0 ? _b : node;
25392     }
25393     ts.getCommentRange = getCommentRange;
25394     /**
25395      * Sets a custom text range to use when emitting comments.
25396      */
25397     function setCommentRange(node, range) {
25398         getOrCreateEmitNode(node).commentRange = range;
25399         return node;
25400     }
25401     ts.setCommentRange = setCommentRange;
25402     function getSyntheticLeadingComments(node) {
25403         var _a;
25404         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.leadingComments;
25405     }
25406     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
25407     function setSyntheticLeadingComments(node, comments) {
25408         getOrCreateEmitNode(node).leadingComments = comments;
25409         return node;
25410     }
25411     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
25412     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
25413         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
25414     }
25415     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
25416     function getSyntheticTrailingComments(node) {
25417         var _a;
25418         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.trailingComments;
25419     }
25420     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
25421     function setSyntheticTrailingComments(node, comments) {
25422         getOrCreateEmitNode(node).trailingComments = comments;
25423         return node;
25424     }
25425     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
25426     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
25427         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
25428     }
25429     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
25430     function moveSyntheticComments(node, original) {
25431         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
25432         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
25433         var emit = getOrCreateEmitNode(original);
25434         emit.leadingComments = undefined;
25435         emit.trailingComments = undefined;
25436         return node;
25437     }
25438     ts.moveSyntheticComments = moveSyntheticComments;
25439     /**
25440      * Gets the constant value to emit for an expression representing an enum.
25441      */
25442     function getConstantValue(node) {
25443         var _a;
25444         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.constantValue;
25445     }
25446     ts.getConstantValue = getConstantValue;
25447     /**
25448      * Sets the constant value to emit for an expression.
25449      */
25450     function setConstantValue(node, value) {
25451         var emitNode = getOrCreateEmitNode(node);
25452         emitNode.constantValue = value;
25453         return node;
25454     }
25455     ts.setConstantValue = setConstantValue;
25456     /**
25457      * Adds an EmitHelper to a node.
25458      */
25459     function addEmitHelper(node, helper) {
25460         var emitNode = getOrCreateEmitNode(node);
25461         emitNode.helpers = ts.append(emitNode.helpers, helper);
25462         return node;
25463     }
25464     ts.addEmitHelper = addEmitHelper;
25465     /**
25466      * Add EmitHelpers to a node.
25467      */
25468     function addEmitHelpers(node, helpers) {
25469         if (ts.some(helpers)) {
25470             var emitNode = getOrCreateEmitNode(node);
25471             for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
25472                 var helper = helpers_2[_i];
25473                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
25474             }
25475         }
25476         return node;
25477     }
25478     ts.addEmitHelpers = addEmitHelpers;
25479     /**
25480      * Removes an EmitHelper from a node.
25481      */
25482     function removeEmitHelper(node, helper) {
25483         var _a;
25484         var helpers = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
25485         if (helpers) {
25486             return ts.orderedRemoveItem(helpers, helper);
25487         }
25488         return false;
25489     }
25490     ts.removeEmitHelper = removeEmitHelper;
25491     /**
25492      * Gets the EmitHelpers of a node.
25493      */
25494     function getEmitHelpers(node) {
25495         var _a;
25496         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
25497     }
25498     ts.getEmitHelpers = getEmitHelpers;
25499     /**
25500      * Moves matching emit helpers from a source node to a target node.
25501      */
25502     function moveEmitHelpers(source, target, predicate) {
25503         var sourceEmitNode = source.emitNode;
25504         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
25505         if (!ts.some(sourceEmitHelpers))
25506             return;
25507         var targetEmitNode = getOrCreateEmitNode(target);
25508         var helpersRemoved = 0;
25509         for (var i = 0; i < sourceEmitHelpers.length; i++) {
25510             var helper = sourceEmitHelpers[i];
25511             if (predicate(helper)) {
25512                 helpersRemoved++;
25513                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
25514             }
25515             else if (helpersRemoved > 0) {
25516                 sourceEmitHelpers[i - helpersRemoved] = helper;
25517             }
25518         }
25519         if (helpersRemoved > 0) {
25520             sourceEmitHelpers.length -= helpersRemoved;
25521         }
25522     }
25523     ts.moveEmitHelpers = moveEmitHelpers;
25524     /* @internal */
25525     function ignoreSourceNewlines(node) {
25526         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
25527         return node;
25528     }
25529     ts.ignoreSourceNewlines = ignoreSourceNewlines;
25530 })(ts || (ts = {}));
25531 /* @internal */
25532 var ts;
25533 (function (ts) {
25534     function createEmitHelperFactory(context) {
25535         var factory = context.factory;
25536         return {
25537             getUnscopedHelperName: getUnscopedHelperName,
25538             // TypeScript Helpers
25539             createDecorateHelper: createDecorateHelper,
25540             createMetadataHelper: createMetadataHelper,
25541             createParamHelper: createParamHelper,
25542             // ES2018 Helpers
25543             createAssignHelper: createAssignHelper,
25544             createAwaitHelper: createAwaitHelper,
25545             createAsyncGeneratorHelper: createAsyncGeneratorHelper,
25546             createAsyncDelegatorHelper: createAsyncDelegatorHelper,
25547             createAsyncValuesHelper: createAsyncValuesHelper,
25548             // ES2018 Destructuring Helpers
25549             createRestHelper: createRestHelper,
25550             // ES2017 Helpers
25551             createAwaiterHelper: createAwaiterHelper,
25552             // ES2015 Helpers
25553             createExtendsHelper: createExtendsHelper,
25554             createTemplateObjectHelper: createTemplateObjectHelper,
25555             createSpreadHelper: createSpreadHelper,
25556             createSpreadArraysHelper: createSpreadArraysHelper,
25557             // ES2015 Destructuring Helpers
25558             createValuesHelper: createValuesHelper,
25559             createReadHelper: createReadHelper,
25560             // ES2015 Generator Helpers
25561             createGeneratorHelper: createGeneratorHelper,
25562             // ES Module Helpers
25563             createCreateBindingHelper: createCreateBindingHelper,
25564             createImportStarHelper: createImportStarHelper,
25565             createImportStarCallbackHelper: createImportStarCallbackHelper,
25566             createImportDefaultHelper: createImportDefaultHelper,
25567             createExportStarHelper: createExportStarHelper,
25568             // Class Fields Helpers
25569             createClassPrivateFieldGetHelper: createClassPrivateFieldGetHelper,
25570             createClassPrivateFieldSetHelper: createClassPrivateFieldSetHelper,
25571         };
25572         /**
25573          * Gets an identifier for the name of an *unscoped* emit helper.
25574          */
25575         function getUnscopedHelperName(name) {
25576             return ts.setEmitFlags(factory.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
25577         }
25578         // TypeScript Helpers
25579         function createDecorateHelper(decoratorExpressions, target, memberName, descriptor) {
25580             context.requestEmitHelper(ts.decorateHelper);
25581             var argumentsArray = [];
25582             argumentsArray.push(factory.createArrayLiteralExpression(decoratorExpressions, /*multiLine*/ true));
25583             argumentsArray.push(target);
25584             if (memberName) {
25585                 argumentsArray.push(memberName);
25586                 if (descriptor) {
25587                     argumentsArray.push(descriptor);
25588                 }
25589             }
25590             return factory.createCallExpression(getUnscopedHelperName("__decorate"), 
25591             /*typeArguments*/ undefined, argumentsArray);
25592         }
25593         function createMetadataHelper(metadataKey, metadataValue) {
25594             context.requestEmitHelper(ts.metadataHelper);
25595             return factory.createCallExpression(getUnscopedHelperName("__metadata"), 
25596             /*typeArguments*/ undefined, [
25597                 factory.createStringLiteral(metadataKey),
25598                 metadataValue
25599             ]);
25600         }
25601         function createParamHelper(expression, parameterOffset, location) {
25602             context.requestEmitHelper(ts.paramHelper);
25603             return ts.setTextRange(factory.createCallExpression(getUnscopedHelperName("__param"), 
25604             /*typeArguments*/ undefined, [
25605                 factory.createNumericLiteral(parameterOffset + ""),
25606                 expression
25607             ]), location);
25608         }
25609         // ES2018 Helpers
25610         function createAssignHelper(attributesSegments) {
25611             if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
25612                 return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "assign"), 
25613                 /*typeArguments*/ undefined, attributesSegments);
25614             }
25615             context.requestEmitHelper(ts.assignHelper);
25616             return factory.createCallExpression(getUnscopedHelperName("__assign"), 
25617             /*typeArguments*/ undefined, attributesSegments);
25618         }
25619         function createAwaitHelper(expression) {
25620             context.requestEmitHelper(ts.awaitHelper);
25621             return factory.createCallExpression(getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
25622         }
25623         function createAsyncGeneratorHelper(generatorFunc, hasLexicalThis) {
25624             context.requestEmitHelper(ts.awaitHelper);
25625             context.requestEmitHelper(ts.asyncGeneratorHelper);
25626             // Mark this node as originally an async function
25627             (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
25628             return factory.createCallExpression(getUnscopedHelperName("__asyncGenerator"), 
25629             /*typeArguments*/ undefined, [
25630                 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
25631                 factory.createIdentifier("arguments"),
25632                 generatorFunc
25633             ]);
25634         }
25635         function createAsyncDelegatorHelper(expression) {
25636             context.requestEmitHelper(ts.awaitHelper);
25637             context.requestEmitHelper(ts.asyncDelegator);
25638             return factory.createCallExpression(getUnscopedHelperName("__asyncDelegator"), 
25639             /*typeArguments*/ undefined, [expression]);
25640         }
25641         function createAsyncValuesHelper(expression) {
25642             context.requestEmitHelper(ts.asyncValues);
25643             return factory.createCallExpression(getUnscopedHelperName("__asyncValues"), 
25644             /*typeArguments*/ undefined, [expression]);
25645         }
25646         // ES2018 Destructuring Helpers
25647         /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
25648          * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
25649          */
25650         function createRestHelper(value, elements, computedTempVariables, location) {
25651             context.requestEmitHelper(ts.restHelper);
25652             var propertyNames = [];
25653             var computedTempVariableOffset = 0;
25654             for (var i = 0; i < elements.length - 1; i++) {
25655                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
25656                 if (propertyName) {
25657                     if (ts.isComputedPropertyName(propertyName)) {
25658                         ts.Debug.assertIsDefined(computedTempVariables, "Encountered computed property name but 'computedTempVariables' argument was not provided.");
25659                         var temp = computedTempVariables[computedTempVariableOffset];
25660                         computedTempVariableOffset++;
25661                         // typeof _tmp === "symbol" ? _tmp : _tmp + ""
25662                         propertyNames.push(factory.createConditionalExpression(factory.createTypeCheck(temp, "symbol"), 
25663                         /*questionToken*/ undefined, temp, 
25664                         /*colonToken*/ undefined, factory.createAdd(temp, factory.createStringLiteral(""))));
25665                     }
25666                     else {
25667                         propertyNames.push(factory.createStringLiteralFromNode(propertyName));
25668                     }
25669                 }
25670             }
25671             return factory.createCallExpression(getUnscopedHelperName("__rest"), 
25672             /*typeArguments*/ undefined, [
25673                 value,
25674                 ts.setTextRange(factory.createArrayLiteralExpression(propertyNames), location)
25675             ]);
25676         }
25677         // ES2017 Helpers
25678         function createAwaiterHelper(hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
25679             context.requestEmitHelper(ts.awaiterHelper);
25680             var generatorFunc = factory.createFunctionExpression(
25681             /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */), 
25682             /*name*/ undefined, 
25683             /*typeParameters*/ undefined, 
25684             /*parameters*/ [], 
25685             /*type*/ undefined, body);
25686             // Mark this node as originally an async function
25687             (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
25688             return factory.createCallExpression(getUnscopedHelperName("__awaiter"), 
25689             /*typeArguments*/ undefined, [
25690                 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
25691                 hasLexicalArguments ? factory.createIdentifier("arguments") : factory.createVoidZero(),
25692                 promiseConstructor ? ts.createExpressionFromEntityName(factory, promiseConstructor) : factory.createVoidZero(),
25693                 generatorFunc
25694             ]);
25695         }
25696         // ES2015 Helpers
25697         function createExtendsHelper(name) {
25698             context.requestEmitHelper(ts.extendsHelper);
25699             return factory.createCallExpression(getUnscopedHelperName("__extends"), 
25700             /*typeArguments*/ undefined, [name, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)]);
25701         }
25702         function createTemplateObjectHelper(cooked, raw) {
25703             context.requestEmitHelper(ts.templateObjectHelper);
25704             return factory.createCallExpression(getUnscopedHelperName("__makeTemplateObject"), 
25705             /*typeArguments*/ undefined, [cooked, raw]);
25706         }
25707         function createSpreadHelper(argumentList) {
25708             context.requestEmitHelper(ts.readHelper);
25709             context.requestEmitHelper(ts.spreadHelper);
25710             return factory.createCallExpression(getUnscopedHelperName("__spread"), 
25711             /*typeArguments*/ undefined, argumentList);
25712         }
25713         function createSpreadArraysHelper(argumentList) {
25714             context.requestEmitHelper(ts.spreadArraysHelper);
25715             return factory.createCallExpression(getUnscopedHelperName("__spreadArrays"), 
25716             /*typeArguments*/ undefined, argumentList);
25717         }
25718         // ES2015 Destructuring Helpers
25719         function createValuesHelper(expression) {
25720             context.requestEmitHelper(ts.valuesHelper);
25721             return factory.createCallExpression(getUnscopedHelperName("__values"), 
25722             /*typeArguments*/ undefined, [expression]);
25723         }
25724         function createReadHelper(iteratorRecord, count) {
25725             context.requestEmitHelper(ts.readHelper);
25726             return factory.createCallExpression(getUnscopedHelperName("__read"), 
25727             /*typeArguments*/ undefined, count !== undefined
25728                 ? [iteratorRecord, factory.createNumericLiteral(count + "")]
25729                 : [iteratorRecord]);
25730         }
25731         // ES2015 Generator Helpers
25732         function createGeneratorHelper(body) {
25733             context.requestEmitHelper(ts.generatorHelper);
25734             return factory.createCallExpression(getUnscopedHelperName("__generator"), 
25735             /*typeArguments*/ undefined, [factory.createThis(), body]);
25736         }
25737         // ES Module Helpers
25738         function createCreateBindingHelper(module, inputName, outputName) {
25739             context.requestEmitHelper(ts.createBindingHelper);
25740             return factory.createCallExpression(getUnscopedHelperName("__createBinding"), 
25741             /*typeArguments*/ undefined, __spreadArrays([factory.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
25742         }
25743         function createImportStarHelper(expression) {
25744             context.requestEmitHelper(ts.importStarHelper);
25745             return factory.createCallExpression(getUnscopedHelperName("__importStar"), 
25746             /*typeArguments*/ undefined, [expression]);
25747         }
25748         function createImportStarCallbackHelper() {
25749             context.requestEmitHelper(ts.importStarHelper);
25750             return getUnscopedHelperName("__importStar");
25751         }
25752         function createImportDefaultHelper(expression) {
25753             context.requestEmitHelper(ts.importDefaultHelper);
25754             return factory.createCallExpression(getUnscopedHelperName("__importDefault"), 
25755             /*typeArguments*/ undefined, [expression]);
25756         }
25757         function createExportStarHelper(moduleExpression, exportsExpression) {
25758             if (exportsExpression === void 0) { exportsExpression = factory.createIdentifier("exports"); }
25759             context.requestEmitHelper(ts.exportStarHelper);
25760             context.requestEmitHelper(ts.createBindingHelper);
25761             return factory.createCallExpression(getUnscopedHelperName("__exportStar"), 
25762             /*typeArguments*/ undefined, [moduleExpression, exportsExpression]);
25763         }
25764         // Class Fields Helpers
25765         function createClassPrivateFieldGetHelper(receiver, privateField) {
25766             context.requestEmitHelper(ts.classPrivateFieldGetHelper);
25767             return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]);
25768         }
25769         function createClassPrivateFieldSetHelper(receiver, privateField, value) {
25770             context.requestEmitHelper(ts.classPrivateFieldSetHelper);
25771             return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]);
25772         }
25773     }
25774     ts.createEmitHelperFactory = createEmitHelperFactory;
25775     /* @internal */
25776     function compareEmitHelpers(x, y) {
25777         if (x === y)
25778             return 0 /* EqualTo */;
25779         if (x.priority === y.priority)
25780             return 0 /* EqualTo */;
25781         if (x.priority === undefined)
25782             return 1 /* GreaterThan */;
25783         if (y.priority === undefined)
25784             return -1 /* LessThan */;
25785         return ts.compareValues(x.priority, y.priority);
25786     }
25787     ts.compareEmitHelpers = compareEmitHelpers;
25788     /**
25789      * @param input Template string input strings
25790      * @param args Names which need to be made file-level unique
25791      */
25792     function helperString(input) {
25793         var args = [];
25794         for (var _i = 1; _i < arguments.length; _i++) {
25795             args[_i - 1] = arguments[_i];
25796         }
25797         return function (uniqueName) {
25798             var result = "";
25799             for (var i = 0; i < args.length; i++) {
25800                 result += input[i];
25801                 result += uniqueName(args[i]);
25802             }
25803             result += input[input.length - 1];
25804             return result;
25805         };
25806     }
25807     ts.helperString = helperString;
25808     // TypeScript Helpers
25809     ts.decorateHelper = {
25810         name: "typescript:decorate",
25811         importName: "__decorate",
25812         scoped: false,
25813         priority: 2,
25814         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            };"
25815     };
25816     ts.metadataHelper = {
25817         name: "typescript:metadata",
25818         importName: "__metadata",
25819         scoped: false,
25820         priority: 3,
25821         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            };"
25822     };
25823     ts.paramHelper = {
25824         name: "typescript:param",
25825         importName: "__param",
25826         scoped: false,
25827         priority: 4,
25828         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
25829     };
25830     // ES2018 Helpers
25831     ts.assignHelper = {
25832         name: "typescript:assign",
25833         importName: "__assign",
25834         scoped: false,
25835         priority: 1,
25836         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            };"
25837     };
25838     ts.awaitHelper = {
25839         name: "typescript:await",
25840         importName: "__await",
25841         scoped: false,
25842         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
25843     };
25844     ts.asyncGeneratorHelper = {
25845         name: "typescript:asyncGenerator",
25846         importName: "__asyncGenerator",
25847         scoped: false,
25848         dependencies: [ts.awaitHelper],
25849         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            };"
25850     };
25851     ts.asyncDelegator = {
25852         name: "typescript:asyncDelegator",
25853         importName: "__asyncDelegator",
25854         scoped: false,
25855         dependencies: [ts.awaitHelper],
25856         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            };"
25857     };
25858     ts.asyncValues = {
25859         name: "typescript:asyncValues",
25860         importName: "__asyncValues",
25861         scoped: false,
25862         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            };"
25863     };
25864     // ES2018 Destructuring Helpers
25865     ts.restHelper = {
25866         name: "typescript:rest",
25867         importName: "__rest",
25868         scoped: false,
25869         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++) {\n                        if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n                            t[p[i]] = s[p[i]];\n                    }\n                return t;\n            };"
25870     };
25871     // ES2017 Helpers
25872     ts.awaiterHelper = {
25873         name: "typescript:awaiter",
25874         importName: "__awaiter",
25875         scoped: false,
25876         priority: 5,
25877         text: "\n            var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n                function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\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) : adopt(result.value).then(fulfilled, rejected); }\n                    step((generator = generator.apply(thisArg, _arguments || [])).next());\n                });\n            };"
25878     };
25879     // ES2015 Helpers
25880     ts.extendsHelper = {
25881         name: "typescript:extends",
25882         importName: "__extends",
25883         scoped: false,
25884         priority: 0,
25885         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 (Object.prototype.hasOwnProperty.call(b, 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            })();"
25886     };
25887     ts.templateObjectHelper = {
25888         name: "typescript:makeTemplateObject",
25889         importName: "__makeTemplateObject",
25890         scoped: false,
25891         priority: 0,
25892         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            };"
25893     };
25894     ts.readHelper = {
25895         name: "typescript:read",
25896         importName: "__read",
25897         scoped: false,
25898         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            };"
25899     };
25900     ts.spreadHelper = {
25901         name: "typescript:spread",
25902         importName: "__spread",
25903         scoped: false,
25904         dependencies: [ts.readHelper],
25905         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            };"
25906     };
25907     ts.spreadArraysHelper = {
25908         name: "typescript:spreadArrays",
25909         importName: "__spreadArrays",
25910         scoped: false,
25911         text: "\n            var __spreadArrays = (this && this.__spreadArrays) || function () {\n                for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n                for (var r = Array(s), k = 0, i = 0; i < il; i++)\n                    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n                        r[k] = a[j];\n                return r;\n            };"
25912     };
25913     // ES2015 Destructuring Helpers
25914     ts.valuesHelper = {
25915         name: "typescript:values",
25916         importName: "__values",
25917         scoped: false,
25918         text: "\n            var __values = (this && this.__values) || function(o) {\n                var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n                if (m) return m.call(o);\n                if (o && typeof o.length === \"number\") return {\n                    next: function () {\n                        if (o && i >= o.length) o = void 0;\n                        return { value: o && o[i++], done: !o };\n                    }\n                };\n                throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n            };"
25919     };
25920     // ES2015 Generator Helpers
25921     // The __generator helper is used by down-level transformations to emulate the runtime
25922     // semantics of an ES2015 generator function. When called, this helper returns an
25923     // object that implements the Iterator protocol, in that it has `next`, `return`, and
25924     // `throw` methods that step through the generator when invoked.
25925     //
25926     // parameters:
25927     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
25928     //  @param body     A function that acts as the transformed generator body.
25929     //
25930     // variables:
25931     //  _       Persistent state for the generator that is shared between the helper and the
25932     //          generator body. The state object has the following members:
25933     //            sent() - A method that returns or throws the current completion value.
25934     //            label  - The next point at which to resume evaluation of the generator body.
25935     //            trys   - A stack of protected regions (try/catch/finally blocks).
25936     //            ops    - A stack of pending instructions when inside of a finally block.
25937     //  f       A value indicating whether the generator is executing.
25938     //  y       An iterator to delegate for a yield*.
25939     //  t       A temporary variable that holds one of the following values (note that these
25940     //          cases do not overlap):
25941     //          - The completion value when resuming from a `yield` or `yield*`.
25942     //          - The error value for a catch block.
25943     //          - The current protected region (array of try/catch/finally/end labels).
25944     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
25945     //            of a `yield*`.
25946     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
25947     //
25948     // functions:
25949     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
25950     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
25951     //              completed.
25952     //
25953     // The __generator helper understands a limited set of instructions:
25954     //  0: next(value?)     - Start or resume the generator with the specified value.
25955     //  1: throw(error)     - Resume the generator with an exception. If the generator is
25956     //                        suspended inside of one or more protected regions, evaluates
25957     //                        any intervening finally blocks between the current label and
25958     //                        the nearest catch block or function boundary. If uncaught, the
25959     //                        exception is thrown to the caller.
25960     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
25961     //                        suspended inside of one or more protected regions, evaluates any
25962     //                        intervening finally blocks.
25963     //  3: break(label)     - Jump to the specified label. If the label is outside of the
25964     //                        current protected region, evaluates any intervening finally
25965     //                        blocks.
25966     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
25967     //                        resumed, the generator will continue at the next label.
25968     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
25969     //                        delegation completes, the generator will continue at the next
25970     //                        label.
25971     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
25972     //                        the current label is inside of one or more protected regions,
25973     //                        evaluates any intervening finally blocks between the current
25974     //                        label and the nearest catch block or function boundary. If
25975     //                        uncaught, the exception is thrown to the caller.
25976     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
25977     //                        entering a finally block.
25978     //
25979     // For examples of how these are used, see the comments in ./transformers/generators.ts
25980     ts.generatorHelper = {
25981         name: "typescript:generator",
25982         importName: "__generator",
25983         scoped: false,
25984         priority: 6,
25985         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            };"
25986     };
25987     // ES Module Helpers
25988     ts.createBindingHelper = {
25989         name: "typescript:commonjscreatebinding",
25990         importName: "__createBinding",
25991         scoped: false,
25992         priority: 1,
25993         text: "\n            var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n                if (k2 === undefined) k2 = k;\n                Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n            }) : (function(o, m, k, k2) {\n                if (k2 === undefined) k2 = k;\n                o[k2] = m[k];\n            }));"
25994     };
25995     ts.setModuleDefaultHelper = {
25996         name: "typescript:commonjscreatevalue",
25997         importName: "__setModuleDefault",
25998         scoped: false,
25999         priority: 1,
26000         text: "\n            var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n                Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n            }) : function(o, v) {\n                o[\"default\"] = v;\n            });"
26001     };
26002     // emit helper for `import * as Name from "foo"`
26003     ts.importStarHelper = {
26004         name: "typescript:commonjsimportstar",
26005         importName: "__importStar",
26006         scoped: false,
26007         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
26008         priority: 2,
26009         text: "\n            var __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 (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n                __setModuleDefault(result, mod);\n                return result;\n            };"
26010     };
26011     // emit helper for `import Name from "foo"`
26012     ts.importDefaultHelper = {
26013         name: "typescript:commonjsimportdefault",
26014         importName: "__importDefault",
26015         scoped: false,
26016         text: "\n            var __importDefault = (this && this.__importDefault) || function (mod) {\n                return (mod && mod.__esModule) ? mod : { \"default\": mod };\n            };"
26017     };
26018     // emit output for the __export helper function
26019     ts.exportStarHelper = {
26020         name: "typescript:export-star",
26021         importName: "__exportStar",
26022         scoped: false,
26023         dependencies: [ts.createBindingHelper],
26024         priority: 2,
26025         text: "\n            var __exportStar = (this && this.__exportStar) || function(m, exports) {\n                for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n            };"
26026     };
26027     // Class fields helpers
26028     ts.classPrivateFieldGetHelper = {
26029         name: "typescript:classPrivateFieldGet",
26030         importName: "__classPrivateFieldGet",
26031         scoped: false,
26032         text: "\n            var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n                if (!privateMap.has(receiver)) {\n                    throw new TypeError(\"attempted to get private field on non-instance\");\n                }\n                return privateMap.get(receiver);\n            };"
26033     };
26034     ts.classPrivateFieldSetHelper = {
26035         name: "typescript:classPrivateFieldSet",
26036         importName: "__classPrivateFieldSet",
26037         scoped: false,
26038         text: "\n            var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n                if (!privateMap.has(receiver)) {\n                    throw new TypeError(\"attempted to set private field on non-instance\");\n                }\n                privateMap.set(receiver, value);\n                return value;\n            };"
26039     };
26040     var allUnscopedEmitHelpers;
26041     function getAllUnscopedEmitHelpers() {
26042         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
26043             ts.decorateHelper,
26044             ts.metadataHelper,
26045             ts.paramHelper,
26046             ts.assignHelper,
26047             ts.awaitHelper,
26048             ts.asyncGeneratorHelper,
26049             ts.asyncDelegator,
26050             ts.asyncValues,
26051             ts.restHelper,
26052             ts.awaiterHelper,
26053             ts.extendsHelper,
26054             ts.templateObjectHelper,
26055             ts.spreadHelper,
26056             ts.spreadArraysHelper,
26057             ts.valuesHelper,
26058             ts.readHelper,
26059             ts.generatorHelper,
26060             ts.importStarHelper,
26061             ts.importDefaultHelper,
26062             ts.exportStarHelper,
26063             ts.classPrivateFieldGetHelper,
26064             ts.classPrivateFieldSetHelper,
26065             ts.createBindingHelper,
26066             ts.setModuleDefaultHelper
26067         ], function (helper) { return helper.name; }));
26068     }
26069     ts.getAllUnscopedEmitHelpers = getAllUnscopedEmitHelpers;
26070     ts.asyncSuperHelper = {
26071         name: "typescript:async-super",
26072         scoped: true,
26073         text: helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
26074     };
26075     ts.advancedAsyncSuperHelper = {
26076         name: "typescript:advanced-async-super",
26077         scoped: true,
26078         text: 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")
26079     };
26080 })(ts || (ts = {}));
26081 var ts;
26082 (function (ts) {
26083     // Literals
26084     function isNumericLiteral(node) {
26085         return node.kind === 8 /* NumericLiteral */;
26086     }
26087     ts.isNumericLiteral = isNumericLiteral;
26088     function isBigIntLiteral(node) {
26089         return node.kind === 9 /* BigIntLiteral */;
26090     }
26091     ts.isBigIntLiteral = isBigIntLiteral;
26092     function isStringLiteral(node) {
26093         return node.kind === 10 /* StringLiteral */;
26094     }
26095     ts.isStringLiteral = isStringLiteral;
26096     function isJsxText(node) {
26097         return node.kind === 11 /* JsxText */;
26098     }
26099     ts.isJsxText = isJsxText;
26100     function isRegularExpressionLiteral(node) {
26101         return node.kind === 13 /* RegularExpressionLiteral */;
26102     }
26103     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
26104     function isNoSubstitutionTemplateLiteral(node) {
26105         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
26106     }
26107     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
26108     // Pseudo-literals
26109     function isTemplateHead(node) {
26110         return node.kind === 15 /* TemplateHead */;
26111     }
26112     ts.isTemplateHead = isTemplateHead;
26113     function isTemplateMiddle(node) {
26114         return node.kind === 16 /* TemplateMiddle */;
26115     }
26116     ts.isTemplateMiddle = isTemplateMiddle;
26117     function isTemplateTail(node) {
26118         return node.kind === 17 /* TemplateTail */;
26119     }
26120     ts.isTemplateTail = isTemplateTail;
26121     // Identifiers
26122     function isIdentifier(node) {
26123         return node.kind === 78 /* Identifier */;
26124     }
26125     ts.isIdentifier = isIdentifier;
26126     // Names
26127     function isQualifiedName(node) {
26128         return node.kind === 157 /* QualifiedName */;
26129     }
26130     ts.isQualifiedName = isQualifiedName;
26131     function isComputedPropertyName(node) {
26132         return node.kind === 158 /* ComputedPropertyName */;
26133     }
26134     ts.isComputedPropertyName = isComputedPropertyName;
26135     function isPrivateIdentifier(node) {
26136         return node.kind === 79 /* PrivateIdentifier */;
26137     }
26138     ts.isPrivateIdentifier = isPrivateIdentifier;
26139     // Tokens
26140     /*@internal*/
26141     function isSuperKeyword(node) {
26142         return node.kind === 105 /* SuperKeyword */;
26143     }
26144     ts.isSuperKeyword = isSuperKeyword;
26145     /*@internal*/
26146     function isImportKeyword(node) {
26147         return node.kind === 99 /* ImportKeyword */;
26148     }
26149     ts.isImportKeyword = isImportKeyword;
26150     /*@internal*/
26151     function isCommaToken(node) {
26152         return node.kind === 27 /* CommaToken */;
26153     }
26154     ts.isCommaToken = isCommaToken;
26155     /*@internal*/
26156     function isQuestionToken(node) {
26157         return node.kind === 57 /* QuestionToken */;
26158     }
26159     ts.isQuestionToken = isQuestionToken;
26160     /*@internal*/
26161     function isExclamationToken(node) {
26162         return node.kind === 53 /* ExclamationToken */;
26163     }
26164     ts.isExclamationToken = isExclamationToken;
26165     // Signature elements
26166     function isTypeParameterDeclaration(node) {
26167         return node.kind === 159 /* TypeParameter */;
26168     }
26169     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
26170     // TODO(rbuckton): Rename to 'isParameterDeclaration'
26171     function isParameter(node) {
26172         return node.kind === 160 /* Parameter */;
26173     }
26174     ts.isParameter = isParameter;
26175     function isDecorator(node) {
26176         return node.kind === 161 /* Decorator */;
26177     }
26178     ts.isDecorator = isDecorator;
26179     // TypeMember
26180     function isPropertySignature(node) {
26181         return node.kind === 162 /* PropertySignature */;
26182     }
26183     ts.isPropertySignature = isPropertySignature;
26184     function isPropertyDeclaration(node) {
26185         return node.kind === 163 /* PropertyDeclaration */;
26186     }
26187     ts.isPropertyDeclaration = isPropertyDeclaration;
26188     function isMethodSignature(node) {
26189         return node.kind === 164 /* MethodSignature */;
26190     }
26191     ts.isMethodSignature = isMethodSignature;
26192     function isMethodDeclaration(node) {
26193         return node.kind === 165 /* MethodDeclaration */;
26194     }
26195     ts.isMethodDeclaration = isMethodDeclaration;
26196     function isConstructorDeclaration(node) {
26197         return node.kind === 166 /* Constructor */;
26198     }
26199     ts.isConstructorDeclaration = isConstructorDeclaration;
26200     function isGetAccessorDeclaration(node) {
26201         return node.kind === 167 /* GetAccessor */;
26202     }
26203     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
26204     function isSetAccessorDeclaration(node) {
26205         return node.kind === 168 /* SetAccessor */;
26206     }
26207     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
26208     function isCallSignatureDeclaration(node) {
26209         return node.kind === 169 /* CallSignature */;
26210     }
26211     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
26212     function isConstructSignatureDeclaration(node) {
26213         return node.kind === 170 /* ConstructSignature */;
26214     }
26215     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
26216     function isIndexSignatureDeclaration(node) {
26217         return node.kind === 171 /* IndexSignature */;
26218     }
26219     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
26220     // Type
26221     function isTypePredicateNode(node) {
26222         return node.kind === 172 /* TypePredicate */;
26223     }
26224     ts.isTypePredicateNode = isTypePredicateNode;
26225     function isTypeReferenceNode(node) {
26226         return node.kind === 173 /* TypeReference */;
26227     }
26228     ts.isTypeReferenceNode = isTypeReferenceNode;
26229     function isFunctionTypeNode(node) {
26230         return node.kind === 174 /* FunctionType */;
26231     }
26232     ts.isFunctionTypeNode = isFunctionTypeNode;
26233     function isConstructorTypeNode(node) {
26234         return node.kind === 175 /* ConstructorType */;
26235     }
26236     ts.isConstructorTypeNode = isConstructorTypeNode;
26237     function isTypeQueryNode(node) {
26238         return node.kind === 176 /* TypeQuery */;
26239     }
26240     ts.isTypeQueryNode = isTypeQueryNode;
26241     function isTypeLiteralNode(node) {
26242         return node.kind === 177 /* TypeLiteral */;
26243     }
26244     ts.isTypeLiteralNode = isTypeLiteralNode;
26245     function isArrayTypeNode(node) {
26246         return node.kind === 178 /* ArrayType */;
26247     }
26248     ts.isArrayTypeNode = isArrayTypeNode;
26249     function isTupleTypeNode(node) {
26250         return node.kind === 179 /* TupleType */;
26251     }
26252     ts.isTupleTypeNode = isTupleTypeNode;
26253     function isNamedTupleMember(node) {
26254         return node.kind === 192 /* NamedTupleMember */;
26255     }
26256     ts.isNamedTupleMember = isNamedTupleMember;
26257     function isOptionalTypeNode(node) {
26258         return node.kind === 180 /* OptionalType */;
26259     }
26260     ts.isOptionalTypeNode = isOptionalTypeNode;
26261     function isRestTypeNode(node) {
26262         return node.kind === 181 /* RestType */;
26263     }
26264     ts.isRestTypeNode = isRestTypeNode;
26265     function isUnionTypeNode(node) {
26266         return node.kind === 182 /* UnionType */;
26267     }
26268     ts.isUnionTypeNode = isUnionTypeNode;
26269     function isIntersectionTypeNode(node) {
26270         return node.kind === 183 /* IntersectionType */;
26271     }
26272     ts.isIntersectionTypeNode = isIntersectionTypeNode;
26273     function isConditionalTypeNode(node) {
26274         return node.kind === 184 /* ConditionalType */;
26275     }
26276     ts.isConditionalTypeNode = isConditionalTypeNode;
26277     function isInferTypeNode(node) {
26278         return node.kind === 185 /* InferType */;
26279     }
26280     ts.isInferTypeNode = isInferTypeNode;
26281     function isParenthesizedTypeNode(node) {
26282         return node.kind === 186 /* ParenthesizedType */;
26283     }
26284     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
26285     function isThisTypeNode(node) {
26286         return node.kind === 187 /* ThisType */;
26287     }
26288     ts.isThisTypeNode = isThisTypeNode;
26289     function isTypeOperatorNode(node) {
26290         return node.kind === 188 /* TypeOperator */;
26291     }
26292     ts.isTypeOperatorNode = isTypeOperatorNode;
26293     function isIndexedAccessTypeNode(node) {
26294         return node.kind === 189 /* IndexedAccessType */;
26295     }
26296     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
26297     function isMappedTypeNode(node) {
26298         return node.kind === 190 /* MappedType */;
26299     }
26300     ts.isMappedTypeNode = isMappedTypeNode;
26301     function isLiteralTypeNode(node) {
26302         return node.kind === 191 /* LiteralType */;
26303     }
26304     ts.isLiteralTypeNode = isLiteralTypeNode;
26305     function isImportTypeNode(node) {
26306         return node.kind === 195 /* ImportType */;
26307     }
26308     ts.isImportTypeNode = isImportTypeNode;
26309     function isTemplateLiteralTypeSpan(node) {
26310         return node.kind === 194 /* TemplateLiteralTypeSpan */;
26311     }
26312     ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan;
26313     function isTemplateLiteralTypeNode(node) {
26314         return node.kind === 193 /* TemplateLiteralType */;
26315     }
26316     ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode;
26317     // Binding patterns
26318     function isObjectBindingPattern(node) {
26319         return node.kind === 196 /* ObjectBindingPattern */;
26320     }
26321     ts.isObjectBindingPattern = isObjectBindingPattern;
26322     function isArrayBindingPattern(node) {
26323         return node.kind === 197 /* ArrayBindingPattern */;
26324     }
26325     ts.isArrayBindingPattern = isArrayBindingPattern;
26326     function isBindingElement(node) {
26327         return node.kind === 198 /* BindingElement */;
26328     }
26329     ts.isBindingElement = isBindingElement;
26330     // Expression
26331     function isArrayLiteralExpression(node) {
26332         return node.kind === 199 /* ArrayLiteralExpression */;
26333     }
26334     ts.isArrayLiteralExpression = isArrayLiteralExpression;
26335     function isObjectLiteralExpression(node) {
26336         return node.kind === 200 /* ObjectLiteralExpression */;
26337     }
26338     ts.isObjectLiteralExpression = isObjectLiteralExpression;
26339     function isPropertyAccessExpression(node) {
26340         return node.kind === 201 /* PropertyAccessExpression */;
26341     }
26342     ts.isPropertyAccessExpression = isPropertyAccessExpression;
26343     function isElementAccessExpression(node) {
26344         return node.kind === 202 /* ElementAccessExpression */;
26345     }
26346     ts.isElementAccessExpression = isElementAccessExpression;
26347     function isCallExpression(node) {
26348         return node.kind === 203 /* CallExpression */;
26349     }
26350     ts.isCallExpression = isCallExpression;
26351     function isNewExpression(node) {
26352         return node.kind === 204 /* NewExpression */;
26353     }
26354     ts.isNewExpression = isNewExpression;
26355     function isTaggedTemplateExpression(node) {
26356         return node.kind === 205 /* TaggedTemplateExpression */;
26357     }
26358     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
26359     function isTypeAssertionExpression(node) {
26360         return node.kind === 206 /* TypeAssertionExpression */;
26361     }
26362     ts.isTypeAssertionExpression = isTypeAssertionExpression;
26363     function isParenthesizedExpression(node) {
26364         return node.kind === 207 /* ParenthesizedExpression */;
26365     }
26366     ts.isParenthesizedExpression = isParenthesizedExpression;
26367     function isFunctionExpression(node) {
26368         return node.kind === 208 /* FunctionExpression */;
26369     }
26370     ts.isFunctionExpression = isFunctionExpression;
26371     function isArrowFunction(node) {
26372         return node.kind === 209 /* ArrowFunction */;
26373     }
26374     ts.isArrowFunction = isArrowFunction;
26375     function isDeleteExpression(node) {
26376         return node.kind === 210 /* DeleteExpression */;
26377     }
26378     ts.isDeleteExpression = isDeleteExpression;
26379     function isTypeOfExpression(node) {
26380         return node.kind === 211 /* TypeOfExpression */;
26381     }
26382     ts.isTypeOfExpression = isTypeOfExpression;
26383     function isVoidExpression(node) {
26384         return node.kind === 212 /* VoidExpression */;
26385     }
26386     ts.isVoidExpression = isVoidExpression;
26387     function isAwaitExpression(node) {
26388         return node.kind === 213 /* AwaitExpression */;
26389     }
26390     ts.isAwaitExpression = isAwaitExpression;
26391     function isPrefixUnaryExpression(node) {
26392         return node.kind === 214 /* PrefixUnaryExpression */;
26393     }
26394     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
26395     function isPostfixUnaryExpression(node) {
26396         return node.kind === 215 /* PostfixUnaryExpression */;
26397     }
26398     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
26399     function isBinaryExpression(node) {
26400         return node.kind === 216 /* BinaryExpression */;
26401     }
26402     ts.isBinaryExpression = isBinaryExpression;
26403     function isConditionalExpression(node) {
26404         return node.kind === 217 /* ConditionalExpression */;
26405     }
26406     ts.isConditionalExpression = isConditionalExpression;
26407     function isTemplateExpression(node) {
26408         return node.kind === 218 /* TemplateExpression */;
26409     }
26410     ts.isTemplateExpression = isTemplateExpression;
26411     function isYieldExpression(node) {
26412         return node.kind === 219 /* YieldExpression */;
26413     }
26414     ts.isYieldExpression = isYieldExpression;
26415     function isSpreadElement(node) {
26416         return node.kind === 220 /* SpreadElement */;
26417     }
26418     ts.isSpreadElement = isSpreadElement;
26419     function isClassExpression(node) {
26420         return node.kind === 221 /* ClassExpression */;
26421     }
26422     ts.isClassExpression = isClassExpression;
26423     function isOmittedExpression(node) {
26424         return node.kind === 222 /* OmittedExpression */;
26425     }
26426     ts.isOmittedExpression = isOmittedExpression;
26427     function isExpressionWithTypeArguments(node) {
26428         return node.kind === 223 /* ExpressionWithTypeArguments */;
26429     }
26430     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
26431     function isAsExpression(node) {
26432         return node.kind === 224 /* AsExpression */;
26433     }
26434     ts.isAsExpression = isAsExpression;
26435     function isNonNullExpression(node) {
26436         return node.kind === 225 /* NonNullExpression */;
26437     }
26438     ts.isNonNullExpression = isNonNullExpression;
26439     function isMetaProperty(node) {
26440         return node.kind === 226 /* MetaProperty */;
26441     }
26442     ts.isMetaProperty = isMetaProperty;
26443     function isSyntheticExpression(node) {
26444         return node.kind === 227 /* SyntheticExpression */;
26445     }
26446     ts.isSyntheticExpression = isSyntheticExpression;
26447     function isPartiallyEmittedExpression(node) {
26448         return node.kind === 336 /* PartiallyEmittedExpression */;
26449     }
26450     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
26451     function isCommaListExpression(node) {
26452         return node.kind === 337 /* CommaListExpression */;
26453     }
26454     ts.isCommaListExpression = isCommaListExpression;
26455     // Misc
26456     function isTemplateSpan(node) {
26457         return node.kind === 228 /* TemplateSpan */;
26458     }
26459     ts.isTemplateSpan = isTemplateSpan;
26460     function isSemicolonClassElement(node) {
26461         return node.kind === 229 /* SemicolonClassElement */;
26462     }
26463     ts.isSemicolonClassElement = isSemicolonClassElement;
26464     // Elements
26465     function isBlock(node) {
26466         return node.kind === 230 /* Block */;
26467     }
26468     ts.isBlock = isBlock;
26469     function isVariableStatement(node) {
26470         return node.kind === 232 /* VariableStatement */;
26471     }
26472     ts.isVariableStatement = isVariableStatement;
26473     function isEmptyStatement(node) {
26474         return node.kind === 231 /* EmptyStatement */;
26475     }
26476     ts.isEmptyStatement = isEmptyStatement;
26477     function isExpressionStatement(node) {
26478         return node.kind === 233 /* ExpressionStatement */;
26479     }
26480     ts.isExpressionStatement = isExpressionStatement;
26481     function isIfStatement(node) {
26482         return node.kind === 234 /* IfStatement */;
26483     }
26484     ts.isIfStatement = isIfStatement;
26485     function isDoStatement(node) {
26486         return node.kind === 235 /* DoStatement */;
26487     }
26488     ts.isDoStatement = isDoStatement;
26489     function isWhileStatement(node) {
26490         return node.kind === 236 /* WhileStatement */;
26491     }
26492     ts.isWhileStatement = isWhileStatement;
26493     function isForStatement(node) {
26494         return node.kind === 237 /* ForStatement */;
26495     }
26496     ts.isForStatement = isForStatement;
26497     function isForInStatement(node) {
26498         return node.kind === 238 /* ForInStatement */;
26499     }
26500     ts.isForInStatement = isForInStatement;
26501     function isForOfStatement(node) {
26502         return node.kind === 239 /* ForOfStatement */;
26503     }
26504     ts.isForOfStatement = isForOfStatement;
26505     function isContinueStatement(node) {
26506         return node.kind === 240 /* ContinueStatement */;
26507     }
26508     ts.isContinueStatement = isContinueStatement;
26509     function isBreakStatement(node) {
26510         return node.kind === 241 /* BreakStatement */;
26511     }
26512     ts.isBreakStatement = isBreakStatement;
26513     function isReturnStatement(node) {
26514         return node.kind === 242 /* ReturnStatement */;
26515     }
26516     ts.isReturnStatement = isReturnStatement;
26517     function isWithStatement(node) {
26518         return node.kind === 243 /* WithStatement */;
26519     }
26520     ts.isWithStatement = isWithStatement;
26521     function isSwitchStatement(node) {
26522         return node.kind === 244 /* SwitchStatement */;
26523     }
26524     ts.isSwitchStatement = isSwitchStatement;
26525     function isLabeledStatement(node) {
26526         return node.kind === 245 /* LabeledStatement */;
26527     }
26528     ts.isLabeledStatement = isLabeledStatement;
26529     function isThrowStatement(node) {
26530         return node.kind === 246 /* ThrowStatement */;
26531     }
26532     ts.isThrowStatement = isThrowStatement;
26533     function isTryStatement(node) {
26534         return node.kind === 247 /* TryStatement */;
26535     }
26536     ts.isTryStatement = isTryStatement;
26537     function isDebuggerStatement(node) {
26538         return node.kind === 248 /* DebuggerStatement */;
26539     }
26540     ts.isDebuggerStatement = isDebuggerStatement;
26541     function isVariableDeclaration(node) {
26542         return node.kind === 249 /* VariableDeclaration */;
26543     }
26544     ts.isVariableDeclaration = isVariableDeclaration;
26545     function isVariableDeclarationList(node) {
26546         return node.kind === 250 /* VariableDeclarationList */;
26547     }
26548     ts.isVariableDeclarationList = isVariableDeclarationList;
26549     function isFunctionDeclaration(node) {
26550         return node.kind === 251 /* FunctionDeclaration */;
26551     }
26552     ts.isFunctionDeclaration = isFunctionDeclaration;
26553     function isClassDeclaration(node) {
26554         return node.kind === 252 /* ClassDeclaration */;
26555     }
26556     ts.isClassDeclaration = isClassDeclaration;
26557     function isInterfaceDeclaration(node) {
26558         return node.kind === 253 /* InterfaceDeclaration */;
26559     }
26560     ts.isInterfaceDeclaration = isInterfaceDeclaration;
26561     function isTypeAliasDeclaration(node) {
26562         return node.kind === 254 /* TypeAliasDeclaration */;
26563     }
26564     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
26565     function isEnumDeclaration(node) {
26566         return node.kind === 255 /* EnumDeclaration */;
26567     }
26568     ts.isEnumDeclaration = isEnumDeclaration;
26569     function isModuleDeclaration(node) {
26570         return node.kind === 256 /* ModuleDeclaration */;
26571     }
26572     ts.isModuleDeclaration = isModuleDeclaration;
26573     function isModuleBlock(node) {
26574         return node.kind === 257 /* ModuleBlock */;
26575     }
26576     ts.isModuleBlock = isModuleBlock;
26577     function isCaseBlock(node) {
26578         return node.kind === 258 /* CaseBlock */;
26579     }
26580     ts.isCaseBlock = isCaseBlock;
26581     function isNamespaceExportDeclaration(node) {
26582         return node.kind === 259 /* NamespaceExportDeclaration */;
26583     }
26584     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
26585     function isImportEqualsDeclaration(node) {
26586         return node.kind === 260 /* ImportEqualsDeclaration */;
26587     }
26588     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
26589     function isImportDeclaration(node) {
26590         return node.kind === 261 /* ImportDeclaration */;
26591     }
26592     ts.isImportDeclaration = isImportDeclaration;
26593     function isImportClause(node) {
26594         return node.kind === 262 /* ImportClause */;
26595     }
26596     ts.isImportClause = isImportClause;
26597     function isNamespaceImport(node) {
26598         return node.kind === 263 /* NamespaceImport */;
26599     }
26600     ts.isNamespaceImport = isNamespaceImport;
26601     function isNamespaceExport(node) {
26602         return node.kind === 269 /* NamespaceExport */;
26603     }
26604     ts.isNamespaceExport = isNamespaceExport;
26605     function isNamedImports(node) {
26606         return node.kind === 264 /* NamedImports */;
26607     }
26608     ts.isNamedImports = isNamedImports;
26609     function isImportSpecifier(node) {
26610         return node.kind === 265 /* ImportSpecifier */;
26611     }
26612     ts.isImportSpecifier = isImportSpecifier;
26613     function isExportAssignment(node) {
26614         return node.kind === 266 /* ExportAssignment */;
26615     }
26616     ts.isExportAssignment = isExportAssignment;
26617     function isExportDeclaration(node) {
26618         return node.kind === 267 /* ExportDeclaration */;
26619     }
26620     ts.isExportDeclaration = isExportDeclaration;
26621     function isNamedExports(node) {
26622         return node.kind === 268 /* NamedExports */;
26623     }
26624     ts.isNamedExports = isNamedExports;
26625     function isExportSpecifier(node) {
26626         return node.kind === 270 /* ExportSpecifier */;
26627     }
26628     ts.isExportSpecifier = isExportSpecifier;
26629     function isMissingDeclaration(node) {
26630         return node.kind === 271 /* MissingDeclaration */;
26631     }
26632     ts.isMissingDeclaration = isMissingDeclaration;
26633     function isNotEmittedStatement(node) {
26634         return node.kind === 335 /* NotEmittedStatement */;
26635     }
26636     ts.isNotEmittedStatement = isNotEmittedStatement;
26637     /* @internal */
26638     function isSyntheticReference(node) {
26639         return node.kind === 340 /* SyntheticReferenceExpression */;
26640     }
26641     ts.isSyntheticReference = isSyntheticReference;
26642     /* @internal */
26643     function isMergeDeclarationMarker(node) {
26644         return node.kind === 338 /* MergeDeclarationMarker */;
26645     }
26646     ts.isMergeDeclarationMarker = isMergeDeclarationMarker;
26647     /* @internal */
26648     function isEndOfDeclarationMarker(node) {
26649         return node.kind === 339 /* EndOfDeclarationMarker */;
26650     }
26651     ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker;
26652     // Module References
26653     function isExternalModuleReference(node) {
26654         return node.kind === 272 /* ExternalModuleReference */;
26655     }
26656     ts.isExternalModuleReference = isExternalModuleReference;
26657     // JSX
26658     function isJsxElement(node) {
26659         return node.kind === 273 /* JsxElement */;
26660     }
26661     ts.isJsxElement = isJsxElement;
26662     function isJsxSelfClosingElement(node) {
26663         return node.kind === 274 /* JsxSelfClosingElement */;
26664     }
26665     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
26666     function isJsxOpeningElement(node) {
26667         return node.kind === 275 /* JsxOpeningElement */;
26668     }
26669     ts.isJsxOpeningElement = isJsxOpeningElement;
26670     function isJsxClosingElement(node) {
26671         return node.kind === 276 /* JsxClosingElement */;
26672     }
26673     ts.isJsxClosingElement = isJsxClosingElement;
26674     function isJsxFragment(node) {
26675         return node.kind === 277 /* JsxFragment */;
26676     }
26677     ts.isJsxFragment = isJsxFragment;
26678     function isJsxOpeningFragment(node) {
26679         return node.kind === 278 /* JsxOpeningFragment */;
26680     }
26681     ts.isJsxOpeningFragment = isJsxOpeningFragment;
26682     function isJsxClosingFragment(node) {
26683         return node.kind === 279 /* JsxClosingFragment */;
26684     }
26685     ts.isJsxClosingFragment = isJsxClosingFragment;
26686     function isJsxAttribute(node) {
26687         return node.kind === 280 /* JsxAttribute */;
26688     }
26689     ts.isJsxAttribute = isJsxAttribute;
26690     function isJsxAttributes(node) {
26691         return node.kind === 281 /* JsxAttributes */;
26692     }
26693     ts.isJsxAttributes = isJsxAttributes;
26694     function isJsxSpreadAttribute(node) {
26695         return node.kind === 282 /* JsxSpreadAttribute */;
26696     }
26697     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
26698     function isJsxExpression(node) {
26699         return node.kind === 283 /* JsxExpression */;
26700     }
26701     ts.isJsxExpression = isJsxExpression;
26702     // Clauses
26703     function isCaseClause(node) {
26704         return node.kind === 284 /* CaseClause */;
26705     }
26706     ts.isCaseClause = isCaseClause;
26707     function isDefaultClause(node) {
26708         return node.kind === 285 /* DefaultClause */;
26709     }
26710     ts.isDefaultClause = isDefaultClause;
26711     function isHeritageClause(node) {
26712         return node.kind === 286 /* HeritageClause */;
26713     }
26714     ts.isHeritageClause = isHeritageClause;
26715     function isCatchClause(node) {
26716         return node.kind === 287 /* CatchClause */;
26717     }
26718     ts.isCatchClause = isCatchClause;
26719     // Property assignments
26720     function isPropertyAssignment(node) {
26721         return node.kind === 288 /* PropertyAssignment */;
26722     }
26723     ts.isPropertyAssignment = isPropertyAssignment;
26724     function isShorthandPropertyAssignment(node) {
26725         return node.kind === 289 /* ShorthandPropertyAssignment */;
26726     }
26727     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
26728     function isSpreadAssignment(node) {
26729         return node.kind === 290 /* SpreadAssignment */;
26730     }
26731     ts.isSpreadAssignment = isSpreadAssignment;
26732     // Enum
26733     function isEnumMember(node) {
26734         return node.kind === 291 /* EnumMember */;
26735     }
26736     ts.isEnumMember = isEnumMember;
26737     // Unparsed
26738     // TODO(rbuckton): isUnparsedPrologue
26739     function isUnparsedPrepend(node) {
26740         return node.kind === 293 /* UnparsedPrepend */;
26741     }
26742     ts.isUnparsedPrepend = isUnparsedPrepend;
26743     // TODO(rbuckton): isUnparsedText
26744     // TODO(rbuckton): isUnparsedInternalText
26745     // TODO(rbuckton): isUnparsedSyntheticReference
26746     // Top-level nodes
26747     function isSourceFile(node) {
26748         return node.kind === 297 /* SourceFile */;
26749     }
26750     ts.isSourceFile = isSourceFile;
26751     function isBundle(node) {
26752         return node.kind === 298 /* Bundle */;
26753     }
26754     ts.isBundle = isBundle;
26755     function isUnparsedSource(node) {
26756         return node.kind === 299 /* UnparsedSource */;
26757     }
26758     ts.isUnparsedSource = isUnparsedSource;
26759     // TODO(rbuckton): isInputFiles
26760     // JSDoc Elements
26761     function isJSDocTypeExpression(node) {
26762         return node.kind === 301 /* JSDocTypeExpression */;
26763     }
26764     ts.isJSDocTypeExpression = isJSDocTypeExpression;
26765     function isJSDocNameReference(node) {
26766         return node.kind === 302 /* JSDocNameReference */;
26767     }
26768     ts.isJSDocNameReference = isJSDocNameReference;
26769     function isJSDocAllType(node) {
26770         return node.kind === 303 /* JSDocAllType */;
26771     }
26772     ts.isJSDocAllType = isJSDocAllType;
26773     function isJSDocUnknownType(node) {
26774         return node.kind === 304 /* JSDocUnknownType */;
26775     }
26776     ts.isJSDocUnknownType = isJSDocUnknownType;
26777     function isJSDocNullableType(node) {
26778         return node.kind === 305 /* JSDocNullableType */;
26779     }
26780     ts.isJSDocNullableType = isJSDocNullableType;
26781     function isJSDocNonNullableType(node) {
26782         return node.kind === 306 /* JSDocNonNullableType */;
26783     }
26784     ts.isJSDocNonNullableType = isJSDocNonNullableType;
26785     function isJSDocOptionalType(node) {
26786         return node.kind === 307 /* JSDocOptionalType */;
26787     }
26788     ts.isJSDocOptionalType = isJSDocOptionalType;
26789     function isJSDocFunctionType(node) {
26790         return node.kind === 308 /* JSDocFunctionType */;
26791     }
26792     ts.isJSDocFunctionType = isJSDocFunctionType;
26793     function isJSDocVariadicType(node) {
26794         return node.kind === 309 /* JSDocVariadicType */;
26795     }
26796     ts.isJSDocVariadicType = isJSDocVariadicType;
26797     function isJSDocNamepathType(node) {
26798         return node.kind === 310 /* JSDocNamepathType */;
26799     }
26800     ts.isJSDocNamepathType = isJSDocNamepathType;
26801     function isJSDoc(node) {
26802         return node.kind === 311 /* JSDocComment */;
26803     }
26804     ts.isJSDoc = isJSDoc;
26805     function isJSDocTypeLiteral(node) {
26806         return node.kind === 312 /* JSDocTypeLiteral */;
26807     }
26808     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
26809     function isJSDocSignature(node) {
26810         return node.kind === 313 /* JSDocSignature */;
26811     }
26812     ts.isJSDocSignature = isJSDocSignature;
26813     // JSDoc Tags
26814     function isJSDocAugmentsTag(node) {
26815         return node.kind === 315 /* JSDocAugmentsTag */;
26816     }
26817     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
26818     function isJSDocAuthorTag(node) {
26819         return node.kind === 317 /* JSDocAuthorTag */;
26820     }
26821     ts.isJSDocAuthorTag = isJSDocAuthorTag;
26822     function isJSDocClassTag(node) {
26823         return node.kind === 319 /* JSDocClassTag */;
26824     }
26825     ts.isJSDocClassTag = isJSDocClassTag;
26826     function isJSDocCallbackTag(node) {
26827         return node.kind === 324 /* JSDocCallbackTag */;
26828     }
26829     ts.isJSDocCallbackTag = isJSDocCallbackTag;
26830     function isJSDocPublicTag(node) {
26831         return node.kind === 320 /* JSDocPublicTag */;
26832     }
26833     ts.isJSDocPublicTag = isJSDocPublicTag;
26834     function isJSDocPrivateTag(node) {
26835         return node.kind === 321 /* JSDocPrivateTag */;
26836     }
26837     ts.isJSDocPrivateTag = isJSDocPrivateTag;
26838     function isJSDocProtectedTag(node) {
26839         return node.kind === 322 /* JSDocProtectedTag */;
26840     }
26841     ts.isJSDocProtectedTag = isJSDocProtectedTag;
26842     function isJSDocReadonlyTag(node) {
26843         return node.kind === 323 /* JSDocReadonlyTag */;
26844     }
26845     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
26846     function isJSDocDeprecatedTag(node) {
26847         return node.kind === 318 /* JSDocDeprecatedTag */;
26848     }
26849     ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag;
26850     function isJSDocEnumTag(node) {
26851         return node.kind === 325 /* JSDocEnumTag */;
26852     }
26853     ts.isJSDocEnumTag = isJSDocEnumTag;
26854     function isJSDocParameterTag(node) {
26855         return node.kind === 326 /* JSDocParameterTag */;
26856     }
26857     ts.isJSDocParameterTag = isJSDocParameterTag;
26858     function isJSDocReturnTag(node) {
26859         return node.kind === 327 /* JSDocReturnTag */;
26860     }
26861     ts.isJSDocReturnTag = isJSDocReturnTag;
26862     function isJSDocThisTag(node) {
26863         return node.kind === 328 /* JSDocThisTag */;
26864     }
26865     ts.isJSDocThisTag = isJSDocThisTag;
26866     function isJSDocTypeTag(node) {
26867         return node.kind === 329 /* JSDocTypeTag */;
26868     }
26869     ts.isJSDocTypeTag = isJSDocTypeTag;
26870     function isJSDocTemplateTag(node) {
26871         return node.kind === 330 /* JSDocTemplateTag */;
26872     }
26873     ts.isJSDocTemplateTag = isJSDocTemplateTag;
26874     function isJSDocTypedefTag(node) {
26875         return node.kind === 331 /* JSDocTypedefTag */;
26876     }
26877     ts.isJSDocTypedefTag = isJSDocTypedefTag;
26878     function isJSDocUnknownTag(node) {
26879         return node.kind === 314 /* JSDocTag */;
26880     }
26881     ts.isJSDocUnknownTag = isJSDocUnknownTag;
26882     function isJSDocPropertyTag(node) {
26883         return node.kind === 333 /* JSDocPropertyTag */;
26884     }
26885     ts.isJSDocPropertyTag = isJSDocPropertyTag;
26886     function isJSDocImplementsTag(node) {
26887         return node.kind === 316 /* JSDocImplementsTag */;
26888     }
26889     ts.isJSDocImplementsTag = isJSDocImplementsTag;
26890     // Synthesized list
26891     /* @internal */
26892     function isSyntaxList(n) {
26893         return n.kind === 334 /* SyntaxList */;
26894     }
26895     ts.isSyntaxList = isSyntaxList;
26896 })(ts || (ts = {}));
26897 /* @internal */
26898 var ts;
26899 (function (ts) {
26900     // Compound nodes
26901     function createEmptyExports(factory) {
26902         return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined);
26903     }
26904     ts.createEmptyExports = createEmptyExports;
26905     function createMemberAccessForPropertyName(factory, target, memberName, location) {
26906         if (ts.isComputedPropertyName(memberName)) {
26907             return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location);
26908         }
26909         else {
26910             var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName)
26911                 ? factory.createPropertyAccessExpression(target, memberName)
26912                 : factory.createElementAccessExpression(target, memberName), memberName);
26913             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
26914             return expression;
26915         }
26916     }
26917     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
26918     function createReactNamespace(reactNamespace, parent) {
26919         // To ensure the emit resolver can properly resolve the namespace, we need to
26920         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
26921         // flag and setting a parent node.
26922         var react = ts.parseNodeFactory.createIdentifier(reactNamespace || "React");
26923         // Set the parent that is in parse tree
26924         // this makes sure that parent chain is intact for checker to traverse complete scope tree
26925         ts.setParent(react, ts.getParseTreeNode(parent));
26926         return react;
26927     }
26928     function createJsxFactoryExpressionFromEntityName(factory, jsxFactory, parent) {
26929         if (ts.isQualifiedName(jsxFactory)) {
26930             var left = createJsxFactoryExpressionFromEntityName(factory, jsxFactory.left, parent);
26931             var right = factory.createIdentifier(ts.idText(jsxFactory.right));
26932             right.escapedText = jsxFactory.right.escapedText;
26933             return factory.createPropertyAccessExpression(left, right);
26934         }
26935         else {
26936             return createReactNamespace(ts.idText(jsxFactory), parent);
26937         }
26938     }
26939     function createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parent) {
26940         return jsxFactoryEntity ?
26941             createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) :
26942             factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "createElement");
26943     }
26944     ts.createJsxFactoryExpression = createJsxFactoryExpression;
26945     function createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parent) {
26946         return jsxFragmentFactoryEntity ?
26947             createJsxFactoryExpressionFromEntityName(factory, jsxFragmentFactoryEntity, parent) :
26948             factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "Fragment");
26949     }
26950     function createExpressionForJsxElement(factory, callee, tagName, props, children, location) {
26951         var argumentsList = [tagName];
26952         if (props) {
26953             argumentsList.push(props);
26954         }
26955         if (children && children.length > 0) {
26956             if (!props) {
26957                 argumentsList.push(factory.createNull());
26958             }
26959             if (children.length > 1) {
26960                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
26961                     var child = children_3[_i];
26962                     startOnNewLine(child);
26963                     argumentsList.push(child);
26964                 }
26965             }
26966             else {
26967                 argumentsList.push(children[0]);
26968             }
26969         }
26970         return ts.setTextRange(factory.createCallExpression(callee, 
26971         /*typeArguments*/ undefined, argumentsList), location);
26972     }
26973     ts.createExpressionForJsxElement = createExpressionForJsxElement;
26974     function createExpressionForJsxFragment(factory, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) {
26975         var tagName = createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parentElement);
26976         var argumentsList = [tagName, factory.createNull()];
26977         if (children && children.length > 0) {
26978             if (children.length > 1) {
26979                 for (var _i = 0, children_4 = children; _i < children_4.length; _i++) {
26980                     var child = children_4[_i];
26981                     startOnNewLine(child);
26982                     argumentsList.push(child);
26983                 }
26984             }
26985             else {
26986                 argumentsList.push(children[0]);
26987             }
26988         }
26989         return ts.setTextRange(factory.createCallExpression(createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement), 
26990         /*typeArguments*/ undefined, argumentsList), location);
26991     }
26992     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
26993     // Utilities
26994     function createForOfBindingStatement(factory, node, boundValue) {
26995         if (ts.isVariableDeclarationList(node)) {
26996             var firstDeclaration = ts.first(node.declarations);
26997             var updatedDeclaration = factory.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
26998             /*exclamationToken*/ undefined, 
26999             /*type*/ undefined, boundValue);
27000             return ts.setTextRange(factory.createVariableStatement(
27001             /*modifiers*/ undefined, factory.updateVariableDeclarationList(node, [updatedDeclaration])), 
27002             /*location*/ node);
27003         }
27004         else {
27005             var updatedExpression = ts.setTextRange(factory.createAssignment(node, boundValue), /*location*/ node);
27006             return ts.setTextRange(factory.createExpressionStatement(updatedExpression), /*location*/ node);
27007         }
27008     }
27009     ts.createForOfBindingStatement = createForOfBindingStatement;
27010     function insertLeadingStatement(factory, dest, source) {
27011         if (ts.isBlock(dest)) {
27012             return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
27013         }
27014         else {
27015             return factory.createBlock(factory.createNodeArray([dest, source]), /*multiLine*/ true);
27016         }
27017     }
27018     ts.insertLeadingStatement = insertLeadingStatement;
27019     function createExpressionFromEntityName(factory, node) {
27020         if (ts.isQualifiedName(node)) {
27021             var left = createExpressionFromEntityName(factory, node.left);
27022             // TODO(rbuckton): Does this need to be parented?
27023             var right = ts.setParent(ts.setTextRange(factory.cloneNode(node.right), node.right), node.right.parent);
27024             return ts.setTextRange(factory.createPropertyAccessExpression(left, right), node);
27025         }
27026         else {
27027             // TODO(rbuckton): Does this need to be parented?
27028             return ts.setParent(ts.setTextRange(factory.cloneNode(node), node), node.parent);
27029         }
27030     }
27031     ts.createExpressionFromEntityName = createExpressionFromEntityName;
27032     function createExpressionForPropertyName(factory, memberName) {
27033         if (ts.isIdentifier(memberName)) {
27034             return factory.createStringLiteralFromNode(memberName);
27035         }
27036         else if (ts.isComputedPropertyName(memberName)) {
27037             // TODO(rbuckton): Does this need to be parented?
27038             return ts.setParent(ts.setTextRange(factory.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent);
27039         }
27040         else {
27041             // TODO(rbuckton): Does this need to be parented?
27042             return ts.setParent(ts.setTextRange(factory.cloneNode(memberName), memberName), memberName.parent);
27043         }
27044     }
27045     ts.createExpressionForPropertyName = createExpressionForPropertyName;
27046     function createExpressionForAccessorDeclaration(factory, properties, property, receiver, multiLine) {
27047         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
27048         if (property === firstAccessor) {
27049             return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({
27050                 enumerable: factory.createFalse(),
27051                 configurable: true,
27052                 get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, 
27053                 /*asteriskToken*/ undefined, 
27054                 /*name*/ undefined, 
27055                 /*typeParameters*/ undefined, getAccessor.parameters, 
27056                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
27057                 ), getAccessor), getAccessor),
27058                 set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, 
27059                 /*asteriskToken*/ undefined, 
27060                 /*name*/ undefined, 
27061                 /*typeParameters*/ undefined, setAccessor.parameters, 
27062                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
27063                 ), setAccessor), setAccessor)
27064             }, !multiLine)), firstAccessor);
27065         }
27066         return undefined;
27067     }
27068     function createExpressionForPropertyAssignment(factory, property, receiver) {
27069         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), property.initializer), property), property);
27070     }
27071     function createExpressionForShorthandPropertyAssignment(factory, property, receiver) {
27072         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), factory.cloneNode(property.name)), 
27073         /*location*/ property), 
27074         /*original*/ property);
27075     }
27076     function createExpressionForMethodDeclaration(factory, method, receiver) {
27077         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken, 
27078         /*name*/ undefined, 
27079         /*typeParameters*/ undefined, method.parameters, 
27080         /*type*/ undefined, method.body // TODO: GH#18217
27081         ), 
27082         /*location*/ method), 
27083         /*original*/ method)), 
27084         /*location*/ method), 
27085         /*original*/ method);
27086     }
27087     function createExpressionForObjectLiteralElementLike(factory, node, property, receiver) {
27088         if (property.name && ts.isPrivateIdentifier(property.name)) {
27089             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
27090         }
27091         switch (property.kind) {
27092             case 167 /* GetAccessor */:
27093             case 168 /* SetAccessor */:
27094                 return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine);
27095             case 288 /* PropertyAssignment */:
27096                 return createExpressionForPropertyAssignment(factory, property, receiver);
27097             case 289 /* ShorthandPropertyAssignment */:
27098                 return createExpressionForShorthandPropertyAssignment(factory, property, receiver);
27099             case 165 /* MethodDeclaration */:
27100                 return createExpressionForMethodDeclaration(factory, property, receiver);
27101         }
27102     }
27103     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
27104     /**
27105      * Gets whether an identifier should only be referred to by its internal name.
27106      */
27107     function isInternalName(node) {
27108         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
27109     }
27110     ts.isInternalName = isInternalName;
27111     /**
27112      * Gets whether an identifier should only be referred to by its local name.
27113      */
27114     function isLocalName(node) {
27115         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
27116     }
27117     ts.isLocalName = isLocalName;
27118     /**
27119      * Gets whether an identifier should only be referred to by its export representation if the
27120      * name points to an exported symbol.
27121      */
27122     function isExportName(node) {
27123         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
27124     }
27125     ts.isExportName = isExportName;
27126     function isUseStrictPrologue(node) {
27127         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
27128     }
27129     function findUseStrictPrologue(statements) {
27130         for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
27131             var statement = statements_1[_i];
27132             if (ts.isPrologueDirective(statement)) {
27133                 if (isUseStrictPrologue(statement)) {
27134                     return statement;
27135                 }
27136             }
27137             else {
27138                 break;
27139             }
27140         }
27141         return undefined;
27142     }
27143     ts.findUseStrictPrologue = findUseStrictPrologue;
27144     function startsWithUseStrict(statements) {
27145         var firstStatement = ts.firstOrUndefined(statements);
27146         return firstStatement !== undefined
27147             && ts.isPrologueDirective(firstStatement)
27148             && isUseStrictPrologue(firstStatement);
27149     }
27150     ts.startsWithUseStrict = startsWithUseStrict;
27151     function isCommaSequence(node) {
27152         return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
27153             node.kind === 337 /* CommaListExpression */;
27154     }
27155     ts.isCommaSequence = isCommaSequence;
27156     function isOuterExpression(node, kinds) {
27157         if (kinds === void 0) { kinds = 15 /* All */; }
27158         switch (node.kind) {
27159             case 207 /* ParenthesizedExpression */:
27160                 return (kinds & 1 /* Parentheses */) !== 0;
27161             case 206 /* TypeAssertionExpression */:
27162             case 224 /* AsExpression */:
27163                 return (kinds & 2 /* TypeAssertions */) !== 0;
27164             case 225 /* NonNullExpression */:
27165                 return (kinds & 4 /* NonNullAssertions */) !== 0;
27166             case 336 /* PartiallyEmittedExpression */:
27167                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
27168         }
27169         return false;
27170     }
27171     ts.isOuterExpression = isOuterExpression;
27172     function skipOuterExpressions(node, kinds) {
27173         if (kinds === void 0) { kinds = 15 /* All */; }
27174         while (isOuterExpression(node, kinds)) {
27175             node = node.expression;
27176         }
27177         return node;
27178     }
27179     ts.skipOuterExpressions = skipOuterExpressions;
27180     function skipAssertions(node) {
27181         return skipOuterExpressions(node, 6 /* Assertions */);
27182     }
27183     ts.skipAssertions = skipAssertions;
27184     function startOnNewLine(node) {
27185         return ts.setStartsOnNewLine(node, /*newLine*/ true);
27186     }
27187     ts.startOnNewLine = startOnNewLine;
27188     function getExternalHelpersModuleName(node) {
27189         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
27190         var emitNode = parseNode && parseNode.emitNode;
27191         return emitNode && emitNode.externalHelpersModuleName;
27192     }
27193     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
27194     function hasRecordedExternalHelpers(sourceFile) {
27195         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
27196         var emitNode = parseNode && parseNode.emitNode;
27197         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
27198     }
27199     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
27200     function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
27201         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
27202             var namedBindings = void 0;
27203             var moduleKind = ts.getEmitModuleKind(compilerOptions);
27204             if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
27205                 // use named imports
27206                 var helpers = ts.getEmitHelpers(sourceFile);
27207                 if (helpers) {
27208                     var helperNames = [];
27209                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
27210                         var helper = helpers_3[_i];
27211                         if (!helper.scoped) {
27212                             var importName = helper.importName;
27213                             if (importName) {
27214                                 ts.pushIfUnique(helperNames, importName);
27215                             }
27216                         }
27217                     }
27218                     if (ts.some(helperNames)) {
27219                         helperNames.sort(ts.compareStringsCaseSensitive);
27220                         // Alias the imports if the names are used somewhere in the file.
27221                         // NOTE: We don't need to care about global import collisions as this is a module.
27222                         namedBindings = nodeFactory.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
27223                             ? nodeFactory.createImportSpecifier(/*propertyName*/ undefined, nodeFactory.createIdentifier(name))
27224                             : nodeFactory.createImportSpecifier(nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name)); }));
27225                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
27226                         var emitNode = ts.getOrCreateEmitNode(parseNode);
27227                         emitNode.externalHelpers = true;
27228                     }
27229                 }
27230             }
27231             else {
27232                 // use a namespace import
27233                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
27234                 if (externalHelpersModuleName) {
27235                     namedBindings = nodeFactory.createNamespaceImport(externalHelpersModuleName);
27236                 }
27237             }
27238             if (namedBindings) {
27239                 var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(
27240                 /*decorators*/ undefined, 
27241                 /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText));
27242                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
27243                 return externalHelpersImportDeclaration;
27244             }
27245         }
27246     }
27247     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
27248     function getOrCreateExternalHelpersModuleNameIfNeeded(factory, node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
27249         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
27250             var externalHelpersModuleName = getExternalHelpersModuleName(node);
27251             if (externalHelpersModuleName) {
27252                 return externalHelpersModuleName;
27253             }
27254             var moduleKind = ts.getEmitModuleKind(compilerOptions);
27255             var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
27256                 && moduleKind !== ts.ModuleKind.System
27257                 && moduleKind < ts.ModuleKind.ES2015;
27258             if (!create) {
27259                 var helpers = ts.getEmitHelpers(node);
27260                 if (helpers) {
27261                     for (var _i = 0, helpers_4 = helpers; _i < helpers_4.length; _i++) {
27262                         var helper = helpers_4[_i];
27263                         if (!helper.scoped) {
27264                             create = true;
27265                             break;
27266                         }
27267                     }
27268                 }
27269             }
27270             if (create) {
27271                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
27272                 var emitNode = ts.getOrCreateEmitNode(parseNode);
27273                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory.createUniqueName(ts.externalHelpersModuleNameText));
27274             }
27275         }
27276     }
27277     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
27278     /**
27279      * Get the name of that target module from an import or export declaration
27280      */
27281     function getLocalNameForExternalImport(factory, node, sourceFile) {
27282         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
27283         if (namespaceDeclaration && !ts.isDefaultImport(node) && !ts.isExportNamespaceAsDefaultDeclaration(node)) {
27284             var name = namespaceDeclaration.name;
27285             return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
27286         }
27287         if (node.kind === 261 /* ImportDeclaration */ && node.importClause) {
27288             return factory.getGeneratedNameForNode(node);
27289         }
27290         if (node.kind === 267 /* ExportDeclaration */ && node.moduleSpecifier) {
27291             return factory.getGeneratedNameForNode(node);
27292         }
27293         return undefined;
27294     }
27295     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
27296     /**
27297      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
27298      * The emitted output name can be different from the input if:
27299      *  1. The module has a /// <amd-module name="<new name>" />
27300      *  2. --out or --outFile is used, making the name relative to the rootDir
27301      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
27302      * Otherwise, a new StringLiteral node representing the module name will be returned.
27303      */
27304     function getExternalModuleNameLiteral(factory, importNode, sourceFile, host, resolver, compilerOptions) {
27305         var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
27306         if (moduleName.kind === 10 /* StringLiteral */) {
27307             return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions)
27308                 || tryRenameExternalModule(factory, moduleName, sourceFile)
27309                 || factory.cloneNode(moduleName);
27310         }
27311         return undefined;
27312     }
27313     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
27314     /**
27315      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
27316      * Here we check if alternative name was provided for a given moduleName and return it if possible.
27317      */
27318     function tryRenameExternalModule(factory, moduleName, sourceFile) {
27319         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
27320         return rename && factory.createStringLiteral(rename);
27321     }
27322     /**
27323      * Get the name of a module as should be written in the emitted output.
27324      * The emitted output name can be different from the input if:
27325      *  1. The module has a /// <amd-module name="<new name>" />
27326      *  2. --out or --outFile is used, making the name relative to the rootDir
27327      * Otherwise, a new StringLiteral node representing the module name will be returned.
27328      */
27329     function tryGetModuleNameFromFile(factory, file, host, options) {
27330         if (!file) {
27331             return undefined;
27332         }
27333         if (file.moduleName) {
27334             return factory.createStringLiteral(file.moduleName);
27335         }
27336         if (!file.isDeclarationFile && ts.outFile(options)) {
27337             return factory.createStringLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
27338         }
27339         return undefined;
27340     }
27341     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
27342     function tryGetModuleNameFromDeclaration(declaration, host, factory, resolver, compilerOptions) {
27343         return tryGetModuleNameFromFile(factory, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
27344     }
27345     /**
27346      * Gets the initializer of an BindingOrAssignmentElement.
27347      */
27348     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
27349         if (ts.isDeclarationBindingElement(bindingElement)) {
27350             // `1` in `let { a = 1 } = ...`
27351             // `1` in `let { a: b = 1 } = ...`
27352             // `1` in `let { a: {b} = 1 } = ...`
27353             // `1` in `let { a: [b] = 1 } = ...`
27354             // `1` in `let [a = 1] = ...`
27355             // `1` in `let [{a} = 1] = ...`
27356             // `1` in `let [[a] = 1] = ...`
27357             return bindingElement.initializer;
27358         }
27359         if (ts.isPropertyAssignment(bindingElement)) {
27360             // `1` in `({ a: b = 1 } = ...)`
27361             // `1` in `({ a: {b} = 1 } = ...)`
27362             // `1` in `({ a: [b] = 1 } = ...)`
27363             var initializer = bindingElement.initializer;
27364             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
27365                 ? initializer.right
27366                 : undefined;
27367         }
27368         if (ts.isShorthandPropertyAssignment(bindingElement)) {
27369             // `1` in `({ a = 1 } = ...)`
27370             return bindingElement.objectAssignmentInitializer;
27371         }
27372         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
27373             // `1` in `[a = 1] = ...`
27374             // `1` in `[{a} = 1] = ...`
27375             // `1` in `[[a] = 1] = ...`
27376             return bindingElement.right;
27377         }
27378         if (ts.isSpreadElement(bindingElement)) {
27379             // Recovery consistent with existing emit.
27380             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
27381         }
27382     }
27383     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
27384     /**
27385      * Gets the name of an BindingOrAssignmentElement.
27386      */
27387     function getTargetOfBindingOrAssignmentElement(bindingElement) {
27388         if (ts.isDeclarationBindingElement(bindingElement)) {
27389             // `a` in `let { a } = ...`
27390             // `a` in `let { a = 1 } = ...`
27391             // `b` in `let { a: b } = ...`
27392             // `b` in `let { a: b = 1 } = ...`
27393             // `a` in `let { ...a } = ...`
27394             // `{b}` in `let { a: {b} } = ...`
27395             // `{b}` in `let { a: {b} = 1 } = ...`
27396             // `[b]` in `let { a: [b] } = ...`
27397             // `[b]` in `let { a: [b] = 1 } = ...`
27398             // `a` in `let [a] = ...`
27399             // `a` in `let [a = 1] = ...`
27400             // `a` in `let [...a] = ...`
27401             // `{a}` in `let [{a}] = ...`
27402             // `{a}` in `let [{a} = 1] = ...`
27403             // `[a]` in `let [[a]] = ...`
27404             // `[a]` in `let [[a] = 1] = ...`
27405             return bindingElement.name;
27406         }
27407         if (ts.isObjectLiteralElementLike(bindingElement)) {
27408             switch (bindingElement.kind) {
27409                 case 288 /* PropertyAssignment */:
27410                     // `b` in `({ a: b } = ...)`
27411                     // `b` in `({ a: b = 1 } = ...)`
27412                     // `{b}` in `({ a: {b} } = ...)`
27413                     // `{b}` in `({ a: {b} = 1 } = ...)`
27414                     // `[b]` in `({ a: [b] } = ...)`
27415                     // `[b]` in `({ a: [b] = 1 } = ...)`
27416                     // `b.c` in `({ a: b.c } = ...)`
27417                     // `b.c` in `({ a: b.c = 1 } = ...)`
27418                     // `b[0]` in `({ a: b[0] } = ...)`
27419                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
27420                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
27421                 case 289 /* ShorthandPropertyAssignment */:
27422                     // `a` in `({ a } = ...)`
27423                     // `a` in `({ a = 1 } = ...)`
27424                     return bindingElement.name;
27425                 case 290 /* SpreadAssignment */:
27426                     // `a` in `({ ...a } = ...)`
27427                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
27428             }
27429             // no target
27430             return undefined;
27431         }
27432         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
27433             // `a` in `[a = 1] = ...`
27434             // `{a}` in `[{a} = 1] = ...`
27435             // `[a]` in `[[a] = 1] = ...`
27436             // `a.b` in `[a.b = 1] = ...`
27437             // `a[0]` in `[a[0] = 1] = ...`
27438             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
27439         }
27440         if (ts.isSpreadElement(bindingElement)) {
27441             // `a` in `[...a] = ...`
27442             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
27443         }
27444         // `a` in `[a] = ...`
27445         // `{a}` in `[{a}] = ...`
27446         // `[a]` in `[[a]] = ...`
27447         // `a.b` in `[a.b] = ...`
27448         // `a[0]` in `[a[0]] = ...`
27449         return bindingElement;
27450     }
27451     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
27452     /**
27453      * Determines whether an BindingOrAssignmentElement is a rest element.
27454      */
27455     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
27456         switch (bindingElement.kind) {
27457             case 160 /* Parameter */:
27458             case 198 /* BindingElement */:
27459                 // `...` in `let [...a] = ...`
27460                 return bindingElement.dotDotDotToken;
27461             case 220 /* SpreadElement */:
27462             case 290 /* SpreadAssignment */:
27463                 // `...` in `[...a] = ...`
27464                 return bindingElement;
27465         }
27466         return undefined;
27467     }
27468     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
27469     /**
27470      * Gets the property name of a BindingOrAssignmentElement
27471      */
27472     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
27473         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
27474         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
27475         return propertyName;
27476     }
27477     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
27478     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
27479         switch (bindingElement.kind) {
27480             case 198 /* BindingElement */:
27481                 // `a` in `let { a: b } = ...`
27482                 // `[a]` in `let { [a]: b } = ...`
27483                 // `"a"` in `let { "a": b } = ...`
27484                 // `1` in `let { 1: b } = ...`
27485                 if (bindingElement.propertyName) {
27486                     var propertyName = bindingElement.propertyName;
27487                     if (ts.isPrivateIdentifier(propertyName)) {
27488                         return ts.Debug.failBadSyntaxKind(propertyName);
27489                     }
27490                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
27491                         ? propertyName.expression
27492                         : propertyName;
27493                 }
27494                 break;
27495             case 288 /* PropertyAssignment */:
27496                 // `a` in `({ a: b } = ...)`
27497                 // `[a]` in `({ [a]: b } = ...)`
27498                 // `"a"` in `({ "a": b } = ...)`
27499                 // `1` in `({ 1: b } = ...)`
27500                 if (bindingElement.name) {
27501                     var propertyName = bindingElement.name;
27502                     if (ts.isPrivateIdentifier(propertyName)) {
27503                         return ts.Debug.failBadSyntaxKind(propertyName);
27504                     }
27505                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
27506                         ? propertyName.expression
27507                         : propertyName;
27508                 }
27509                 break;
27510             case 290 /* SpreadAssignment */:
27511                 // `a` in `({ ...a } = ...)`
27512                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
27513                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
27514                 }
27515                 return bindingElement.name;
27516         }
27517         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
27518         if (target && ts.isPropertyName(target)) {
27519             return target;
27520         }
27521     }
27522     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
27523     function isStringOrNumericLiteral(node) {
27524         var kind = node.kind;
27525         return kind === 10 /* StringLiteral */
27526             || kind === 8 /* NumericLiteral */;
27527     }
27528     /**
27529      * Gets the elements of a BindingOrAssignmentPattern
27530      */
27531     function getElementsOfBindingOrAssignmentPattern(name) {
27532         switch (name.kind) {
27533             case 196 /* ObjectBindingPattern */:
27534             case 197 /* ArrayBindingPattern */:
27535             case 199 /* ArrayLiteralExpression */:
27536                 // `a` in `{a}`
27537                 // `a` in `[a]`
27538                 return name.elements;
27539             case 200 /* ObjectLiteralExpression */:
27540                 // `a` in `{a}`
27541                 return name.properties;
27542         }
27543     }
27544     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
27545     /* @internal */
27546     function getJSDocTypeAliasName(fullName) {
27547         if (fullName) {
27548             var rightNode = fullName;
27549             while (true) {
27550                 if (ts.isIdentifier(rightNode) || !rightNode.body) {
27551                     return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
27552                 }
27553                 rightNode = rightNode.body;
27554             }
27555         }
27556     }
27557     ts.getJSDocTypeAliasName = getJSDocTypeAliasName;
27558     function canHaveModifiers(node) {
27559         var kind = node.kind;
27560         return kind === 160 /* Parameter */
27561             || kind === 162 /* PropertySignature */
27562             || kind === 163 /* PropertyDeclaration */
27563             || kind === 164 /* MethodSignature */
27564             || kind === 165 /* MethodDeclaration */
27565             || kind === 166 /* Constructor */
27566             || kind === 167 /* GetAccessor */
27567             || kind === 168 /* SetAccessor */
27568             || kind === 171 /* IndexSignature */
27569             || kind === 208 /* FunctionExpression */
27570             || kind === 209 /* ArrowFunction */
27571             || kind === 221 /* ClassExpression */
27572             || kind === 232 /* VariableStatement */
27573             || kind === 251 /* FunctionDeclaration */
27574             || kind === 252 /* ClassDeclaration */
27575             || kind === 253 /* InterfaceDeclaration */
27576             || kind === 254 /* TypeAliasDeclaration */
27577             || kind === 255 /* EnumDeclaration */
27578             || kind === 256 /* ModuleDeclaration */
27579             || kind === 260 /* ImportEqualsDeclaration */
27580             || kind === 261 /* ImportDeclaration */
27581             || kind === 266 /* ExportAssignment */
27582             || kind === 267 /* ExportDeclaration */;
27583     }
27584     ts.canHaveModifiers = canHaveModifiers;
27585     /* @internal */
27586     function isExportModifier(node) {
27587         return node.kind === 92 /* ExportKeyword */;
27588     }
27589     ts.isExportModifier = isExportModifier;
27590     /* @internal */
27591     function isAsyncModifier(node) {
27592         return node.kind === 129 /* AsyncKeyword */;
27593     }
27594     ts.isAsyncModifier = isAsyncModifier;
27595     /* @internal */
27596     function isStaticModifier(node) {
27597         return node.kind === 123 /* StaticKeyword */;
27598     }
27599     ts.isStaticModifier = isStaticModifier;
27600 })(ts || (ts = {}));
27601 var ts;
27602 (function (ts) {
27603     function setTextRange(range, location) {
27604         return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range;
27605     }
27606     ts.setTextRange = setTextRange;
27607 })(ts || (ts = {}));
27608 var ts;
27609 (function (ts) {
27610     var SignatureFlags;
27611     (function (SignatureFlags) {
27612         SignatureFlags[SignatureFlags["None"] = 0] = "None";
27613         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
27614         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
27615         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
27616         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
27617         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
27618     })(SignatureFlags || (SignatureFlags = {}));
27619     var SpeculationKind;
27620     (function (SpeculationKind) {
27621         SpeculationKind[SpeculationKind["TryParse"] = 0] = "TryParse";
27622         SpeculationKind[SpeculationKind["Lookahead"] = 1] = "Lookahead";
27623         SpeculationKind[SpeculationKind["Reparse"] = 2] = "Reparse";
27624     })(SpeculationKind || (SpeculationKind = {}));
27625     var NodeConstructor;
27626     var TokenConstructor;
27627     var IdentifierConstructor;
27628     var PrivateIdentifierConstructor;
27629     var SourceFileConstructor;
27630     /**
27631      * NOTE: You should not use this, it is only exported to support `createNode` in `~/src/compat/deprecations.ts`.
27632      */
27633     /* @internal */
27634     ts.parseBaseNodeFactory = {
27635         createBaseSourceFileNode: function (kind) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, -1, -1); },
27636         createBaseIdentifierNode: function (kind) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, -1, -1); },
27637         createBasePrivateIdentifierNode: function (kind) { return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1); },
27638         createBaseTokenNode: function (kind) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, -1, -1); },
27639         createBaseNode: function (kind) { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, -1, -1); },
27640     };
27641     /* @internal */
27642     ts.parseNodeFactory = ts.createNodeFactory(1 /* NoParenthesizerRules */, ts.parseBaseNodeFactory);
27643     function visitNode(cbNode, node) {
27644         return node && cbNode(node);
27645     }
27646     function visitNodes(cbNode, cbNodes, nodes) {
27647         if (nodes) {
27648             if (cbNodes) {
27649                 return cbNodes(nodes);
27650             }
27651             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
27652                 var node = nodes_1[_i];
27653                 var result = cbNode(node);
27654                 if (result) {
27655                     return result;
27656                 }
27657             }
27658         }
27659     }
27660     /*@internal*/
27661     function isJSDocLikeText(text, start) {
27662         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
27663             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
27664             text.charCodeAt(start + 3) !== 47 /* slash */;
27665     }
27666     ts.isJSDocLikeText = isJSDocLikeText;
27667     /**
27668      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
27669      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
27670      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
27671      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
27672      *
27673      * @param node a given node to visit its children
27674      * @param cbNode a callback to be invoked for all child nodes
27675      * @param cbNodes a callback to be invoked for embedded array
27676      *
27677      * @remarks `forEachChild` must visit the children of a node in the order
27678      * that they appear in the source code. The language service depends on this property to locate nodes by position.
27679      */
27680     function forEachChild(node, cbNode, cbNodes) {
27681         if (!node || node.kind <= 156 /* LastToken */) {
27682             return;
27683         }
27684         switch (node.kind) {
27685             case 157 /* QualifiedName */:
27686                 return visitNode(cbNode, node.left) ||
27687                     visitNode(cbNode, node.right);
27688             case 159 /* TypeParameter */:
27689                 return visitNode(cbNode, node.name) ||
27690                     visitNode(cbNode, node.constraint) ||
27691                     visitNode(cbNode, node.default) ||
27692                     visitNode(cbNode, node.expression);
27693             case 289 /* ShorthandPropertyAssignment */:
27694                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27695                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27696                     visitNode(cbNode, node.name) ||
27697                     visitNode(cbNode, node.questionToken) ||
27698                     visitNode(cbNode, node.exclamationToken) ||
27699                     visitNode(cbNode, node.equalsToken) ||
27700                     visitNode(cbNode, node.objectAssignmentInitializer);
27701             case 290 /* SpreadAssignment */:
27702                 return visitNode(cbNode, node.expression);
27703             case 160 /* Parameter */:
27704                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27705                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27706                     visitNode(cbNode, node.dotDotDotToken) ||
27707                     visitNode(cbNode, node.name) ||
27708                     visitNode(cbNode, node.questionToken) ||
27709                     visitNode(cbNode, node.type) ||
27710                     visitNode(cbNode, node.initializer);
27711             case 163 /* PropertyDeclaration */:
27712                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27713                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27714                     visitNode(cbNode, node.name) ||
27715                     visitNode(cbNode, node.questionToken) ||
27716                     visitNode(cbNode, node.exclamationToken) ||
27717                     visitNode(cbNode, node.type) ||
27718                     visitNode(cbNode, node.initializer);
27719             case 162 /* PropertySignature */:
27720                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27721                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27722                     visitNode(cbNode, node.name) ||
27723                     visitNode(cbNode, node.questionToken) ||
27724                     visitNode(cbNode, node.type) ||
27725                     visitNode(cbNode, node.initializer);
27726             case 288 /* PropertyAssignment */:
27727                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27728                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27729                     visitNode(cbNode, node.name) ||
27730                     visitNode(cbNode, node.questionToken) ||
27731                     visitNode(cbNode, node.initializer);
27732             case 249 /* VariableDeclaration */:
27733                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27734                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27735                     visitNode(cbNode, node.name) ||
27736                     visitNode(cbNode, node.exclamationToken) ||
27737                     visitNode(cbNode, node.type) ||
27738                     visitNode(cbNode, node.initializer);
27739             case 198 /* BindingElement */:
27740                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27741                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27742                     visitNode(cbNode, node.dotDotDotToken) ||
27743                     visitNode(cbNode, node.propertyName) ||
27744                     visitNode(cbNode, node.name) ||
27745                     visitNode(cbNode, node.initializer);
27746             case 174 /* FunctionType */:
27747             case 175 /* ConstructorType */:
27748             case 169 /* CallSignature */:
27749             case 170 /* ConstructSignature */:
27750             case 171 /* IndexSignature */:
27751                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27752                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27753                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27754                     visitNodes(cbNode, cbNodes, node.parameters) ||
27755                     visitNode(cbNode, node.type);
27756             case 165 /* MethodDeclaration */:
27757             case 164 /* MethodSignature */:
27758             case 166 /* Constructor */:
27759             case 167 /* GetAccessor */:
27760             case 168 /* SetAccessor */:
27761             case 208 /* FunctionExpression */:
27762             case 251 /* FunctionDeclaration */:
27763             case 209 /* ArrowFunction */:
27764                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27765                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27766                     visitNode(cbNode, node.asteriskToken) ||
27767                     visitNode(cbNode, node.name) ||
27768                     visitNode(cbNode, node.questionToken) ||
27769                     visitNode(cbNode, node.exclamationToken) ||
27770                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27771                     visitNodes(cbNode, cbNodes, node.parameters) ||
27772                     visitNode(cbNode, node.type) ||
27773                     visitNode(cbNode, node.equalsGreaterThanToken) ||
27774                     visitNode(cbNode, node.body);
27775             case 173 /* TypeReference */:
27776                 return visitNode(cbNode, node.typeName) ||
27777                     visitNodes(cbNode, cbNodes, node.typeArguments);
27778             case 172 /* TypePredicate */:
27779                 return visitNode(cbNode, node.assertsModifier) ||
27780                     visitNode(cbNode, node.parameterName) ||
27781                     visitNode(cbNode, node.type);
27782             case 176 /* TypeQuery */:
27783                 return visitNode(cbNode, node.exprName);
27784             case 177 /* TypeLiteral */:
27785                 return visitNodes(cbNode, cbNodes, node.members);
27786             case 178 /* ArrayType */:
27787                 return visitNode(cbNode, node.elementType);
27788             case 179 /* TupleType */:
27789                 return visitNodes(cbNode, cbNodes, node.elements);
27790             case 182 /* UnionType */:
27791             case 183 /* IntersectionType */:
27792                 return visitNodes(cbNode, cbNodes, node.types);
27793             case 184 /* ConditionalType */:
27794                 return visitNode(cbNode, node.checkType) ||
27795                     visitNode(cbNode, node.extendsType) ||
27796                     visitNode(cbNode, node.trueType) ||
27797                     visitNode(cbNode, node.falseType);
27798             case 185 /* InferType */:
27799                 return visitNode(cbNode, node.typeParameter);
27800             case 195 /* ImportType */:
27801                 return visitNode(cbNode, node.argument) ||
27802                     visitNode(cbNode, node.qualifier) ||
27803                     visitNodes(cbNode, cbNodes, node.typeArguments);
27804             case 186 /* ParenthesizedType */:
27805             case 188 /* TypeOperator */:
27806                 return visitNode(cbNode, node.type);
27807             case 189 /* IndexedAccessType */:
27808                 return visitNode(cbNode, node.objectType) ||
27809                     visitNode(cbNode, node.indexType);
27810             case 190 /* MappedType */:
27811                 return visitNode(cbNode, node.readonlyToken) ||
27812                     visitNode(cbNode, node.typeParameter) ||
27813                     visitNode(cbNode, node.nameType) ||
27814                     visitNode(cbNode, node.questionToken) ||
27815                     visitNode(cbNode, node.type);
27816             case 191 /* LiteralType */:
27817                 return visitNode(cbNode, node.literal);
27818             case 192 /* NamedTupleMember */:
27819                 return visitNode(cbNode, node.dotDotDotToken) ||
27820                     visitNode(cbNode, node.name) ||
27821                     visitNode(cbNode, node.questionToken) ||
27822                     visitNode(cbNode, node.type);
27823             case 196 /* ObjectBindingPattern */:
27824             case 197 /* ArrayBindingPattern */:
27825                 return visitNodes(cbNode, cbNodes, node.elements);
27826             case 199 /* ArrayLiteralExpression */:
27827                 return visitNodes(cbNode, cbNodes, node.elements);
27828             case 200 /* ObjectLiteralExpression */:
27829                 return visitNodes(cbNode, cbNodes, node.properties);
27830             case 201 /* PropertyAccessExpression */:
27831                 return visitNode(cbNode, node.expression) ||
27832                     visitNode(cbNode, node.questionDotToken) ||
27833                     visitNode(cbNode, node.name);
27834             case 202 /* ElementAccessExpression */:
27835                 return visitNode(cbNode, node.expression) ||
27836                     visitNode(cbNode, node.questionDotToken) ||
27837                     visitNode(cbNode, node.argumentExpression);
27838             case 203 /* CallExpression */:
27839             case 204 /* NewExpression */:
27840                 return visitNode(cbNode, node.expression) ||
27841                     visitNode(cbNode, node.questionDotToken) ||
27842                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
27843                     visitNodes(cbNode, cbNodes, node.arguments);
27844             case 205 /* TaggedTemplateExpression */:
27845                 return visitNode(cbNode, node.tag) ||
27846                     visitNode(cbNode, node.questionDotToken) ||
27847                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
27848                     visitNode(cbNode, node.template);
27849             case 206 /* TypeAssertionExpression */:
27850                 return visitNode(cbNode, node.type) ||
27851                     visitNode(cbNode, node.expression);
27852             case 207 /* ParenthesizedExpression */:
27853                 return visitNode(cbNode, node.expression);
27854             case 210 /* DeleteExpression */:
27855                 return visitNode(cbNode, node.expression);
27856             case 211 /* TypeOfExpression */:
27857                 return visitNode(cbNode, node.expression);
27858             case 212 /* VoidExpression */:
27859                 return visitNode(cbNode, node.expression);
27860             case 214 /* PrefixUnaryExpression */:
27861                 return visitNode(cbNode, node.operand);
27862             case 219 /* YieldExpression */:
27863                 return visitNode(cbNode, node.asteriskToken) ||
27864                     visitNode(cbNode, node.expression);
27865             case 213 /* AwaitExpression */:
27866                 return visitNode(cbNode, node.expression);
27867             case 215 /* PostfixUnaryExpression */:
27868                 return visitNode(cbNode, node.operand);
27869             case 216 /* BinaryExpression */:
27870                 return visitNode(cbNode, node.left) ||
27871                     visitNode(cbNode, node.operatorToken) ||
27872                     visitNode(cbNode, node.right);
27873             case 224 /* AsExpression */:
27874                 return visitNode(cbNode, node.expression) ||
27875                     visitNode(cbNode, node.type);
27876             case 225 /* NonNullExpression */:
27877                 return visitNode(cbNode, node.expression);
27878             case 226 /* MetaProperty */:
27879                 return visitNode(cbNode, node.name);
27880             case 217 /* ConditionalExpression */:
27881                 return visitNode(cbNode, node.condition) ||
27882                     visitNode(cbNode, node.questionToken) ||
27883                     visitNode(cbNode, node.whenTrue) ||
27884                     visitNode(cbNode, node.colonToken) ||
27885                     visitNode(cbNode, node.whenFalse);
27886             case 220 /* SpreadElement */:
27887                 return visitNode(cbNode, node.expression);
27888             case 230 /* Block */:
27889             case 257 /* ModuleBlock */:
27890                 return visitNodes(cbNode, cbNodes, node.statements);
27891             case 297 /* SourceFile */:
27892                 return visitNodes(cbNode, cbNodes, node.statements) ||
27893                     visitNode(cbNode, node.endOfFileToken);
27894             case 232 /* VariableStatement */:
27895                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27896                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27897                     visitNode(cbNode, node.declarationList);
27898             case 250 /* VariableDeclarationList */:
27899                 return visitNodes(cbNode, cbNodes, node.declarations);
27900             case 233 /* ExpressionStatement */:
27901                 return visitNode(cbNode, node.expression);
27902             case 234 /* IfStatement */:
27903                 return visitNode(cbNode, node.expression) ||
27904                     visitNode(cbNode, node.thenStatement) ||
27905                     visitNode(cbNode, node.elseStatement);
27906             case 235 /* DoStatement */:
27907                 return visitNode(cbNode, node.statement) ||
27908                     visitNode(cbNode, node.expression);
27909             case 236 /* WhileStatement */:
27910                 return visitNode(cbNode, node.expression) ||
27911                     visitNode(cbNode, node.statement);
27912             case 237 /* ForStatement */:
27913                 return visitNode(cbNode, node.initializer) ||
27914                     visitNode(cbNode, node.condition) ||
27915                     visitNode(cbNode, node.incrementor) ||
27916                     visitNode(cbNode, node.statement);
27917             case 238 /* ForInStatement */:
27918                 return visitNode(cbNode, node.initializer) ||
27919                     visitNode(cbNode, node.expression) ||
27920                     visitNode(cbNode, node.statement);
27921             case 239 /* ForOfStatement */:
27922                 return visitNode(cbNode, node.awaitModifier) ||
27923                     visitNode(cbNode, node.initializer) ||
27924                     visitNode(cbNode, node.expression) ||
27925                     visitNode(cbNode, node.statement);
27926             case 240 /* ContinueStatement */:
27927             case 241 /* BreakStatement */:
27928                 return visitNode(cbNode, node.label);
27929             case 242 /* ReturnStatement */:
27930                 return visitNode(cbNode, node.expression);
27931             case 243 /* WithStatement */:
27932                 return visitNode(cbNode, node.expression) ||
27933                     visitNode(cbNode, node.statement);
27934             case 244 /* SwitchStatement */:
27935                 return visitNode(cbNode, node.expression) ||
27936                     visitNode(cbNode, node.caseBlock);
27937             case 258 /* CaseBlock */:
27938                 return visitNodes(cbNode, cbNodes, node.clauses);
27939             case 284 /* CaseClause */:
27940                 return visitNode(cbNode, node.expression) ||
27941                     visitNodes(cbNode, cbNodes, node.statements);
27942             case 285 /* DefaultClause */:
27943                 return visitNodes(cbNode, cbNodes, node.statements);
27944             case 245 /* LabeledStatement */:
27945                 return visitNode(cbNode, node.label) ||
27946                     visitNode(cbNode, node.statement);
27947             case 246 /* ThrowStatement */:
27948                 return visitNode(cbNode, node.expression);
27949             case 247 /* TryStatement */:
27950                 return visitNode(cbNode, node.tryBlock) ||
27951                     visitNode(cbNode, node.catchClause) ||
27952                     visitNode(cbNode, node.finallyBlock);
27953             case 287 /* CatchClause */:
27954                 return visitNode(cbNode, node.variableDeclaration) ||
27955                     visitNode(cbNode, node.block);
27956             case 161 /* Decorator */:
27957                 return visitNode(cbNode, node.expression);
27958             case 252 /* ClassDeclaration */:
27959             case 221 /* ClassExpression */:
27960                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27961                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27962                     visitNode(cbNode, node.name) ||
27963                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27964                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
27965                     visitNodes(cbNode, cbNodes, node.members);
27966             case 253 /* InterfaceDeclaration */:
27967                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27968                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27969                     visitNode(cbNode, node.name) ||
27970                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27971                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
27972                     visitNodes(cbNode, cbNodes, node.members);
27973             case 254 /* TypeAliasDeclaration */:
27974                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27975                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27976                     visitNode(cbNode, node.name) ||
27977                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27978                     visitNode(cbNode, node.type);
27979             case 255 /* EnumDeclaration */:
27980                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27981                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27982                     visitNode(cbNode, node.name) ||
27983                     visitNodes(cbNode, cbNodes, node.members);
27984             case 291 /* EnumMember */:
27985                 return visitNode(cbNode, node.name) ||
27986                     visitNode(cbNode, node.initializer);
27987             case 256 /* ModuleDeclaration */:
27988                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27989                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27990                     visitNode(cbNode, node.name) ||
27991                     visitNode(cbNode, node.body);
27992             case 260 /* ImportEqualsDeclaration */:
27993                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27994                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27995                     visitNode(cbNode, node.name) ||
27996                     visitNode(cbNode, node.moduleReference);
27997             case 261 /* ImportDeclaration */:
27998                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27999                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28000                     visitNode(cbNode, node.importClause) ||
28001                     visitNode(cbNode, node.moduleSpecifier);
28002             case 262 /* ImportClause */:
28003                 return visitNode(cbNode, node.name) ||
28004                     visitNode(cbNode, node.namedBindings);
28005             case 259 /* NamespaceExportDeclaration */:
28006                 return visitNode(cbNode, node.name);
28007             case 263 /* NamespaceImport */:
28008                 return visitNode(cbNode, node.name);
28009             case 269 /* NamespaceExport */:
28010                 return visitNode(cbNode, node.name);
28011             case 264 /* NamedImports */:
28012             case 268 /* NamedExports */:
28013                 return visitNodes(cbNode, cbNodes, node.elements);
28014             case 267 /* ExportDeclaration */:
28015                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28016                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28017                     visitNode(cbNode, node.exportClause) ||
28018                     visitNode(cbNode, node.moduleSpecifier);
28019             case 265 /* ImportSpecifier */:
28020             case 270 /* ExportSpecifier */:
28021                 return visitNode(cbNode, node.propertyName) ||
28022                     visitNode(cbNode, node.name);
28023             case 266 /* ExportAssignment */:
28024                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28025                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28026                     visitNode(cbNode, node.expression);
28027             case 218 /* TemplateExpression */:
28028                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
28029             case 228 /* TemplateSpan */:
28030                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
28031             case 193 /* TemplateLiteralType */:
28032                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
28033             case 194 /* TemplateLiteralTypeSpan */:
28034                 return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal);
28035             case 158 /* ComputedPropertyName */:
28036                 return visitNode(cbNode, node.expression);
28037             case 286 /* HeritageClause */:
28038                 return visitNodes(cbNode, cbNodes, node.types);
28039             case 223 /* ExpressionWithTypeArguments */:
28040                 return visitNode(cbNode, node.expression) ||
28041                     visitNodes(cbNode, cbNodes, node.typeArguments);
28042             case 272 /* ExternalModuleReference */:
28043                 return visitNode(cbNode, node.expression);
28044             case 271 /* MissingDeclaration */:
28045                 return visitNodes(cbNode, cbNodes, node.decorators);
28046             case 337 /* CommaListExpression */:
28047                 return visitNodes(cbNode, cbNodes, node.elements);
28048             case 273 /* JsxElement */:
28049                 return visitNode(cbNode, node.openingElement) ||
28050                     visitNodes(cbNode, cbNodes, node.children) ||
28051                     visitNode(cbNode, node.closingElement);
28052             case 277 /* JsxFragment */:
28053                 return visitNode(cbNode, node.openingFragment) ||
28054                     visitNodes(cbNode, cbNodes, node.children) ||
28055                     visitNode(cbNode, node.closingFragment);
28056             case 274 /* JsxSelfClosingElement */:
28057             case 275 /* JsxOpeningElement */:
28058                 return visitNode(cbNode, node.tagName) ||
28059                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
28060                     visitNode(cbNode, node.attributes);
28061             case 281 /* JsxAttributes */:
28062                 return visitNodes(cbNode, cbNodes, node.properties);
28063             case 280 /* JsxAttribute */:
28064                 return visitNode(cbNode, node.name) ||
28065                     visitNode(cbNode, node.initializer);
28066             case 282 /* JsxSpreadAttribute */:
28067                 return visitNode(cbNode, node.expression);
28068             case 283 /* JsxExpression */:
28069                 return visitNode(cbNode, node.dotDotDotToken) ||
28070                     visitNode(cbNode, node.expression);
28071             case 276 /* JsxClosingElement */:
28072                 return visitNode(cbNode, node.tagName);
28073             case 180 /* OptionalType */:
28074             case 181 /* RestType */:
28075             case 301 /* JSDocTypeExpression */:
28076             case 306 /* JSDocNonNullableType */:
28077             case 305 /* JSDocNullableType */:
28078             case 307 /* JSDocOptionalType */:
28079             case 309 /* JSDocVariadicType */:
28080                 return visitNode(cbNode, node.type);
28081             case 308 /* JSDocFunctionType */:
28082                 return visitNodes(cbNode, cbNodes, node.parameters) ||
28083                     visitNode(cbNode, node.type);
28084             case 311 /* JSDocComment */:
28085                 return visitNodes(cbNode, cbNodes, node.tags);
28086             case 332 /* JSDocSeeTag */:
28087                 return visitNode(cbNode, node.tagName) ||
28088                     visitNode(cbNode, node.name);
28089             case 302 /* JSDocNameReference */:
28090                 return visitNode(cbNode, node.name);
28091             case 326 /* JSDocParameterTag */:
28092             case 333 /* JSDocPropertyTag */:
28093                 return visitNode(cbNode, node.tagName) ||
28094                     (node.isNameFirst
28095                         ? visitNode(cbNode, node.name) ||
28096                             visitNode(cbNode, node.typeExpression)
28097                         : visitNode(cbNode, node.typeExpression) ||
28098                             visitNode(cbNode, node.name));
28099             case 317 /* JSDocAuthorTag */:
28100                 return visitNode(cbNode, node.tagName);
28101             case 316 /* JSDocImplementsTag */:
28102                 return visitNode(cbNode, node.tagName) ||
28103                     visitNode(cbNode, node.class);
28104             case 315 /* JSDocAugmentsTag */:
28105                 return visitNode(cbNode, node.tagName) ||
28106                     visitNode(cbNode, node.class);
28107             case 330 /* JSDocTemplateTag */:
28108                 return visitNode(cbNode, node.tagName) ||
28109                     visitNode(cbNode, node.constraint) ||
28110                     visitNodes(cbNode, cbNodes, node.typeParameters);
28111             case 331 /* JSDocTypedefTag */:
28112                 return visitNode(cbNode, node.tagName) ||
28113                     (node.typeExpression &&
28114                         node.typeExpression.kind === 301 /* JSDocTypeExpression */
28115                         ? visitNode(cbNode, node.typeExpression) ||
28116                             visitNode(cbNode, node.fullName)
28117                         : visitNode(cbNode, node.fullName) ||
28118                             visitNode(cbNode, node.typeExpression));
28119             case 324 /* JSDocCallbackTag */:
28120                 return visitNode(cbNode, node.tagName) ||
28121                     visitNode(cbNode, node.fullName) ||
28122                     visitNode(cbNode, node.typeExpression);
28123             case 327 /* JSDocReturnTag */:
28124             case 329 /* JSDocTypeTag */:
28125             case 328 /* JSDocThisTag */:
28126             case 325 /* JSDocEnumTag */:
28127                 return visitNode(cbNode, node.tagName) ||
28128                     visitNode(cbNode, node.typeExpression);
28129             case 313 /* JSDocSignature */:
28130                 return ts.forEach(node.typeParameters, cbNode) ||
28131                     ts.forEach(node.parameters, cbNode) ||
28132                     visitNode(cbNode, node.type);
28133             case 312 /* JSDocTypeLiteral */:
28134                 return ts.forEach(node.jsDocPropertyTags, cbNode);
28135             case 314 /* JSDocTag */:
28136             case 319 /* JSDocClassTag */:
28137             case 320 /* JSDocPublicTag */:
28138             case 321 /* JSDocPrivateTag */:
28139             case 322 /* JSDocProtectedTag */:
28140             case 323 /* JSDocReadonlyTag */:
28141                 return visitNode(cbNode, node.tagName);
28142             case 336 /* PartiallyEmittedExpression */:
28143                 return visitNode(cbNode, node.expression);
28144         }
28145     }
28146     ts.forEachChild = forEachChild;
28147     /** @internal */
28148     /**
28149      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
28150      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
28151      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
28152      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
28153      *
28154      * @param node a given node to visit its children
28155      * @param cbNode a callback to be invoked for all child nodes
28156      * @param cbNodes a callback to be invoked for embedded array
28157      *
28158      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
28159      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
28160      */
28161     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
28162         var stack = [rootNode];
28163         while (stack.length) {
28164             var parent = stack.pop();
28165             var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
28166             if (res) {
28167                 return res;
28168             }
28169         }
28170         return;
28171         function gatherPossibleChildren(node) {
28172             var children = [];
28173             forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
28174             return children;
28175             function addWorkItem(n) {
28176                 children.unshift(n);
28177             }
28178         }
28179         function visitAllPossibleChildren(parent, children) {
28180             for (var _i = 0, children_5 = children; _i < children_5.length; _i++) {
28181                 var child = children_5[_i];
28182                 if (ts.isArray(child)) {
28183                     if (cbNodes) {
28184                         var res = cbNodes(child, parent);
28185                         if (res) {
28186                             if (res === "skip")
28187                                 continue;
28188                             return res;
28189                         }
28190                     }
28191                     for (var i = child.length - 1; i >= 0; i--) {
28192                         var realChild = child[i];
28193                         var res = cbNode(realChild, parent);
28194                         if (res) {
28195                             if (res === "skip")
28196                                 continue;
28197                             return res;
28198                         }
28199                         stack.push(realChild);
28200                     }
28201                 }
28202                 else {
28203                     stack.push(child);
28204                     var res = cbNode(child, parent);
28205                     if (res) {
28206                         if (res === "skip")
28207                             continue;
28208                         return res;
28209                     }
28210                 }
28211             }
28212         }
28213     }
28214     ts.forEachChildRecursively = forEachChildRecursively;
28215     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
28216         if (setParentNodes === void 0) { setParentNodes = false; }
28217         var tracingData = ["parse" /* Parse */, "createSourceFile", { path: fileName }];
28218         ts.tracing.begin.apply(ts.tracing, tracingData);
28219         ts.performance.mark("beforeParse");
28220         var result;
28221         ts.perfLogger.logStartParseSourceFile(fileName);
28222         if (languageVersion === 100 /* JSON */) {
28223             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
28224         }
28225         else {
28226             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
28227         }
28228         ts.perfLogger.logStopParseSourceFile();
28229         ts.performance.mark("afterParse");
28230         ts.performance.measure("Parse", "beforeParse", "afterParse");
28231         ts.tracing.end.apply(ts.tracing, tracingData);
28232         return result;
28233     }
28234     ts.createSourceFile = createSourceFile;
28235     function parseIsolatedEntityName(text, languageVersion) {
28236         return Parser.parseIsolatedEntityName(text, languageVersion);
28237     }
28238     ts.parseIsolatedEntityName = parseIsolatedEntityName;
28239     /**
28240      * Parse json text into SyntaxTree and return node and parse errors if any
28241      * @param fileName
28242      * @param sourceText
28243      */
28244     function parseJsonText(fileName, sourceText) {
28245         return Parser.parseJsonText(fileName, sourceText);
28246     }
28247     ts.parseJsonText = parseJsonText;
28248     // See also `isExternalOrCommonJsModule` in utilities.ts
28249     function isExternalModule(file) {
28250         return file.externalModuleIndicator !== undefined;
28251     }
28252     ts.isExternalModule = isExternalModule;
28253     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
28254     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
28255     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
28256     // this file as possible.
28257     //
28258     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
28259     // from this SourceFile that are being held onto may change as a result (including
28260     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
28261     // be used once 'update' is called on it.
28262     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
28263         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
28264         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
28265         // 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.
28266         // We will manually port the flag to the new source file.
28267         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
28268         return newSourceFile;
28269     }
28270     ts.updateSourceFile = updateSourceFile;
28271     /* @internal */
28272     function parseIsolatedJSDocComment(content, start, length) {
28273         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
28274         if (result && result.jsDoc) {
28275             // because the jsDocComment was parsed out of the source file, it might
28276             // not be covered by the fixupParentReferences.
28277             Parser.fixupParentReferences(result.jsDoc);
28278         }
28279         return result;
28280     }
28281     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
28282     /* @internal */
28283     // Exposed only for testing.
28284     function parseJSDocTypeExpressionForTests(content, start, length) {
28285         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
28286     }
28287     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
28288     // Implement the parser as a singleton module.  We do this for perf reasons because creating
28289     // parser instances can actually be expensive enough to impact us on projects with many source
28290     // files.
28291     var Parser;
28292     (function (Parser) {
28293         // Share a single scanner across all calls to parse a source file.  This helps speed things
28294         // up by avoiding the cost of creating/compiling scanners over and over again.
28295         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
28296         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
28297         // capture constructors in 'initializeState' to avoid null checks
28298         // tslint:disable variable-name
28299         var NodeConstructor;
28300         var TokenConstructor;
28301         var IdentifierConstructor;
28302         var PrivateIdentifierConstructor;
28303         var SourceFileConstructor;
28304         // tslint:enable variable-name
28305         function countNode(node) {
28306             nodeCount++;
28307             return node;
28308         }
28309         // Rather than using `createBaseNodeFactory` here, we establish a `BaseNodeFactory` that closes over the
28310         // constructors above, which are reset each time `initializeState` is called.
28311         var baseNodeFactory = {
28312             createBaseSourceFileNode: function (kind) { return countNode(new SourceFileConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28313             createBaseIdentifierNode: function (kind) { return countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28314             createBasePrivateIdentifierNode: function (kind) { return countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28315             createBaseTokenNode: function (kind) { return countNode(new TokenConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28316             createBaseNode: function (kind) { return countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0)); }
28317         };
28318         var factory = ts.createNodeFactory(1 /* NoParenthesizerRules */ | 2 /* NoNodeConverters */ | 8 /* NoOriginalNode */, baseNodeFactory);
28319         var fileName;
28320         var sourceFlags;
28321         var sourceText;
28322         var languageVersion;
28323         var scriptKind;
28324         var languageVariant;
28325         var parseDiagnostics;
28326         var jsDocDiagnostics;
28327         var syntaxCursor;
28328         var currentToken;
28329         var nodeCount;
28330         var identifiers;
28331         var privateIdentifiers;
28332         var identifierCount;
28333         var parsingContext;
28334         var notParenthesizedArrow;
28335         // Flags that dictate what parsing context we're in.  For example:
28336         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
28337         // that some tokens that would be considered identifiers may be considered keywords.
28338         //
28339         // When adding more parser context flags, consider which is the more common case that the
28340         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
28341         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
28342         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
28343         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
28344         // all nodes would need extra state on them to store this info.
28345         //
28346         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
28347         // grammar specification.
28348         //
28349         // An important thing about these context concepts.  By default they are effectively inherited
28350         // while parsing through every grammar production.  i.e. if you don't change them, then when
28351         // you parse a sub-production, it will have the same context values as the parent production.
28352         // This is great most of the time.  After all, consider all the 'expression' grammar productions
28353         // and how nearly all of them pass along the 'in' and 'yield' context values:
28354         //
28355         // EqualityExpression[In, Yield] :
28356         //      RelationalExpression[?In, ?Yield]
28357         //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
28358         //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
28359         //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
28360         //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
28361         //
28362         // Where you have to be careful is then understanding what the points are in the grammar
28363         // where the values are *not* passed along.  For example:
28364         //
28365         // SingleNameBinding[Yield,GeneratorParameter]
28366         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
28367         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
28368         //
28369         // Here this is saying that if the GeneratorParameter context flag is set, that we should
28370         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
28371         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
28372         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
28373         // should leave the 'yield' context flag alone.
28374         //
28375         // Getting this all correct is tricky and requires careful reading of the grammar to
28376         // understand when these values should be changed versus when they should be inherited.
28377         //
28378         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
28379         // parsing.  These context flags are naturally stored and restored through normal recursive
28380         // descent parsing and unwinding.
28381         var contextFlags;
28382         // Indicates whether we are currently parsing top-level statements.
28383         var topLevel = true;
28384         // Whether or not we've had a parse error since creating the last AST node.  If we have
28385         // encountered an error, it will be stored on the next AST node we create.  Parse errors
28386         // can be broken down into three categories:
28387         //
28388         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
28389         //    character that was completely not understood.
28390         //
28391         // 2) A token was expected, but was not present.  This type of error is commonly produced
28392         //    by the 'parseExpected' function.
28393         //
28394         // 3) A token was present that no parsing function was able to consume.  This type of error
28395         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
28396         //    decides to skip the token.
28397         //
28398         // In all of these cases, we want to mark the next node as having had an error before it.
28399         // With this mark, we can know in incremental settings if this node can be reused, or if
28400         // we have to reparse it.  If we don't keep this information around, we may just reuse the
28401         // node.  in that event we would then not produce the same errors as we did before, causing
28402         // significant confusion problems.
28403         //
28404         // Note: it is necessary that this value be saved/restored during speculative/lookahead
28405         // parsing.  During lookahead parsing, we will often create a node.  That node will have
28406         // this value attached, and then this value will be set back to 'false'.  If we decide to
28407         // rewind, we must get back to the same value we had prior to the lookahead.
28408         //
28409         // Note: any errors at the end of the file that do not precede a regular node, should get
28410         // attached to the EOF token.
28411         var parseErrorBeforeNextFinishedNode = false;
28412         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
28413             if (setParentNodes === void 0) { setParentNodes = false; }
28414             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
28415             if (scriptKind === 6 /* JSON */) {
28416                 var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
28417                 ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
28418                 result_3.referencedFiles = ts.emptyArray;
28419                 result_3.typeReferenceDirectives = ts.emptyArray;
28420                 result_3.libReferenceDirectives = ts.emptyArray;
28421                 result_3.amdDependencies = ts.emptyArray;
28422                 result_3.hasNoDefaultLib = false;
28423                 result_3.pragmas = ts.emptyMap;
28424                 return result_3;
28425             }
28426             initializeState(fileName, sourceText, languageVersion, syntaxCursor, scriptKind);
28427             var result = parseSourceFileWorker(languageVersion, setParentNodes, scriptKind);
28428             clearState();
28429             return result;
28430         }
28431         Parser.parseSourceFile = parseSourceFile;
28432         function parseIsolatedEntityName(content, languageVersion) {
28433             // Choice of `isDeclarationFile` should be arbitrary
28434             initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
28435             // Prime the scanner.
28436             nextToken();
28437             var entityName = parseEntityName(/*allowReservedWords*/ true);
28438             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
28439             clearState();
28440             return isInvalid ? entityName : undefined;
28441         }
28442         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
28443         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
28444             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
28445             if (setParentNodes === void 0) { setParentNodes = false; }
28446             initializeState(fileName, sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
28447             sourceFlags = contextFlags;
28448             // Prime the scanner.
28449             nextToken();
28450             var pos = getNodePos();
28451             var statements, endOfFileToken;
28452             if (token() === 1 /* EndOfFileToken */) {
28453                 statements = createNodeArray([], pos, pos);
28454                 endOfFileToken = parseTokenNode();
28455             }
28456             else {
28457                 var expression = void 0;
28458                 switch (token()) {
28459                     case 22 /* OpenBracketToken */:
28460                         expression = parseArrayLiteralExpression();
28461                         break;
28462                     case 109 /* TrueKeyword */:
28463                     case 94 /* FalseKeyword */:
28464                     case 103 /* NullKeyword */:
28465                         expression = parseTokenNode();
28466                         break;
28467                     case 40 /* MinusToken */:
28468                         if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
28469                             expression = parsePrefixUnaryExpression();
28470                         }
28471                         else {
28472                             expression = parseObjectLiteralExpression();
28473                         }
28474                         break;
28475                     case 8 /* NumericLiteral */:
28476                     case 10 /* StringLiteral */:
28477                         if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
28478                             expression = parseLiteralNode();
28479                             break;
28480                         }
28481                     // falls through
28482                     default:
28483                         expression = parseObjectLiteralExpression();
28484                         break;
28485                 }
28486                 var statement = factory.createExpressionStatement(expression);
28487                 finishNode(statement, pos);
28488                 statements = createNodeArray([statement], pos);
28489                 endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
28490             }
28491             // Set source file so that errors will be reported with this file name
28492             var sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false, statements, endOfFileToken, sourceFlags);
28493             if (setParentNodes) {
28494                 fixupParentReferences(sourceFile);
28495             }
28496             sourceFile.nodeCount = nodeCount;
28497             sourceFile.identifierCount = identifierCount;
28498             sourceFile.identifiers = identifiers;
28499             sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
28500             if (jsDocDiagnostics) {
28501                 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
28502             }
28503             var result = sourceFile;
28504             clearState();
28505             return result;
28506         }
28507         Parser.parseJsonText = parseJsonText;
28508         function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind) {
28509             NodeConstructor = ts.objectAllocator.getNodeConstructor();
28510             TokenConstructor = ts.objectAllocator.getTokenConstructor();
28511             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
28512             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
28513             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
28514             fileName = ts.normalizePath(_fileName);
28515             sourceText = _sourceText;
28516             languageVersion = _languageVersion;
28517             syntaxCursor = _syntaxCursor;
28518             scriptKind = _scriptKind;
28519             languageVariant = ts.getLanguageVariant(_scriptKind);
28520             parseDiagnostics = [];
28521             parsingContext = 0;
28522             identifiers = new ts.Map();
28523             privateIdentifiers = new ts.Map();
28524             identifierCount = 0;
28525             nodeCount = 0;
28526             sourceFlags = 0;
28527             topLevel = true;
28528             switch (scriptKind) {
28529                 case 1 /* JS */:
28530                 case 2 /* JSX */:
28531                     contextFlags = 131072 /* JavaScriptFile */;
28532                     break;
28533                 case 6 /* JSON */:
28534                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
28535                     break;
28536                 default:
28537                     contextFlags = 0 /* None */;
28538                     break;
28539             }
28540             parseErrorBeforeNextFinishedNode = false;
28541             // Initialize and prime the scanner before parsing the source elements.
28542             scanner.setText(sourceText);
28543             scanner.setOnError(scanError);
28544             scanner.setScriptTarget(languageVersion);
28545             scanner.setLanguageVariant(languageVariant);
28546         }
28547         function clearState() {
28548             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
28549             scanner.clearCommentDirectives();
28550             scanner.setText("");
28551             scanner.setOnError(undefined);
28552             // Clear any data.  We don't want to accidentally hold onto it for too long.
28553             sourceText = undefined;
28554             languageVersion = undefined;
28555             syntaxCursor = undefined;
28556             scriptKind = undefined;
28557             languageVariant = undefined;
28558             sourceFlags = 0;
28559             parseDiagnostics = undefined;
28560             jsDocDiagnostics = undefined;
28561             parsingContext = 0;
28562             identifiers = undefined;
28563             notParenthesizedArrow = undefined;
28564             topLevel = true;
28565         }
28566         function parseSourceFileWorker(languageVersion, setParentNodes, scriptKind) {
28567             var isDeclarationFile = isDeclarationFileName(fileName);
28568             if (isDeclarationFile) {
28569                 contextFlags |= 8388608 /* Ambient */;
28570             }
28571             sourceFlags = contextFlags;
28572             // Prime the scanner.
28573             nextToken();
28574             var statements = parseList(0 /* SourceElements */, parseStatement);
28575             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
28576             var endOfFileToken = addJSDocComment(parseTokenNode());
28577             var sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, sourceFlags);
28578             // A member of ReadonlyArray<T> 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
28579             processCommentPragmas(sourceFile, sourceText);
28580             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
28581             sourceFile.commentDirectives = scanner.getCommentDirectives();
28582             sourceFile.nodeCount = nodeCount;
28583             sourceFile.identifierCount = identifierCount;
28584             sourceFile.identifiers = identifiers;
28585             sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
28586             if (jsDocDiagnostics) {
28587                 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
28588             }
28589             if (setParentNodes) {
28590                 fixupParentReferences(sourceFile);
28591             }
28592             return sourceFile;
28593             function reportPragmaDiagnostic(pos, end, diagnostic) {
28594                 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, pos, end, diagnostic));
28595             }
28596         }
28597         function withJSDoc(node, hasJSDoc) {
28598             return hasJSDoc ? addJSDocComment(node) : node;
28599         }
28600         var hasDeprecatedTag = false;
28601         function addJSDocComment(node) {
28602             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
28603             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceText), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
28604             if (jsDoc.length)
28605                 node.jsDoc = jsDoc;
28606             if (hasDeprecatedTag) {
28607                 hasDeprecatedTag = false;
28608                 node.flags |= 134217728 /* Deprecated */;
28609             }
28610             return node;
28611         }
28612         function reparseTopLevelAwait(sourceFile) {
28613             var savedSyntaxCursor = syntaxCursor;
28614             var baseSyntaxCursor = IncrementalParser.createSyntaxCursor(sourceFile);
28615             syntaxCursor = { currentNode: currentNode };
28616             var statements = [];
28617             var savedParseDiagnostics = parseDiagnostics;
28618             parseDiagnostics = [];
28619             var pos = 0;
28620             var start = findNextStatementWithAwait(sourceFile.statements, 0);
28621             var _loop_3 = function () {
28622                 // append all statements between pos and start
28623                 var prevStatement = sourceFile.statements[pos];
28624                 var nextStatement = sourceFile.statements[start];
28625                 ts.addRange(statements, sourceFile.statements, pos, start);
28626                 pos = findNextStatementWithoutAwait(sourceFile.statements, start);
28627                 // append all diagnostics associated with the copied range
28628                 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement.pos; });
28629                 var diagnosticEnd = diagnosticStart >= 0 ? ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= nextStatement.pos; }, diagnosticStart) : -1;
28630                 if (diagnosticStart >= 0) {
28631                     ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : undefined);
28632                 }
28633                 // reparse all statements between start and pos. We skip existing diagnostics for the same range and allow the parser to generate new ones.
28634                 speculationHelper(function () {
28635                     var savedContextFlags = contextFlags;
28636                     contextFlags |= 32768 /* AwaitContext */;
28637                     scanner.setTextPos(nextStatement.pos);
28638                     nextToken();
28639                     while (token() !== 1 /* EndOfFileToken */) {
28640                         var startPos = scanner.getStartPos();
28641                         var statement = parseListElement(0 /* SourceElements */, parseStatement);
28642                         statements.push(statement);
28643                         if (startPos === scanner.getStartPos()) {
28644                             nextToken();
28645                         }
28646                         if (pos >= 0) {
28647                             var nonAwaitStatement = sourceFile.statements[pos];
28648                             if (statement.end === nonAwaitStatement.pos) {
28649                                 // done reparsing this section
28650                                 break;
28651                             }
28652                             if (statement.end > nonAwaitStatement.pos) {
28653                                 // we ate into the next statement, so we must reparse it.
28654                                 pos = findNextStatementWithoutAwait(sourceFile.statements, pos + 1);
28655                             }
28656                         }
28657                     }
28658                     contextFlags = savedContextFlags;
28659                 }, 2 /* Reparse */);
28660                 // find the next statement containing an `await`
28661                 start = pos >= 0 ? findNextStatementWithAwait(sourceFile.statements, pos) : -1;
28662             };
28663             while (start !== -1) {
28664                 _loop_3();
28665             }
28666             // append all statements between pos and the end of the list
28667             if (pos >= 0) {
28668                 var prevStatement_1 = sourceFile.statements[pos];
28669                 ts.addRange(statements, sourceFile.statements, pos);
28670                 // append all diagnostics associated with the copied range
28671                 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement_1.pos; });
28672                 if (diagnosticStart >= 0) {
28673                     ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart);
28674                 }
28675             }
28676             syntaxCursor = savedSyntaxCursor;
28677             return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements));
28678             function containsPossibleTopLevelAwait(node) {
28679                 return !(node.flags & 32768 /* AwaitContext */)
28680                     && !!(node.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */);
28681             }
28682             function findNextStatementWithAwait(statements, start) {
28683                 for (var i = start; i < statements.length; i++) {
28684                     if (containsPossibleTopLevelAwait(statements[i])) {
28685                         return i;
28686                     }
28687                 }
28688                 return -1;
28689             }
28690             function findNextStatementWithoutAwait(statements, start) {
28691                 for (var i = start; i < statements.length; i++) {
28692                     if (!containsPossibleTopLevelAwait(statements[i])) {
28693                         return i;
28694                     }
28695                 }
28696                 return -1;
28697             }
28698             function currentNode(position) {
28699                 var node = baseSyntaxCursor.currentNode(position);
28700                 if (topLevel && node && containsPossibleTopLevelAwait(node)) {
28701                     node.intersectsChange = true;
28702                 }
28703                 return node;
28704             }
28705         }
28706         function fixupParentReferences(rootNode) {
28707             // normally parent references are set during binding. However, for clients that only need
28708             // a syntax tree, and no semantic features, then the binding process is an unnecessary
28709             // overhead.  This functions allows us to set all the parents, without all the expense of
28710             // binding.
28711             ts.setParentRecursive(rootNode, /*incremental*/ true);
28712         }
28713         Parser.fixupParentReferences = fixupParentReferences;
28714         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, flags) {
28715             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
28716             // this is quite rare comparing to other nodes and createNode should be as fast as possible
28717             var sourceFile = factory.createSourceFile(statements, endOfFileToken, flags);
28718             ts.setTextRangePosWidth(sourceFile, 0, sourceText.length);
28719             setExternalModuleIndicator(sourceFile);
28720             // If we parsed this as an external module, it may contain top-level await
28721             if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */) {
28722                 sourceFile = reparseTopLevelAwait(sourceFile);
28723             }
28724             sourceFile.text = sourceText;
28725             sourceFile.bindDiagnostics = [];
28726             sourceFile.bindSuggestionDiagnostics = undefined;
28727             sourceFile.languageVersion = languageVersion;
28728             sourceFile.fileName = fileName;
28729             sourceFile.languageVariant = ts.getLanguageVariant(scriptKind);
28730             sourceFile.isDeclarationFile = isDeclarationFile;
28731             sourceFile.scriptKind = scriptKind;
28732             return sourceFile;
28733         }
28734         function setContextFlag(val, flag) {
28735             if (val) {
28736                 contextFlags |= flag;
28737             }
28738             else {
28739                 contextFlags &= ~flag;
28740             }
28741         }
28742         function setDisallowInContext(val) {
28743             setContextFlag(val, 4096 /* DisallowInContext */);
28744         }
28745         function setYieldContext(val) {
28746             setContextFlag(val, 8192 /* YieldContext */);
28747         }
28748         function setDecoratorContext(val) {
28749             setContextFlag(val, 16384 /* DecoratorContext */);
28750         }
28751         function setAwaitContext(val) {
28752             setContextFlag(val, 32768 /* AwaitContext */);
28753         }
28754         function doOutsideOfContext(context, func) {
28755             // contextFlagsToClear will contain only the context flags that are
28756             // currently set that we need to temporarily clear
28757             // We don't just blindly reset to the previous flags to ensure
28758             // that we do not mutate cached flags for the incremental
28759             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
28760             // HasAggregatedChildData).
28761             var contextFlagsToClear = context & contextFlags;
28762             if (contextFlagsToClear) {
28763                 // clear the requested context flags
28764                 setContextFlag(/*val*/ false, contextFlagsToClear);
28765                 var result = func();
28766                 // restore the context flags we just cleared
28767                 setContextFlag(/*val*/ true, contextFlagsToClear);
28768                 return result;
28769             }
28770             // no need to do anything special as we are not in any of the requested contexts
28771             return func();
28772         }
28773         function doInsideOfContext(context, func) {
28774             // contextFlagsToSet will contain only the context flags that
28775             // are not currently set that we need to temporarily enable.
28776             // We don't just blindly reset to the previous flags to ensure
28777             // that we do not mutate cached flags for the incremental
28778             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
28779             // HasAggregatedChildData).
28780             var contextFlagsToSet = context & ~contextFlags;
28781             if (contextFlagsToSet) {
28782                 // set the requested context flags
28783                 setContextFlag(/*val*/ true, contextFlagsToSet);
28784                 var result = func();
28785                 // reset the context flags we just set
28786                 setContextFlag(/*val*/ false, contextFlagsToSet);
28787                 return result;
28788             }
28789             // no need to do anything special as we are already in all of the requested contexts
28790             return func();
28791         }
28792         function allowInAnd(func) {
28793             return doOutsideOfContext(4096 /* DisallowInContext */, func);
28794         }
28795         function disallowInAnd(func) {
28796             return doInsideOfContext(4096 /* DisallowInContext */, func);
28797         }
28798         function doInYieldContext(func) {
28799             return doInsideOfContext(8192 /* YieldContext */, func);
28800         }
28801         function doInDecoratorContext(func) {
28802             return doInsideOfContext(16384 /* DecoratorContext */, func);
28803         }
28804         function doInAwaitContext(func) {
28805             return doInsideOfContext(32768 /* AwaitContext */, func);
28806         }
28807         function doOutsideOfAwaitContext(func) {
28808             return doOutsideOfContext(32768 /* AwaitContext */, func);
28809         }
28810         function doInYieldAndAwaitContext(func) {
28811             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
28812         }
28813         function doOutsideOfYieldAndAwaitContext(func) {
28814             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
28815         }
28816         function inContext(flags) {
28817             return (contextFlags & flags) !== 0;
28818         }
28819         function inYieldContext() {
28820             return inContext(8192 /* YieldContext */);
28821         }
28822         function inDisallowInContext() {
28823             return inContext(4096 /* DisallowInContext */);
28824         }
28825         function inDecoratorContext() {
28826             return inContext(16384 /* DecoratorContext */);
28827         }
28828         function inAwaitContext() {
28829             return inContext(32768 /* AwaitContext */);
28830         }
28831         function parseErrorAtCurrentToken(message, arg0) {
28832             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
28833         }
28834         function parseErrorAtPosition(start, length, message, arg0) {
28835             // Don't report another error if it would just be at the same position as the last error.
28836             var lastError = ts.lastOrUndefined(parseDiagnostics);
28837             if (!lastError || start !== lastError.start) {
28838                 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, start, length, message, arg0));
28839             }
28840             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
28841             // node we finish so that it can't be reused incrementally.
28842             parseErrorBeforeNextFinishedNode = true;
28843         }
28844         function parseErrorAt(start, end, message, arg0) {
28845             parseErrorAtPosition(start, end - start, message, arg0);
28846         }
28847         function parseErrorAtRange(range, message, arg0) {
28848             parseErrorAt(range.pos, range.end, message, arg0);
28849         }
28850         function scanError(message, length) {
28851             parseErrorAtPosition(scanner.getTextPos(), length, message);
28852         }
28853         function getNodePos() {
28854             return scanner.getStartPos();
28855         }
28856         function hasPrecedingJSDocComment() {
28857             return scanner.hasPrecedingJSDocComment();
28858         }
28859         // Use this function to access the current token instead of reading the currentToken
28860         // variable. Since function results aren't narrowed in control flow analysis, this ensures
28861         // that the type checker doesn't make wrong assumptions about the type of the current
28862         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
28863         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
28864         // there is no performance penalty.
28865         function token() {
28866             return currentToken;
28867         }
28868         function nextTokenWithoutCheck() {
28869             return currentToken = scanner.scan();
28870         }
28871         function nextTokenAnd(func) {
28872             nextToken();
28873             return func();
28874         }
28875         function nextToken() {
28876             // if the keyword had an escape
28877             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
28878                 // issue a parse error for the escape
28879                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
28880             }
28881             return nextTokenWithoutCheck();
28882         }
28883         function nextTokenJSDoc() {
28884             return currentToken = scanner.scanJsDocToken();
28885         }
28886         function reScanGreaterToken() {
28887             return currentToken = scanner.reScanGreaterToken();
28888         }
28889         function reScanSlashToken() {
28890             return currentToken = scanner.reScanSlashToken();
28891         }
28892         function reScanTemplateToken(isTaggedTemplate) {
28893             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
28894         }
28895         function reScanTemplateHeadOrNoSubstitutionTemplate() {
28896             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
28897         }
28898         function reScanLessThanToken() {
28899             return currentToken = scanner.reScanLessThanToken();
28900         }
28901         function scanJsxIdentifier() {
28902             return currentToken = scanner.scanJsxIdentifier();
28903         }
28904         function scanJsxText() {
28905             return currentToken = scanner.scanJsxToken();
28906         }
28907         function scanJsxAttributeValue() {
28908             return currentToken = scanner.scanJsxAttributeValue();
28909         }
28910         function speculationHelper(callback, speculationKind) {
28911             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
28912             // caller asked us to always reset our state).
28913             var saveToken = currentToken;
28914             var saveParseDiagnosticsLength = parseDiagnostics.length;
28915             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
28916             // Note: it is not actually necessary to save/restore the context flags here.  That's
28917             // because the saving/restoring of these flags happens naturally through the recursive
28918             // descent nature of our parser.  However, we still store this here just so we can
28919             // assert that invariant holds.
28920             var saveContextFlags = contextFlags;
28921             // If we're only looking ahead, then tell the scanner to only lookahead as well.
28922             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
28923             // same.
28924             var result = speculationKind !== 0 /* TryParse */
28925                 ? scanner.lookAhead(callback)
28926                 : scanner.tryScan(callback);
28927             ts.Debug.assert(saveContextFlags === contextFlags);
28928             // If our callback returned something 'falsy' or we're just looking ahead,
28929             // then unconditionally restore us to where we were.
28930             if (!result || speculationKind !== 0 /* TryParse */) {
28931                 currentToken = saveToken;
28932                 if (speculationKind !== 2 /* Reparse */) {
28933                     parseDiagnostics.length = saveParseDiagnosticsLength;
28934                 }
28935                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
28936             }
28937             return result;
28938         }
28939         /** Invokes the provided callback then unconditionally restores the parser to the state it
28940          * was in immediately prior to invoking the callback.  The result of invoking the callback
28941          * is returned from this function.
28942          */
28943         function lookAhead(callback) {
28944             return speculationHelper(callback, 1 /* Lookahead */);
28945         }
28946         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
28947          * the parser to the state it was in immediately prior to invoking the callback.  If the
28948          * callback returns something truthy, then the parser state is not rolled back.  The result
28949          * of invoking the callback is returned from this function.
28950          */
28951         function tryParse(callback) {
28952             return speculationHelper(callback, 0 /* TryParse */);
28953         }
28954         function isBindingIdentifier() {
28955             if (token() === 78 /* Identifier */) {
28956                 return true;
28957             }
28958             return token() > 115 /* LastReservedWord */;
28959         }
28960         // Ignore strict mode flag because we will report an error in type checker instead.
28961         function isIdentifier() {
28962             if (token() === 78 /* Identifier */) {
28963                 return true;
28964             }
28965             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
28966             // considered a keyword and is not an identifier.
28967             if (token() === 124 /* YieldKeyword */ && inYieldContext()) {
28968                 return false;
28969             }
28970             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
28971             // considered a keyword and is not an identifier.
28972             if (token() === 130 /* AwaitKeyword */ && inAwaitContext()) {
28973                 return false;
28974             }
28975             return token() > 115 /* LastReservedWord */;
28976         }
28977         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
28978             if (shouldAdvance === void 0) { shouldAdvance = true; }
28979             if (token() === kind) {
28980                 if (shouldAdvance) {
28981                     nextToken();
28982                 }
28983                 return true;
28984             }
28985             // Report specific message if provided with one.  Otherwise, report generic fallback message.
28986             if (diagnosticMessage) {
28987                 parseErrorAtCurrentToken(diagnosticMessage);
28988             }
28989             else {
28990                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
28991             }
28992             return false;
28993         }
28994         function parseExpectedJSDoc(kind) {
28995             if (token() === kind) {
28996                 nextTokenJSDoc();
28997                 return true;
28998             }
28999             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
29000             return false;
29001         }
29002         function parseOptional(t) {
29003             if (token() === t) {
29004                 nextToken();
29005                 return true;
29006             }
29007             return false;
29008         }
29009         function parseOptionalToken(t) {
29010             if (token() === t) {
29011                 return parseTokenNode();
29012             }
29013             return undefined;
29014         }
29015         function parseOptionalTokenJSDoc(t) {
29016             if (token() === t) {
29017                 return parseTokenNodeJSDoc();
29018             }
29019             return undefined;
29020         }
29021         function parseExpectedToken(t, diagnosticMessage, arg0) {
29022             return parseOptionalToken(t) ||
29023                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
29024         }
29025         function parseExpectedTokenJSDoc(t) {
29026             return parseOptionalTokenJSDoc(t) ||
29027                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
29028         }
29029         function parseTokenNode() {
29030             var pos = getNodePos();
29031             var kind = token();
29032             nextToken();
29033             return finishNode(factory.createToken(kind), pos);
29034         }
29035         function parseTokenNodeJSDoc() {
29036             var pos = getNodePos();
29037             var kind = token();
29038             nextTokenJSDoc();
29039             return finishNode(factory.createToken(kind), pos);
29040         }
29041         function canParseSemicolon() {
29042             // If there's a real semicolon, then we can always parse it out.
29043             if (token() === 26 /* SemicolonToken */) {
29044                 return true;
29045             }
29046             // We can parse out an optional semicolon in ASI cases in the following cases.
29047             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
29048         }
29049         function parseSemicolon() {
29050             if (canParseSemicolon()) {
29051                 if (token() === 26 /* SemicolonToken */) {
29052                     // consume the semicolon if it was explicitly provided.
29053                     nextToken();
29054                 }
29055                 return true;
29056             }
29057             else {
29058                 return parseExpected(26 /* SemicolonToken */);
29059             }
29060         }
29061         function createNodeArray(elements, pos, end, hasTrailingComma) {
29062             var array = factory.createNodeArray(elements, hasTrailingComma);
29063             ts.setTextRangePosEnd(array, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
29064             return array;
29065         }
29066         function finishNode(node, pos, end) {
29067             ts.setTextRangePosEnd(node, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
29068             if (contextFlags) {
29069                 node.flags |= contextFlags;
29070             }
29071             // Keep track on the node if we encountered an error while parsing it.  If we did, then
29072             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
29073             // flag so that we don't mark any subsequent nodes.
29074             if (parseErrorBeforeNextFinishedNode) {
29075                 parseErrorBeforeNextFinishedNode = false;
29076                 node.flags |= 65536 /* ThisNodeHasError */;
29077             }
29078             return node;
29079         }
29080         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
29081             if (reportAtCurrentPosition) {
29082                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
29083             }
29084             else if (diagnosticMessage) {
29085                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
29086             }
29087             var pos = getNodePos();
29088             var result = kind === 78 /* Identifier */ ? factory.createIdentifier("", /*typeArguments*/ undefined, /*originalKeywordKind*/ undefined) :
29089                 ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) :
29090                     kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) :
29091                         kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) :
29092                             kind === 271 /* MissingDeclaration */ ? factory.createMissingDeclaration() :
29093                                 factory.createToken(kind);
29094             return finishNode(result, pos);
29095         }
29096         function internIdentifier(text) {
29097             var identifier = identifiers.get(text);
29098             if (identifier === undefined) {
29099                 identifiers.set(text, identifier = text);
29100             }
29101             return identifier;
29102         }
29103         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
29104         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
29105         // each identifier in order to reduce memory consumption.
29106         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
29107             identifierCount++;
29108             if (isIdentifier) {
29109                 var pos = getNodePos();
29110                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
29111                 var originalKeywordKind = token();
29112                 var text = internIdentifier(scanner.getTokenValue());
29113                 nextTokenWithoutCheck();
29114                 return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos);
29115             }
29116             if (token() === 79 /* PrivateIdentifier */) {
29117                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
29118                 return createIdentifier(/*isIdentifier*/ true);
29119             }
29120             // Only for end of file because the error gets reported incorrectly on embedded script tags.
29121             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
29122             var isReservedWord = scanner.isReservedWord();
29123             var msgArg = scanner.getTokenText();
29124             var defaultMessage = isReservedWord ?
29125                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
29126                 ts.Diagnostics.Identifier_expected;
29127             return createMissingNode(78 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
29128         }
29129         function parseBindingIdentifier(privateIdentifierDiagnosticMessage) {
29130             return createIdentifier(isBindingIdentifier(), /*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
29131         }
29132         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
29133             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
29134         }
29135         function parseIdentifierName(diagnosticMessage) {
29136             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
29137         }
29138         function isLiteralPropertyName() {
29139             return ts.tokenIsIdentifierOrKeyword(token()) ||
29140                 token() === 10 /* StringLiteral */ ||
29141                 token() === 8 /* NumericLiteral */;
29142         }
29143         function parsePropertyNameWorker(allowComputedPropertyNames) {
29144             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
29145                 var node = parseLiteralNode();
29146                 node.text = internIdentifier(node.text);
29147                 return node;
29148             }
29149             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
29150                 return parseComputedPropertyName();
29151             }
29152             if (token() === 79 /* PrivateIdentifier */) {
29153                 return parsePrivateIdentifier();
29154             }
29155             return parseIdentifierName();
29156         }
29157         function parsePropertyName() {
29158             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
29159         }
29160         function parseComputedPropertyName() {
29161             // PropertyName [Yield]:
29162             //      LiteralPropertyName
29163             //      ComputedPropertyName[?Yield]
29164             var pos = getNodePos();
29165             parseExpected(22 /* OpenBracketToken */);
29166             // We parse any expression (including a comma expression). But the grammar
29167             // says that only an assignment expression is allowed, so the grammar checker
29168             // will error if it sees a comma expression.
29169             var expression = allowInAnd(parseExpression);
29170             parseExpected(23 /* CloseBracketToken */);
29171             return finishNode(factory.createComputedPropertyName(expression), pos);
29172         }
29173         function internPrivateIdentifier(text) {
29174             var privateIdentifier = privateIdentifiers.get(text);
29175             if (privateIdentifier === undefined) {
29176                 privateIdentifiers.set(text, privateIdentifier = text);
29177             }
29178             return privateIdentifier;
29179         }
29180         function parsePrivateIdentifier() {
29181             var pos = getNodePos();
29182             var node = factory.createPrivateIdentifier(internPrivateIdentifier(scanner.getTokenText()));
29183             nextToken();
29184             return finishNode(node, pos);
29185         }
29186         function parseContextualModifier(t) {
29187             return token() === t && tryParse(nextTokenCanFollowModifier);
29188         }
29189         function nextTokenIsOnSameLineAndCanFollowModifier() {
29190             nextToken();
29191             if (scanner.hasPrecedingLineBreak()) {
29192                 return false;
29193             }
29194             return canFollowModifier();
29195         }
29196         function nextTokenCanFollowModifier() {
29197             switch (token()) {
29198                 case 84 /* ConstKeyword */:
29199                     // 'const' is only a modifier if followed by 'enum'.
29200                     return nextToken() === 91 /* EnumKeyword */;
29201                 case 92 /* ExportKeyword */:
29202                     nextToken();
29203                     if (token() === 87 /* DefaultKeyword */) {
29204                         return lookAhead(nextTokenCanFollowDefaultKeyword);
29205                     }
29206                     if (token() === 149 /* TypeKeyword */) {
29207                         return lookAhead(nextTokenCanFollowExportModifier);
29208                     }
29209                     return canFollowExportModifier();
29210                 case 87 /* DefaultKeyword */:
29211                     return nextTokenCanFollowDefaultKeyword();
29212                 case 123 /* StaticKeyword */:
29213                 case 134 /* GetKeyword */:
29214                 case 146 /* SetKeyword */:
29215                     nextToken();
29216                     return canFollowModifier();
29217                 default:
29218                     return nextTokenIsOnSameLineAndCanFollowModifier();
29219             }
29220         }
29221         function canFollowExportModifier() {
29222             return token() !== 41 /* AsteriskToken */
29223                 && token() !== 126 /* AsKeyword */
29224                 && token() !== 18 /* OpenBraceToken */
29225                 && canFollowModifier();
29226         }
29227         function nextTokenCanFollowExportModifier() {
29228             nextToken();
29229             return canFollowExportModifier();
29230         }
29231         function parseAnyContextualModifier() {
29232             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
29233         }
29234         function canFollowModifier() {
29235             return token() === 22 /* OpenBracketToken */
29236                 || token() === 18 /* OpenBraceToken */
29237                 || token() === 41 /* AsteriskToken */
29238                 || token() === 25 /* DotDotDotToken */
29239                 || isLiteralPropertyName();
29240         }
29241         function nextTokenCanFollowDefaultKeyword() {
29242             nextToken();
29243             return token() === 83 /* ClassKeyword */ || token() === 97 /* FunctionKeyword */ ||
29244                 token() === 117 /* InterfaceKeyword */ ||
29245                 (token() === 125 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
29246                 (token() === 129 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
29247         }
29248         // True if positioned at the start of a list element
29249         function isListElement(parsingContext, inErrorRecovery) {
29250             var node = currentNode(parsingContext);
29251             if (node) {
29252                 return true;
29253             }
29254             switch (parsingContext) {
29255                 case 0 /* SourceElements */:
29256                 case 1 /* BlockStatements */:
29257                 case 3 /* SwitchClauseStatements */:
29258                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
29259                     // The problem is that ';' can show up in far too many contexts, and if we see one
29260                     // and assume it's a statement, then we may bail out inappropriately from whatever
29261                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
29262                     // we really don't want to assume the class is over and we're on a statement in the
29263                     // outer module.  We just want to consume and move on.
29264                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
29265                 case 2 /* SwitchClauses */:
29266                     return token() === 81 /* CaseKeyword */ || token() === 87 /* DefaultKeyword */;
29267                 case 4 /* TypeMembers */:
29268                     return lookAhead(isTypeMemberStart);
29269                 case 5 /* ClassMembers */:
29270                     // We allow semicolons as class elements (as specified by ES6) as long as we're
29271                     // not in error recovery.  If we're in error recovery, we don't want an errant
29272                     // semicolon to be treated as a class member (since they're almost always used
29273                     // for statements.
29274                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
29275                 case 6 /* EnumMembers */:
29276                     // Include open bracket computed properties. This technically also lets in indexers,
29277                     // which would be a candidate for improved error reporting.
29278                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
29279                 case 12 /* ObjectLiteralMembers */:
29280                     switch (token()) {
29281                         case 22 /* OpenBracketToken */:
29282                         case 41 /* AsteriskToken */:
29283                         case 25 /* DotDotDotToken */:
29284                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
29285                             return true;
29286                         default:
29287                             return isLiteralPropertyName();
29288                     }
29289                 case 18 /* RestProperties */:
29290                     return isLiteralPropertyName();
29291                 case 9 /* ObjectBindingElements */:
29292                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
29293                 case 7 /* HeritageClauseElement */:
29294                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
29295                     // That way we won't consume the body of a class in its heritage clause.
29296                     if (token() === 18 /* OpenBraceToken */) {
29297                         return lookAhead(isValidHeritageClauseObjectLiteral);
29298                     }
29299                     if (!inErrorRecovery) {
29300                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
29301                     }
29302                     else {
29303                         // If we're in error recovery we tighten up what we're willing to match.
29304                         // That way we don't treat something like "this" as a valid heritage clause
29305                         // element during recovery.
29306                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
29307                     }
29308                 case 8 /* VariableDeclarations */:
29309                     return isBindingIdentifierOrPrivateIdentifierOrPattern();
29310                 case 10 /* ArrayBindingElements */:
29311                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern();
29312                 case 19 /* TypeParameters */:
29313                     return isIdentifier();
29314                 case 15 /* ArrayLiteralMembers */:
29315                     switch (token()) {
29316                         case 27 /* CommaToken */:
29317                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
29318                             return true;
29319                     }
29320                 // falls through
29321                 case 11 /* ArgumentExpressions */:
29322                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
29323                 case 16 /* Parameters */:
29324                     return isStartOfParameter(/*isJSDocParameter*/ false);
29325                 case 17 /* JSDocParameters */:
29326                     return isStartOfParameter(/*isJSDocParameter*/ true);
29327                 case 20 /* TypeArguments */:
29328                 case 21 /* TupleElementTypes */:
29329                     return token() === 27 /* CommaToken */ || isStartOfType();
29330                 case 22 /* HeritageClauses */:
29331                     return isHeritageClause();
29332                 case 23 /* ImportOrExportSpecifiers */:
29333                     return ts.tokenIsIdentifierOrKeyword(token());
29334                 case 13 /* JsxAttributes */:
29335                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
29336                 case 14 /* JsxChildren */:
29337                     return true;
29338             }
29339             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
29340         }
29341         function isValidHeritageClauseObjectLiteral() {
29342             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
29343             if (nextToken() === 19 /* CloseBraceToken */) {
29344                 // if we see "extends {}" then only treat the {} as what we're extending (and not
29345                 // the class body) if we have:
29346                 //
29347                 //      extends {} {
29348                 //      extends {},
29349                 //      extends {} extends
29350                 //      extends {} implements
29351                 var next = nextToken();
29352                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 93 /* ExtendsKeyword */ || next === 116 /* ImplementsKeyword */;
29353             }
29354             return true;
29355         }
29356         function nextTokenIsIdentifier() {
29357             nextToken();
29358             return isIdentifier();
29359         }
29360         function nextTokenIsIdentifierOrKeyword() {
29361             nextToken();
29362             return ts.tokenIsIdentifierOrKeyword(token());
29363         }
29364         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
29365             nextToken();
29366             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
29367         }
29368         function isHeritageClauseExtendsOrImplementsKeyword() {
29369             if (token() === 116 /* ImplementsKeyword */ ||
29370                 token() === 93 /* ExtendsKeyword */) {
29371                 return lookAhead(nextTokenIsStartOfExpression);
29372             }
29373             return false;
29374         }
29375         function nextTokenIsStartOfExpression() {
29376             nextToken();
29377             return isStartOfExpression();
29378         }
29379         function nextTokenIsStartOfType() {
29380             nextToken();
29381             return isStartOfType();
29382         }
29383         // True if positioned at a list terminator
29384         function isListTerminator(kind) {
29385             if (token() === 1 /* EndOfFileToken */) {
29386                 // Being at the end of the file ends all lists.
29387                 return true;
29388             }
29389             switch (kind) {
29390                 case 1 /* BlockStatements */:
29391                 case 2 /* SwitchClauses */:
29392                 case 4 /* TypeMembers */:
29393                 case 5 /* ClassMembers */:
29394                 case 6 /* EnumMembers */:
29395                 case 12 /* ObjectLiteralMembers */:
29396                 case 9 /* ObjectBindingElements */:
29397                 case 23 /* ImportOrExportSpecifiers */:
29398                     return token() === 19 /* CloseBraceToken */;
29399                 case 3 /* SwitchClauseStatements */:
29400                     return token() === 19 /* CloseBraceToken */ || token() === 81 /* CaseKeyword */ || token() === 87 /* DefaultKeyword */;
29401                 case 7 /* HeritageClauseElement */:
29402                     return token() === 18 /* OpenBraceToken */ || token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
29403                 case 8 /* VariableDeclarations */:
29404                     return isVariableDeclaratorListTerminator();
29405                 case 19 /* TypeParameters */:
29406                     // Tokens other than '>' are here for better error recovery
29407                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
29408                 case 11 /* ArgumentExpressions */:
29409                     // Tokens other than ')' are here for better error recovery
29410                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
29411                 case 15 /* ArrayLiteralMembers */:
29412                 case 21 /* TupleElementTypes */:
29413                 case 10 /* ArrayBindingElements */:
29414                     return token() === 23 /* CloseBracketToken */;
29415                 case 17 /* JSDocParameters */:
29416                 case 16 /* Parameters */:
29417                 case 18 /* RestProperties */:
29418                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
29419                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
29420                 case 20 /* TypeArguments */:
29421                     // All other tokens should cause the type-argument to terminate except comma token
29422                     return token() !== 27 /* CommaToken */;
29423                 case 22 /* HeritageClauses */:
29424                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
29425                 case 13 /* JsxAttributes */:
29426                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
29427                 case 14 /* JsxChildren */:
29428                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
29429                 default:
29430                     return false;
29431             }
29432         }
29433         function isVariableDeclaratorListTerminator() {
29434             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
29435             // with parsing the list of variable declarators.
29436             if (canParseSemicolon()) {
29437                 return true;
29438             }
29439             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
29440             // are done if we see an 'in' keyword in front of us. Same with for-of
29441             if (isInOrOfKeyword(token())) {
29442                 return true;
29443             }
29444             // ERROR RECOVERY TWEAK:
29445             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
29446             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
29447             // another variable declaration.
29448             if (token() === 38 /* EqualsGreaterThanToken */) {
29449                 return true;
29450             }
29451             // Keep trying to parse out variable declarators.
29452             return false;
29453         }
29454         // True if positioned at element or terminator of the current list or any enclosing list
29455         function isInSomeParsingContext() {
29456             for (var kind = 0; kind < 24 /* Count */; kind++) {
29457                 if (parsingContext & (1 << kind)) {
29458                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
29459                         return true;
29460                     }
29461                 }
29462             }
29463             return false;
29464         }
29465         // Parses a list of elements
29466         function parseList(kind, parseElement) {
29467             var saveParsingContext = parsingContext;
29468             parsingContext |= 1 << kind;
29469             var list = [];
29470             var listPos = getNodePos();
29471             while (!isListTerminator(kind)) {
29472                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
29473                     var element = parseListElement(kind, parseElement);
29474                     list.push(element);
29475                     continue;
29476                 }
29477                 if (abortParsingListOrMoveToNextToken(kind)) {
29478                     break;
29479                 }
29480             }
29481             parsingContext = saveParsingContext;
29482             return createNodeArray(list, listPos);
29483         }
29484         function parseListElement(parsingContext, parseElement) {
29485             var node = currentNode(parsingContext);
29486             if (node) {
29487                 return consumeNode(node);
29488             }
29489             return parseElement();
29490         }
29491         function currentNode(parsingContext) {
29492             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
29493             //
29494             // If there is an outstanding parse error that we've encountered, but not attached to
29495             // some node, then we cannot get a node from the old source tree.  This is because we
29496             // want to mark the next node we encounter as being unusable.
29497             //
29498             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
29499             // on it (or its leftmost child) as having the error.  For now though, being conservative
29500             // is nice and likely won't ever affect perf.
29501             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
29502                 return undefined;
29503             }
29504             var node = syntaxCursor.currentNode(scanner.getStartPos());
29505             // Can't reuse a missing node.
29506             // Can't reuse a node that intersected the change range.
29507             // Can't reuse a node that contains a parse error.  This is necessary so that we
29508             // produce the same set of errors again.
29509             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
29510                 return undefined;
29511             }
29512             // We can only reuse a node if it was parsed under the same strict mode that we're
29513             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
29514             // the user added 'using strict' at the top of the file, then we can't use that node
29515             // again as the presence of strict mode may cause us to parse the tokens in the file
29516             // differently.
29517             //
29518             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
29519             // are unaffected by strict mode.  It's just the parser will decide what to do with it
29520             // differently depending on what mode it is in.
29521             //
29522             // This also applies to all our other context flags as well.
29523             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
29524             if (nodeContextFlags !== contextFlags) {
29525                 return undefined;
29526             }
29527             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
29528             // in the current list parsing context that we're currently at.
29529             if (!canReuseNode(node, parsingContext)) {
29530                 return undefined;
29531             }
29532             if (node.jsDocCache) {
29533                 // jsDocCache may include tags from parent nodes, which might have been modified.
29534                 node.jsDocCache = undefined;
29535             }
29536             return node;
29537         }
29538         function consumeNode(node) {
29539             // Move the scanner so it is after the node we just consumed.
29540             scanner.setTextPos(node.end);
29541             nextToken();
29542             return node;
29543         }
29544         function isReusableParsingContext(parsingContext) {
29545             switch (parsingContext) {
29546                 case 5 /* ClassMembers */:
29547                 case 2 /* SwitchClauses */:
29548                 case 0 /* SourceElements */:
29549                 case 1 /* BlockStatements */:
29550                 case 3 /* SwitchClauseStatements */:
29551                 case 6 /* EnumMembers */:
29552                 case 4 /* TypeMembers */:
29553                 case 8 /* VariableDeclarations */:
29554                 case 17 /* JSDocParameters */:
29555                 case 16 /* Parameters */:
29556                     return true;
29557             }
29558             return false;
29559         }
29560         function canReuseNode(node, parsingContext) {
29561             switch (parsingContext) {
29562                 case 5 /* ClassMembers */:
29563                     return isReusableClassMember(node);
29564                 case 2 /* SwitchClauses */:
29565                     return isReusableSwitchClause(node);
29566                 case 0 /* SourceElements */:
29567                 case 1 /* BlockStatements */:
29568                 case 3 /* SwitchClauseStatements */:
29569                     return isReusableStatement(node);
29570                 case 6 /* EnumMembers */:
29571                     return isReusableEnumMember(node);
29572                 case 4 /* TypeMembers */:
29573                     return isReusableTypeMember(node);
29574                 case 8 /* VariableDeclarations */:
29575                     return isReusableVariableDeclaration(node);
29576                 case 17 /* JSDocParameters */:
29577                 case 16 /* Parameters */:
29578                     return isReusableParameter(node);
29579                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
29580                 // you can do so safely.  Danger areas involve nodes that may involve speculative
29581                 // parsing.  If speculative parsing is involved with the node, then the range the
29582                 // parser reached while looking ahead might be in the edited range (see the example
29583                 // in canReuseVariableDeclaratorNode for a good case of this).
29584                 // case ParsingContext.HeritageClauses:
29585                 // This would probably be safe to reuse.  There is no speculative parsing with
29586                 // heritage clauses.
29587                 // case ParsingContext.TypeParameters:
29588                 // This would probably be safe to reuse.  There is no speculative parsing with
29589                 // type parameters.  Note that that's because type *parameters* only occur in
29590                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
29591                 // *expression* contexts.
29592                 // case ParsingContext.TupleElementTypes:
29593                 // This would probably be safe to reuse.  There is no speculative parsing with
29594                 // tuple types.
29595                 // Technically, type argument list types are probably safe to reuse.  While
29596                 // speculative parsing is involved with them (since type argument lists are only
29597                 // produced from speculative parsing a < as a type argument list), we only have
29598                 // the types because speculative parsing succeeded.  Thus, the lookahead never
29599                 // went past the end of the list and rewound.
29600                 // case ParsingContext.TypeArguments:
29601                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
29602                 // need a large amount of lookahead, and we should not reuse them as they may
29603                 // have actually intersected the edit.
29604                 // case ParsingContext.ArgumentExpressions:
29605                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
29606                 // cases.  i.e. a property assignment may end with an expression, and thus might
29607                 // have lookahead far beyond it's old node.
29608                 // case ParsingContext.ObjectLiteralMembers:
29609                 // This is probably not safe to reuse.  There can be speculative parsing with
29610                 // type names in a heritage clause.  There can be generic names in the type
29611                 // name list, and there can be left hand side expressions (which can have type
29612                 // arguments.)
29613                 // case ParsingContext.HeritageClauseElement:
29614                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
29615                 // on any given element. Same for children.
29616                 // case ParsingContext.JsxAttributes:
29617                 // case ParsingContext.JsxChildren:
29618             }
29619             return false;
29620         }
29621         function isReusableClassMember(node) {
29622             if (node) {
29623                 switch (node.kind) {
29624                     case 166 /* Constructor */:
29625                     case 171 /* IndexSignature */:
29626                     case 167 /* GetAccessor */:
29627                     case 168 /* SetAccessor */:
29628                     case 163 /* PropertyDeclaration */:
29629                     case 229 /* SemicolonClassElement */:
29630                         return true;
29631                     case 165 /* MethodDeclaration */:
29632                         // Method declarations are not necessarily reusable.  An object-literal
29633                         // may have a method calls "constructor(...)" and we must reparse that
29634                         // into an actual .ConstructorDeclaration.
29635                         var methodDeclaration = node;
29636                         var nameIsConstructor = methodDeclaration.name.kind === 78 /* Identifier */ &&
29637                             methodDeclaration.name.originalKeywordKind === 132 /* ConstructorKeyword */;
29638                         return !nameIsConstructor;
29639                 }
29640             }
29641             return false;
29642         }
29643         function isReusableSwitchClause(node) {
29644             if (node) {
29645                 switch (node.kind) {
29646                     case 284 /* CaseClause */:
29647                     case 285 /* DefaultClause */:
29648                         return true;
29649                 }
29650             }
29651             return false;
29652         }
29653         function isReusableStatement(node) {
29654             if (node) {
29655                 switch (node.kind) {
29656                     case 251 /* FunctionDeclaration */:
29657                     case 232 /* VariableStatement */:
29658                     case 230 /* Block */:
29659                     case 234 /* IfStatement */:
29660                     case 233 /* ExpressionStatement */:
29661                     case 246 /* ThrowStatement */:
29662                     case 242 /* ReturnStatement */:
29663                     case 244 /* SwitchStatement */:
29664                     case 241 /* BreakStatement */:
29665                     case 240 /* ContinueStatement */:
29666                     case 238 /* ForInStatement */:
29667                     case 239 /* ForOfStatement */:
29668                     case 237 /* ForStatement */:
29669                     case 236 /* WhileStatement */:
29670                     case 243 /* WithStatement */:
29671                     case 231 /* EmptyStatement */:
29672                     case 247 /* TryStatement */:
29673                     case 245 /* LabeledStatement */:
29674                     case 235 /* DoStatement */:
29675                     case 248 /* DebuggerStatement */:
29676                     case 261 /* ImportDeclaration */:
29677                     case 260 /* ImportEqualsDeclaration */:
29678                     case 267 /* ExportDeclaration */:
29679                     case 266 /* ExportAssignment */:
29680                     case 256 /* ModuleDeclaration */:
29681                     case 252 /* ClassDeclaration */:
29682                     case 253 /* InterfaceDeclaration */:
29683                     case 255 /* EnumDeclaration */:
29684                     case 254 /* TypeAliasDeclaration */:
29685                         return true;
29686                 }
29687             }
29688             return false;
29689         }
29690         function isReusableEnumMember(node) {
29691             return node.kind === 291 /* EnumMember */;
29692         }
29693         function isReusableTypeMember(node) {
29694             if (node) {
29695                 switch (node.kind) {
29696                     case 170 /* ConstructSignature */:
29697                     case 164 /* MethodSignature */:
29698                     case 171 /* IndexSignature */:
29699                     case 162 /* PropertySignature */:
29700                     case 169 /* CallSignature */:
29701                         return true;
29702                 }
29703             }
29704             return false;
29705         }
29706         function isReusableVariableDeclaration(node) {
29707             if (node.kind !== 249 /* VariableDeclaration */) {
29708                 return false;
29709             }
29710             // Very subtle incremental parsing bug.  Consider the following code:
29711             //
29712             //      let v = new List < A, B
29713             //
29714             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
29715             // on one side and "B" on the other. If you then change that to:
29716             //
29717             //      let v = new List < A, B >()
29718             //
29719             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
29720             // start reparsing at "B" and we completely fail to handle this properly.
29721             //
29722             // In order to prevent this, we do not allow a variable declarator to be reused if it
29723             // has an initializer.
29724             var variableDeclarator = node;
29725             return variableDeclarator.initializer === undefined;
29726         }
29727         function isReusableParameter(node) {
29728             if (node.kind !== 160 /* Parameter */) {
29729                 return false;
29730             }
29731             // See the comment in isReusableVariableDeclaration for why we do this.
29732             var parameter = node;
29733             return parameter.initializer === undefined;
29734         }
29735         // Returns true if we should abort parsing.
29736         function abortParsingListOrMoveToNextToken(kind) {
29737             parsingContextErrors(kind);
29738             if (isInSomeParsingContext()) {
29739                 return true;
29740             }
29741             nextToken();
29742             return false;
29743         }
29744         function parsingContextErrors(context) {
29745             switch (context) {
29746                 case 0 /* SourceElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected);
29747                 case 1 /* BlockStatements */: return parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected);
29748                 case 2 /* SwitchClauses */: return parseErrorAtCurrentToken(ts.Diagnostics.case_or_default_expected);
29749                 case 3 /* SwitchClauseStatements */: return parseErrorAtCurrentToken(ts.Diagnostics.Statement_expected);
29750                 case 18 /* RestProperties */: // fallthrough
29751                 case 4 /* TypeMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_or_signature_expected);
29752                 case 5 /* ClassMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected);
29753                 case 6 /* EnumMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Enum_member_expected);
29754                 case 7 /* HeritageClauseElement */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_expected);
29755                 case 8 /* VariableDeclarations */:
29756                     return ts.isKeyword(token())
29757                         ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_variable_declaration_name, ts.tokenToString(token()))
29758                         : parseErrorAtCurrentToken(ts.Diagnostics.Variable_declaration_expected);
29759                 case 9 /* ObjectBindingElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_destructuring_pattern_expected);
29760                 case 10 /* ArrayBindingElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Array_element_destructuring_pattern_expected);
29761                 case 11 /* ArgumentExpressions */: return parseErrorAtCurrentToken(ts.Diagnostics.Argument_expression_expected);
29762                 case 12 /* ObjectLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected);
29763                 case 15 /* ArrayLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected);
29764                 case 17 /* JSDocParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected);
29765                 case 16 /* Parameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected);
29766                 case 19 /* TypeParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected);
29767                 case 20 /* TypeArguments */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected);
29768                 case 21 /* TupleElementTypes */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected);
29769                 case 22 /* HeritageClauses */: return parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token_expected);
29770                 case 23 /* ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
29771                 case 13 /* JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
29772                 case 14 /* JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
29773                 default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);`
29774             }
29775         }
29776         // Parses a comma-delimited list of elements
29777         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
29778             var saveParsingContext = parsingContext;
29779             parsingContext |= 1 << kind;
29780             var list = [];
29781             var listPos = getNodePos();
29782             var commaStart = -1; // Meaning the previous token was not a comma
29783             while (true) {
29784                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
29785                     var startPos = scanner.getStartPos();
29786                     list.push(parseListElement(kind, parseElement));
29787                     commaStart = scanner.getTokenPos();
29788                     if (parseOptional(27 /* CommaToken */)) {
29789                         // No need to check for a zero length node since we know we parsed a comma
29790                         continue;
29791                     }
29792                     commaStart = -1; // Back to the state where the last token was not a comma
29793                     if (isListTerminator(kind)) {
29794                         break;
29795                     }
29796                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
29797                     // out a comma so we give a good error message.
29798                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
29799                     // If the token was a semicolon, and the caller allows that, then skip it and
29800                     // continue.  This ensures we get back on track and don't result in tons of
29801                     // parse errors.  For example, this can happen when people do things like use
29802                     // a semicolon to delimit object literal members.   Note: we'll have already
29803                     // reported an error when we called parseExpected above.
29804                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
29805                         nextToken();
29806                     }
29807                     if (startPos === scanner.getStartPos()) {
29808                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
29809                         // Consume a token to advance the parser in some way and avoid an infinite loop
29810                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
29811                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
29812                         nextToken();
29813                     }
29814                     continue;
29815                 }
29816                 if (isListTerminator(kind)) {
29817                     break;
29818                 }
29819                 if (abortParsingListOrMoveToNextToken(kind)) {
29820                     break;
29821                 }
29822             }
29823             parsingContext = saveParsingContext;
29824             // Recording the trailing comma is deliberately done after the previous
29825             // loop, and not just if we see a list terminator. This is because the list
29826             // may have ended incorrectly, but it is still important to know if there
29827             // was a trailing comma.
29828             // Check if the last token was a comma.
29829             // Always preserve a trailing comma by marking it on the NodeArray
29830             return createNodeArray(list, listPos, /*end*/ undefined, commaStart >= 0);
29831         }
29832         function getExpectedCommaDiagnostic(kind) {
29833             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
29834         }
29835         function createMissingList() {
29836             var list = createNodeArray([], getNodePos());
29837             list.isMissingList = true;
29838             return list;
29839         }
29840         function isMissingList(arr) {
29841             return !!arr.isMissingList;
29842         }
29843         function parseBracketedList(kind, parseElement, open, close) {
29844             if (parseExpected(open)) {
29845                 var result = parseDelimitedList(kind, parseElement);
29846                 parseExpected(close);
29847                 return result;
29848             }
29849             return createMissingList();
29850         }
29851         function parseEntityName(allowReservedWords, diagnosticMessage) {
29852             var pos = getNodePos();
29853             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
29854             var dotPos = getNodePos();
29855             while (parseOptional(24 /* DotToken */)) {
29856                 if (token() === 29 /* LessThanToken */) {
29857                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
29858                     entity.jsdocDotPos = dotPos;
29859                     break;
29860                 }
29861                 dotPos = getNodePos();
29862                 entity = finishNode(factory.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false)), pos);
29863             }
29864             return entity;
29865         }
29866         function createQualifiedName(entity, name) {
29867             return finishNode(factory.createQualifiedName(entity, name), entity.pos);
29868         }
29869         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
29870             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
29871             // However, often we'll encounter this in error situations when the identifier or keyword
29872             // is actually starting another valid construct.
29873             //
29874             // So, we check for the following specific case:
29875             //
29876             //      name.
29877             //      identifierOrKeyword identifierNameOrKeyword
29878             //
29879             // Note: the newlines are important here.  For example, if that above code
29880             // were rewritten into:
29881             //
29882             //      name.identifierOrKeyword
29883             //      identifierNameOrKeyword
29884             //
29885             // Then we would consider it valid.  That's because ASI would take effect and
29886             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
29887             // In the first case though, ASI will not take effect because there is not a
29888             // line terminator after the identifier or keyword.
29889             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
29890                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
29891                 if (matchesPattern) {
29892                     // Report that we need an identifier.  However, report it right after the dot,
29893                     // and not on the next token.  This is because the next token might actually
29894                     // be an identifier and the error would be quite confusing.
29895                     return createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
29896                 }
29897             }
29898             if (token() === 79 /* PrivateIdentifier */) {
29899                 var node = parsePrivateIdentifier();
29900                 return allowPrivateIdentifiers ? node : createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
29901             }
29902             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
29903         }
29904         function parseTemplateSpans(isTaggedTemplate) {
29905             var pos = getNodePos();
29906             var list = [];
29907             var node;
29908             do {
29909                 node = parseTemplateSpan(isTaggedTemplate);
29910                 list.push(node);
29911             } while (node.literal.kind === 16 /* TemplateMiddle */);
29912             return createNodeArray(list, pos);
29913         }
29914         function parseTemplateExpression(isTaggedTemplate) {
29915             var pos = getNodePos();
29916             return finishNode(factory.createTemplateExpression(parseTemplateHead(isTaggedTemplate), parseTemplateSpans(isTaggedTemplate)), pos);
29917         }
29918         function parseTemplateType() {
29919             var pos = getNodePos();
29920             return finishNode(factory.createTemplateLiteralType(parseTemplateHead(/*isTaggedTemplate*/ false), parseTemplateTypeSpans()), pos);
29921         }
29922         function parseTemplateTypeSpans() {
29923             var pos = getNodePos();
29924             var list = [];
29925             var node;
29926             do {
29927                 node = parseTemplateTypeSpan();
29928                 list.push(node);
29929             } while (node.literal.kind === 16 /* TemplateMiddle */);
29930             return createNodeArray(list, pos);
29931         }
29932         function parseTemplateTypeSpan() {
29933             var pos = getNodePos();
29934             return finishNode(factory.createTemplateLiteralTypeSpan(parseType(), parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false)), pos);
29935         }
29936         function parseLiteralOfTemplateSpan(isTaggedTemplate) {
29937             if (token() === 19 /* CloseBraceToken */) {
29938                 reScanTemplateToken(isTaggedTemplate);
29939                 return parseTemplateMiddleOrTemplateTail();
29940             }
29941             else {
29942                 // TODO(rbuckton): Do we need to call `parseExpectedToken` or can we just call `createMissingNode` directly?
29943                 return parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
29944             }
29945         }
29946         function parseTemplateSpan(isTaggedTemplate) {
29947             var pos = getNodePos();
29948             return finishNode(factory.createTemplateSpan(allowInAnd(parseExpression), parseLiteralOfTemplateSpan(isTaggedTemplate)), pos);
29949         }
29950         function parseLiteralNode() {
29951             return parseLiteralLikeNode(token());
29952         }
29953         function parseTemplateHead(isTaggedTemplate) {
29954             if (isTaggedTemplate) {
29955                 reScanTemplateHeadOrNoSubstitutionTemplate();
29956             }
29957             var fragment = parseLiteralLikeNode(token());
29958             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
29959             return fragment;
29960         }
29961         function parseTemplateMiddleOrTemplateTail() {
29962             var fragment = parseLiteralLikeNode(token());
29963             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
29964             return fragment;
29965         }
29966         function getTemplateLiteralRawText(kind) {
29967             var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
29968             var tokenText = scanner.getTokenText();
29969             return tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
29970         }
29971         function parseLiteralLikeNode(kind) {
29972             var pos = getNodePos();
29973             var node = ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & 2048 /* TemplateLiteralLikeFlags */) :
29974                 // Octal literals are not allowed in strict mode or ES5
29975                 // Note that theoretically the following condition would hold true literals like 009,
29976                 // which is not octal. But because of how the scanner separates the tokens, we would
29977                 // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
29978                 // We also do not need to check for negatives because any prefix operator would be part of a
29979                 // parent unary expression.
29980                 kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) :
29981                     kind === 10 /* StringLiteral */ ? factory.createStringLiteral(scanner.getTokenValue(), /*isSingleQuote*/ undefined, scanner.hasExtendedUnicodeEscape()) :
29982                         ts.isLiteralKind(kind) ? factory.createLiteralLikeNode(kind, scanner.getTokenValue()) :
29983                             ts.Debug.fail();
29984             if (scanner.hasExtendedUnicodeEscape()) {
29985                 node.hasExtendedUnicodeEscape = true;
29986             }
29987             if (scanner.isUnterminated()) {
29988                 node.isUnterminated = true;
29989             }
29990             nextToken();
29991             return finishNode(node, pos);
29992         }
29993         // TYPES
29994         function parseEntityNameOfTypeReference() {
29995             return parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
29996         }
29997         function parseTypeArgumentsOfTypeReference() {
29998             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
29999                 return parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
30000             }
30001         }
30002         function parseTypeReference() {
30003             var pos = getNodePos();
30004             return finishNode(factory.createTypeReferenceNode(parseEntityNameOfTypeReference(), parseTypeArgumentsOfTypeReference()), pos);
30005         }
30006         // If true, we should abort parsing an error function.
30007         function typeHasArrowFunctionBlockingParseError(node) {
30008             switch (node.kind) {
30009                 case 173 /* TypeReference */:
30010                     return ts.nodeIsMissing(node.typeName);
30011                 case 174 /* FunctionType */:
30012                 case 175 /* ConstructorType */: {
30013                     var _a = node, parameters = _a.parameters, type = _a.type;
30014                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
30015                 }
30016                 case 186 /* ParenthesizedType */:
30017                     return typeHasArrowFunctionBlockingParseError(node.type);
30018                 default:
30019                     return false;
30020             }
30021         }
30022         function parseThisTypePredicate(lhs) {
30023             nextToken();
30024             return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, lhs, parseType()), lhs.pos);
30025         }
30026         function parseThisTypeNode() {
30027             var pos = getNodePos();
30028             nextToken();
30029             return finishNode(factory.createThisTypeNode(), pos);
30030         }
30031         function parseJSDocAllType() {
30032             var pos = getNodePos();
30033             nextToken();
30034             return finishNode(factory.createJSDocAllType(), pos);
30035         }
30036         function parseJSDocNonNullableType() {
30037             var pos = getNodePos();
30038             nextToken();
30039             return finishNode(factory.createJSDocNonNullableType(parseNonArrayType()), pos);
30040         }
30041         function parseJSDocUnknownOrNullableType() {
30042             var pos = getNodePos();
30043             // skip the ?
30044             nextToken();
30045             // Need to lookahead to decide if this is a nullable or unknown type.
30046             // Here are cases where we'll pick the unknown type:
30047             //
30048             //      Foo(?,
30049             //      { a: ? }
30050             //      Foo(?)
30051             //      Foo<?>
30052             //      Foo(?=
30053             //      (?|
30054             if (token() === 27 /* CommaToken */ ||
30055                 token() === 19 /* CloseBraceToken */ ||
30056                 token() === 21 /* CloseParenToken */ ||
30057                 token() === 31 /* GreaterThanToken */ ||
30058                 token() === 62 /* EqualsToken */ ||
30059                 token() === 51 /* BarToken */) {
30060                 return finishNode(factory.createJSDocUnknownType(), pos);
30061             }
30062             else {
30063                 return finishNode(factory.createJSDocNullableType(parseType()), pos);
30064             }
30065         }
30066         function parseJSDocFunctionType() {
30067             var pos = getNodePos();
30068             var hasJSDoc = hasPrecedingJSDocComment();
30069             if (lookAhead(nextTokenIsOpenParen)) {
30070                 nextToken();
30071                 var parameters = parseParameters(4 /* Type */ | 32 /* JSDoc */);
30072                 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
30073                 return withJSDoc(finishNode(factory.createJSDocFunctionType(parameters, type), pos), hasJSDoc);
30074             }
30075             return finishNode(factory.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ undefined), pos);
30076         }
30077         function parseJSDocParameter() {
30078             var pos = getNodePos();
30079             var name;
30080             if (token() === 107 /* ThisKeyword */ || token() === 102 /* NewKeyword */) {
30081                 name = parseIdentifierName();
30082                 parseExpected(58 /* ColonToken */);
30083             }
30084             return finishNode(factory.createParameterDeclaration(
30085             /*decorators*/ undefined, 
30086             /*modifiers*/ undefined, 
30087             /*dotDotDotToken*/ undefined, 
30088             // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier?
30089             name, 
30090             /*questionToken*/ undefined, parseJSDocType(), 
30091             /*initializer*/ undefined), pos);
30092         }
30093         function parseJSDocType() {
30094             scanner.setInJSDocType(true);
30095             var pos = getNodePos();
30096             if (parseOptional(139 /* ModuleKeyword */)) {
30097                 // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here?
30098                 var moduleTag = factory.createJSDocNamepathType(/*type*/ undefined);
30099                 terminate: while (true) {
30100                     switch (token()) {
30101                         case 19 /* CloseBraceToken */:
30102                         case 1 /* EndOfFileToken */:
30103                         case 27 /* CommaToken */:
30104                         case 5 /* WhitespaceTrivia */:
30105                             break terminate;
30106                         default:
30107                             nextTokenJSDoc();
30108                     }
30109                 }
30110                 scanner.setInJSDocType(false);
30111                 return finishNode(moduleTag, pos);
30112             }
30113             var hasDotDotDot = parseOptional(25 /* DotDotDotToken */);
30114             var type = parseTypeOrTypePredicate();
30115             scanner.setInJSDocType(false);
30116             if (hasDotDotDot) {
30117                 type = finishNode(factory.createJSDocVariadicType(type), pos);
30118             }
30119             if (token() === 62 /* EqualsToken */) {
30120                 nextToken();
30121                 return finishNode(factory.createJSDocOptionalType(type), pos);
30122             }
30123             return type;
30124         }
30125         function parseTypeQuery() {
30126             var pos = getNodePos();
30127             parseExpected(111 /* TypeOfKeyword */);
30128             return finishNode(factory.createTypeQueryNode(parseEntityName(/*allowReservedWords*/ true)), pos);
30129         }
30130         function parseTypeParameter() {
30131             var pos = getNodePos();
30132             var name = parseIdentifier();
30133             var constraint;
30134             var expression;
30135             if (parseOptional(93 /* ExtendsKeyword */)) {
30136                 // It's not uncommon for people to write improper constraints to a generic.  If the
30137                 // user writes a constraint that is an expression and not an actual type, then parse
30138                 // it out as an expression (so we can recover well), but report that a type is needed
30139                 // instead.
30140                 if (isStartOfType() || !isStartOfExpression()) {
30141                     constraint = parseType();
30142                 }
30143                 else {
30144                     // It was not a type, and it looked like an expression.  Parse out an expression
30145                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
30146                     // and not parseExpression here.  If the user has:
30147                     //
30148                     //      <T extends "">
30149                     //
30150                     // We do *not* want to consume the `>` as we're consuming the expression for "".
30151                     expression = parseUnaryExpressionOrHigher();
30152                 }
30153             }
30154             var defaultType = parseOptional(62 /* EqualsToken */) ? parseType() : undefined;
30155             var node = factory.createTypeParameterDeclaration(name, constraint, defaultType);
30156             node.expression = expression;
30157             return finishNode(node, pos);
30158         }
30159         function parseTypeParameters() {
30160             if (token() === 29 /* LessThanToken */) {
30161                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
30162             }
30163         }
30164         function isStartOfParameter(isJSDocParameter) {
30165             return token() === 25 /* DotDotDotToken */ ||
30166                 isBindingIdentifierOrPrivateIdentifierOrPattern() ||
30167                 ts.isModifierKind(token()) ||
30168                 token() === 59 /* AtToken */ ||
30169                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
30170         }
30171         function parseNameOfParameter(modifiers) {
30172             // FormalParameter [Yield,Await]:
30173             //      BindingElement[?Yield,?Await]
30174             var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
30175             if (ts.getFullWidth(name) === 0 && !ts.some(modifiers) && ts.isModifierKind(token())) {
30176                 // in cases like
30177                 // 'use strict'
30178                 // function foo(static)
30179                 // isParameter('static') === true, because of isModifier('static')
30180                 // however 'static' is not a legal identifier in a strict mode.
30181                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
30182                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
30183                 // to avoid this we'll advance cursor to the next token.
30184                 nextToken();
30185             }
30186             return name;
30187         }
30188         function parseParameterInOuterAwaitContext() {
30189             return parseParameterWorker(/*inOuterAwaitContext*/ true);
30190         }
30191         function parseParameter() {
30192             return parseParameterWorker(/*inOuterAwaitContext*/ false);
30193         }
30194         function parseParameterWorker(inOuterAwaitContext) {
30195             var pos = getNodePos();
30196             var hasJSDoc = hasPrecedingJSDocComment();
30197             if (token() === 107 /* ThisKeyword */) {
30198                 var node_1 = factory.createParameterDeclaration(
30199                 /*decorators*/ undefined, 
30200                 /*modifiers*/ undefined, 
30201                 /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), 
30202                 /*questionToken*/ undefined, parseTypeAnnotation(), 
30203                 /*initializer*/ undefined);
30204                 return withJSDoc(finishNode(node_1, pos), hasJSDoc);
30205             }
30206             // FormalParameter [Yield,Await]:
30207             //      BindingElement[?Yield,?Await]
30208             // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context.
30209             var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators();
30210             var savedTopLevel = topLevel;
30211             topLevel = false;
30212             var modifiers = parseModifiers();
30213             var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, parseOptionalToken(25 /* DotDotDotToken */), parseNameOfParameter(modifiers), parseOptionalToken(57 /* QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc);
30214             topLevel = savedTopLevel;
30215             return node;
30216         }
30217         function parseReturnType(returnToken, isType) {
30218             if (shouldParseReturnType(returnToken, isType)) {
30219                 return parseTypeOrTypePredicate();
30220             }
30221         }
30222         function shouldParseReturnType(returnToken, isType) {
30223             if (returnToken === 38 /* EqualsGreaterThanToken */) {
30224                 parseExpected(returnToken);
30225                 return true;
30226             }
30227             else if (parseOptional(58 /* ColonToken */)) {
30228                 return true;
30229             }
30230             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
30231                 // This is easy to get backward, especially in type contexts, so parse the type anyway
30232                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
30233                 nextToken();
30234                 return true;
30235             }
30236             return false;
30237         }
30238         function parseParametersWorker(flags) {
30239             // FormalParameters [Yield,Await]: (modified)
30240             //      [empty]
30241             //      FormalParameterList[?Yield,Await]
30242             //
30243             // FormalParameter[Yield,Await]: (modified)
30244             //      BindingElement[?Yield,Await]
30245             //
30246             // BindingElement [Yield,Await]: (modified)
30247             //      SingleNameBinding[?Yield,?Await]
30248             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30249             //
30250             // SingleNameBinding [Yield,Await]:
30251             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30252             var savedYieldContext = inYieldContext();
30253             var savedAwaitContext = inAwaitContext();
30254             setYieldContext(!!(flags & 1 /* Yield */));
30255             setAwaitContext(!!(flags & 2 /* Await */));
30256             var parameters = flags & 32 /* JSDoc */ ?
30257                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
30258                 parseDelimitedList(16 /* Parameters */, savedAwaitContext ? parseParameterInOuterAwaitContext : parseParameter);
30259             setYieldContext(savedYieldContext);
30260             setAwaitContext(savedAwaitContext);
30261             return parameters;
30262         }
30263         function parseParameters(flags) {
30264             // FormalParameters [Yield,Await]: (modified)
30265             //      [empty]
30266             //      FormalParameterList[?Yield,Await]
30267             //
30268             // FormalParameter[Yield,Await]: (modified)
30269             //      BindingElement[?Yield,Await]
30270             //
30271             // BindingElement [Yield,Await]: (modified)
30272             //      SingleNameBinding[?Yield,?Await]
30273             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30274             //
30275             // SingleNameBinding [Yield,Await]:
30276             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30277             if (!parseExpected(20 /* OpenParenToken */)) {
30278                 return createMissingList();
30279             }
30280             var parameters = parseParametersWorker(flags);
30281             parseExpected(21 /* CloseParenToken */);
30282             return parameters;
30283         }
30284         function parseTypeMemberSemicolon() {
30285             // We allow type members to be separated by commas or (possibly ASI) semicolons.
30286             // First check if it was a comma.  If so, we're done with the member.
30287             if (parseOptional(27 /* CommaToken */)) {
30288                 return;
30289             }
30290             // Didn't have a comma.  We must have a (possible ASI) semicolon.
30291             parseSemicolon();
30292         }
30293         function parseSignatureMember(kind) {
30294             var pos = getNodePos();
30295             var hasJSDoc = hasPrecedingJSDocComment();
30296             if (kind === 170 /* ConstructSignature */) {
30297                 parseExpected(102 /* NewKeyword */);
30298             }
30299             var typeParameters = parseTypeParameters();
30300             var parameters = parseParameters(4 /* Type */);
30301             var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
30302             parseTypeMemberSemicolon();
30303             var node = kind === 169 /* CallSignature */
30304                 ? factory.createCallSignature(typeParameters, parameters, type)
30305                 : factory.createConstructSignature(typeParameters, parameters, type);
30306             return withJSDoc(finishNode(node, pos), hasJSDoc);
30307         }
30308         function isIndexSignature() {
30309             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
30310         }
30311         function isUnambiguouslyIndexSignature() {
30312             // The only allowed sequence is:
30313             //
30314             //   [id:
30315             //
30316             // However, for error recovery, we also check the following cases:
30317             //
30318             //   [...
30319             //   [id,
30320             //   [id?,
30321             //   [id?:
30322             //   [id?]
30323             //   [public id
30324             //   [private id
30325             //   [protected id
30326             //   []
30327             //
30328             nextToken();
30329             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
30330                 return true;
30331             }
30332             if (ts.isModifierKind(token())) {
30333                 nextToken();
30334                 if (isIdentifier()) {
30335                     return true;
30336                 }
30337             }
30338             else if (!isIdentifier()) {
30339                 return false;
30340             }
30341             else {
30342                 // Skip the identifier
30343                 nextToken();
30344             }
30345             // A colon signifies a well formed indexer
30346             // A comma should be a badly formed indexer because comma expressions are not allowed
30347             // in computed properties.
30348             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
30349                 return true;
30350             }
30351             // Question mark could be an indexer with an optional property,
30352             // or it could be a conditional expression in a computed property.
30353             if (token() !== 57 /* QuestionToken */) {
30354                 return false;
30355             }
30356             // If any of the following tokens are after the question mark, it cannot
30357             // be a conditional expression, so treat it as an indexer.
30358             nextToken();
30359             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
30360         }
30361         function parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers) {
30362             var parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
30363             var type = parseTypeAnnotation();
30364             parseTypeMemberSemicolon();
30365             var node = factory.createIndexSignature(decorators, modifiers, parameters, type);
30366             return withJSDoc(finishNode(node, pos), hasJSDoc);
30367         }
30368         function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) {
30369             var name = parsePropertyName();
30370             var questionToken = parseOptionalToken(57 /* QuestionToken */);
30371             var node;
30372             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
30373                 // Method signatures don't exist in expression contexts.  So they have neither
30374                 // [Yield] nor [Await]
30375                 var typeParameters = parseTypeParameters();
30376                 var parameters = parseParameters(4 /* Type */);
30377                 var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
30378                 node = factory.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type);
30379             }
30380             else {
30381                 var type = parseTypeAnnotation();
30382                 node = factory.createPropertySignature(modifiers, name, questionToken, type);
30383                 // Although type literal properties cannot not have initializers, we attempt
30384                 // to parse an initializer so we can report in the checker that an interface
30385                 // property or type literal property cannot have an initializer.
30386                 if (token() === 62 /* EqualsToken */)
30387                     node.initializer = parseInitializer();
30388             }
30389             parseTypeMemberSemicolon();
30390             return withJSDoc(finishNode(node, pos), hasJSDoc);
30391         }
30392         function isTypeMemberStart() {
30393             // Return true if we have the start of a signature member
30394             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
30395                 return true;
30396             }
30397             var idToken = false;
30398             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
30399             while (ts.isModifierKind(token())) {
30400                 idToken = true;
30401                 nextToken();
30402             }
30403             // Index signatures and computed property names are type members
30404             if (token() === 22 /* OpenBracketToken */) {
30405                 return true;
30406             }
30407             // Try to get the first property-like token following all modifiers
30408             if (isLiteralPropertyName()) {
30409                 idToken = true;
30410                 nextToken();
30411             }
30412             // If we were able to get any potential identifier, check that it is
30413             // the start of a member declaration
30414             if (idToken) {
30415                 return token() === 20 /* OpenParenToken */ ||
30416                     token() === 29 /* LessThanToken */ ||
30417                     token() === 57 /* QuestionToken */ ||
30418                     token() === 58 /* ColonToken */ ||
30419                     token() === 27 /* CommaToken */ ||
30420                     canParseSemicolon();
30421             }
30422             return false;
30423         }
30424         function parseTypeMember() {
30425             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
30426                 return parseSignatureMember(169 /* CallSignature */);
30427             }
30428             if (token() === 102 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
30429                 return parseSignatureMember(170 /* ConstructSignature */);
30430             }
30431             var pos = getNodePos();
30432             var hasJSDoc = hasPrecedingJSDocComment();
30433             var modifiers = parseModifiers();
30434             if (isIndexSignature()) {
30435                 return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers);
30436             }
30437             return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers);
30438         }
30439         function nextTokenIsOpenParenOrLessThan() {
30440             nextToken();
30441             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
30442         }
30443         function nextTokenIsDot() {
30444             return nextToken() === 24 /* DotToken */;
30445         }
30446         function nextTokenIsOpenParenOrLessThanOrDot() {
30447             switch (nextToken()) {
30448                 case 20 /* OpenParenToken */:
30449                 case 29 /* LessThanToken */:
30450                 case 24 /* DotToken */:
30451                     return true;
30452             }
30453             return false;
30454         }
30455         function parseTypeLiteral() {
30456             var pos = getNodePos();
30457             return finishNode(factory.createTypeLiteralNode(parseObjectTypeMembers()), pos);
30458         }
30459         function parseObjectTypeMembers() {
30460             var members;
30461             if (parseExpected(18 /* OpenBraceToken */)) {
30462                 members = parseList(4 /* TypeMembers */, parseTypeMember);
30463                 parseExpected(19 /* CloseBraceToken */);
30464             }
30465             else {
30466                 members = createMissingList();
30467             }
30468             return members;
30469         }
30470         function isStartOfMappedType() {
30471             nextToken();
30472             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
30473                 return nextToken() === 142 /* ReadonlyKeyword */;
30474             }
30475             if (token() === 142 /* ReadonlyKeyword */) {
30476                 nextToken();
30477             }
30478             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 100 /* InKeyword */;
30479         }
30480         function parseMappedTypeParameter() {
30481             var pos = getNodePos();
30482             var name = parseIdentifierName();
30483             parseExpected(100 /* InKeyword */);
30484             var type = parseType();
30485             return finishNode(factory.createTypeParameterDeclaration(name, type, /*defaultType*/ undefined), pos);
30486         }
30487         function parseMappedType() {
30488             var pos = getNodePos();
30489             parseExpected(18 /* OpenBraceToken */);
30490             var readonlyToken;
30491             if (token() === 142 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
30492                 readonlyToken = parseTokenNode();
30493                 if (readonlyToken.kind !== 142 /* ReadonlyKeyword */) {
30494                     parseExpected(142 /* ReadonlyKeyword */);
30495                 }
30496             }
30497             parseExpected(22 /* OpenBracketToken */);
30498             var typeParameter = parseMappedTypeParameter();
30499             var nameType = parseOptional(126 /* AsKeyword */) ? parseType() : undefined;
30500             parseExpected(23 /* CloseBracketToken */);
30501             var questionToken;
30502             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
30503                 questionToken = parseTokenNode();
30504                 if (questionToken.kind !== 57 /* QuestionToken */) {
30505                     parseExpected(57 /* QuestionToken */);
30506                 }
30507             }
30508             var type = parseTypeAnnotation();
30509             parseSemicolon();
30510             parseExpected(19 /* CloseBraceToken */);
30511             return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos);
30512         }
30513         function parseTupleElementType() {
30514             var pos = getNodePos();
30515             if (parseOptional(25 /* DotDotDotToken */)) {
30516                 return finishNode(factory.createRestTypeNode(parseType()), pos);
30517             }
30518             var type = parseType();
30519             if (ts.isJSDocNullableType(type) && type.pos === type.type.pos) {
30520                 var node = factory.createOptionalTypeNode(type.type);
30521                 ts.setTextRange(node, type);
30522                 node.flags = type.flags;
30523                 return node;
30524             }
30525             return type;
30526         }
30527         function isNextTokenColonOrQuestionColon() {
30528             return nextToken() === 58 /* ColonToken */ || (token() === 57 /* QuestionToken */ && nextToken() === 58 /* ColonToken */);
30529         }
30530         function isTupleElementName() {
30531             if (token() === 25 /* DotDotDotToken */) {
30532                 return ts.tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon();
30533             }
30534             return ts.tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon();
30535         }
30536         function parseTupleElementNameOrTupleElementType() {
30537             if (lookAhead(isTupleElementName)) {
30538                 var pos = getNodePos();
30539                 var hasJSDoc = hasPrecedingJSDocComment();
30540                 var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
30541                 var name = parseIdentifierName();
30542                 var questionToken = parseOptionalToken(57 /* QuestionToken */);
30543                 parseExpected(58 /* ColonToken */);
30544                 var type = parseTupleElementType();
30545                 var node = factory.createNamedTupleMember(dotDotDotToken, name, questionToken, type);
30546                 return withJSDoc(finishNode(node, pos), hasJSDoc);
30547             }
30548             return parseTupleElementType();
30549         }
30550         function parseTupleType() {
30551             var pos = getNodePos();
30552             return finishNode(factory.createTupleTypeNode(parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */)), pos);
30553         }
30554         function parseParenthesizedType() {
30555             var pos = getNodePos();
30556             parseExpected(20 /* OpenParenToken */);
30557             var type = parseType();
30558             parseExpected(21 /* CloseParenToken */);
30559             return finishNode(factory.createParenthesizedType(type), pos);
30560         }
30561         function parseFunctionOrConstructorType() {
30562             var pos = getNodePos();
30563             var hasJSDoc = hasPrecedingJSDocComment();
30564             var isConstructorType = parseOptional(102 /* NewKeyword */);
30565             var typeParameters = parseTypeParameters();
30566             var parameters = parseParameters(4 /* Type */);
30567             var type = parseReturnType(38 /* EqualsGreaterThanToken */, /*isType*/ false);
30568             var node = isConstructorType
30569                 ? factory.createConstructorTypeNode(typeParameters, parameters, type)
30570                 : factory.createFunctionTypeNode(typeParameters, parameters, type);
30571             return withJSDoc(finishNode(node, pos), hasJSDoc);
30572         }
30573         function parseKeywordAndNoDot() {
30574             var node = parseTokenNode();
30575             return token() === 24 /* DotToken */ ? undefined : node;
30576         }
30577         function parseLiteralTypeNode(negative) {
30578             var pos = getNodePos();
30579             if (negative) {
30580                 nextToken();
30581             }
30582             var expression = token() === 109 /* TrueKeyword */ || token() === 94 /* FalseKeyword */ || token() === 103 /* NullKeyword */ ?
30583                 parseTokenNode() :
30584                 parseLiteralLikeNode(token());
30585             if (negative) {
30586                 expression = finishNode(factory.createPrefixUnaryExpression(40 /* MinusToken */, expression), pos);
30587             }
30588             return finishNode(factory.createLiteralTypeNode(expression), pos);
30589         }
30590         function isStartOfTypeOfImportType() {
30591             nextToken();
30592             return token() === 99 /* ImportKeyword */;
30593         }
30594         function parseImportType() {
30595             sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
30596             var pos = getNodePos();
30597             var isTypeOf = parseOptional(111 /* TypeOfKeyword */);
30598             parseExpected(99 /* ImportKeyword */);
30599             parseExpected(20 /* OpenParenToken */);
30600             var type = parseType();
30601             parseExpected(21 /* CloseParenToken */);
30602             var qualifier = parseOptional(24 /* DotToken */) ? parseEntityNameOfTypeReference() : undefined;
30603             var typeArguments = parseTypeArgumentsOfTypeReference();
30604             return finishNode(factory.createImportTypeNode(type, qualifier, typeArguments, isTypeOf), pos);
30605         }
30606         function nextTokenIsNumericOrBigIntLiteral() {
30607             nextToken();
30608             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
30609         }
30610         function parseNonArrayType() {
30611             switch (token()) {
30612                 case 128 /* AnyKeyword */:
30613                 case 152 /* UnknownKeyword */:
30614                 case 147 /* StringKeyword */:
30615                 case 144 /* NumberKeyword */:
30616                 case 155 /* BigIntKeyword */:
30617                 case 148 /* SymbolKeyword */:
30618                 case 131 /* BooleanKeyword */:
30619                 case 150 /* UndefinedKeyword */:
30620                 case 141 /* NeverKeyword */:
30621                 case 145 /* ObjectKeyword */:
30622                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
30623                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
30624                 case 65 /* AsteriskEqualsToken */:
30625                     // If there is '*=', treat it as * followed by postfix =
30626                     scanner.reScanAsteriskEqualsToken();
30627                 // falls through
30628                 case 41 /* AsteriskToken */:
30629                     return parseJSDocAllType();
30630                 case 60 /* QuestionQuestionToken */:
30631                     // If there is '??', treat it as prefix-'?' in JSDoc type.
30632                     scanner.reScanQuestionToken();
30633                 // falls through
30634                 case 57 /* QuestionToken */:
30635                     return parseJSDocUnknownOrNullableType();
30636                 case 97 /* FunctionKeyword */:
30637                     return parseJSDocFunctionType();
30638                 case 53 /* ExclamationToken */:
30639                     return parseJSDocNonNullableType();
30640                 case 14 /* NoSubstitutionTemplateLiteral */:
30641                 case 10 /* StringLiteral */:
30642                 case 8 /* NumericLiteral */:
30643                 case 9 /* BigIntLiteral */:
30644                 case 109 /* TrueKeyword */:
30645                 case 94 /* FalseKeyword */:
30646                 case 103 /* NullKeyword */:
30647                     return parseLiteralTypeNode();
30648                 case 40 /* MinusToken */:
30649                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
30650                 case 113 /* VoidKeyword */:
30651                     return parseTokenNode();
30652                 case 107 /* ThisKeyword */: {
30653                     var thisKeyword = parseThisTypeNode();
30654                     if (token() === 137 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
30655                         return parseThisTypePredicate(thisKeyword);
30656                     }
30657                     else {
30658                         return thisKeyword;
30659                     }
30660                 }
30661                 case 111 /* TypeOfKeyword */:
30662                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
30663                 case 18 /* OpenBraceToken */:
30664                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
30665                 case 22 /* OpenBracketToken */:
30666                     return parseTupleType();
30667                 case 20 /* OpenParenToken */:
30668                     return parseParenthesizedType();
30669                 case 99 /* ImportKeyword */:
30670                     return parseImportType();
30671                 case 127 /* AssertsKeyword */:
30672                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
30673                 case 15 /* TemplateHead */:
30674                     return parseTemplateType();
30675                 default:
30676                     return parseTypeReference();
30677             }
30678         }
30679         function isStartOfType(inStartOfParameter) {
30680             switch (token()) {
30681                 case 128 /* AnyKeyword */:
30682                 case 152 /* UnknownKeyword */:
30683                 case 147 /* StringKeyword */:
30684                 case 144 /* NumberKeyword */:
30685                 case 155 /* BigIntKeyword */:
30686                 case 131 /* BooleanKeyword */:
30687                 case 142 /* ReadonlyKeyword */:
30688                 case 148 /* SymbolKeyword */:
30689                 case 151 /* UniqueKeyword */:
30690                 case 113 /* VoidKeyword */:
30691                 case 150 /* UndefinedKeyword */:
30692                 case 103 /* NullKeyword */:
30693                 case 107 /* ThisKeyword */:
30694                 case 111 /* TypeOfKeyword */:
30695                 case 141 /* NeverKeyword */:
30696                 case 18 /* OpenBraceToken */:
30697                 case 22 /* OpenBracketToken */:
30698                 case 29 /* LessThanToken */:
30699                 case 51 /* BarToken */:
30700                 case 50 /* AmpersandToken */:
30701                 case 102 /* NewKeyword */:
30702                 case 10 /* StringLiteral */:
30703                 case 8 /* NumericLiteral */:
30704                 case 9 /* BigIntLiteral */:
30705                 case 109 /* TrueKeyword */:
30706                 case 94 /* FalseKeyword */:
30707                 case 145 /* ObjectKeyword */:
30708                 case 41 /* AsteriskToken */:
30709                 case 57 /* QuestionToken */:
30710                 case 53 /* ExclamationToken */:
30711                 case 25 /* DotDotDotToken */:
30712                 case 135 /* InferKeyword */:
30713                 case 99 /* ImportKeyword */:
30714                 case 127 /* AssertsKeyword */:
30715                 case 14 /* NoSubstitutionTemplateLiteral */:
30716                 case 15 /* TemplateHead */:
30717                     return true;
30718                 case 97 /* FunctionKeyword */:
30719                     return !inStartOfParameter;
30720                 case 40 /* MinusToken */:
30721                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
30722                 case 20 /* OpenParenToken */:
30723                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
30724                     // or something that starts a type. We don't want to consider things like '(1)' a type.
30725                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
30726                 default:
30727                     return isIdentifier();
30728             }
30729         }
30730         function isStartOfParenthesizedOrFunctionType() {
30731             nextToken();
30732             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
30733         }
30734         function parsePostfixTypeOrHigher() {
30735             var pos = getNodePos();
30736             var type = parseNonArrayType();
30737             while (!scanner.hasPrecedingLineBreak()) {
30738                 switch (token()) {
30739                     case 53 /* ExclamationToken */:
30740                         nextToken();
30741                         type = finishNode(factory.createJSDocNonNullableType(type), pos);
30742                         break;
30743                     case 57 /* QuestionToken */:
30744                         // If next token is start of a type we have a conditional type
30745                         if (lookAhead(nextTokenIsStartOfType)) {
30746                             return type;
30747                         }
30748                         nextToken();
30749                         type = finishNode(factory.createJSDocNullableType(type), pos);
30750                         break;
30751                     case 22 /* OpenBracketToken */:
30752                         parseExpected(22 /* OpenBracketToken */);
30753                         if (isStartOfType()) {
30754                             var indexType = parseType();
30755                             parseExpected(23 /* CloseBracketToken */);
30756                             type = finishNode(factory.createIndexedAccessTypeNode(type, indexType), pos);
30757                         }
30758                         else {
30759                             parseExpected(23 /* CloseBracketToken */);
30760                             type = finishNode(factory.createArrayTypeNode(type), pos);
30761                         }
30762                         break;
30763                     default:
30764                         return type;
30765                 }
30766             }
30767             return type;
30768         }
30769         function parseTypeOperator(operator) {
30770             var pos = getNodePos();
30771             parseExpected(operator);
30772             return finishNode(factory.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos);
30773         }
30774         function parseTypeParameterOfInferType() {
30775             var pos = getNodePos();
30776             return finishNode(factory.createTypeParameterDeclaration(parseIdentifier(), 
30777             /*constraint*/ undefined, 
30778             /*defaultType*/ undefined), pos);
30779         }
30780         function parseInferType() {
30781             var pos = getNodePos();
30782             parseExpected(135 /* InferKeyword */);
30783             return finishNode(factory.createInferTypeNode(parseTypeParameterOfInferType()), pos);
30784         }
30785         function parseTypeOperatorOrHigher() {
30786             var operator = token();
30787             switch (operator) {
30788                 case 138 /* KeyOfKeyword */:
30789                 case 151 /* UniqueKeyword */:
30790                 case 142 /* ReadonlyKeyword */:
30791                     return parseTypeOperator(operator);
30792                 case 135 /* InferKeyword */:
30793                     return parseInferType();
30794             }
30795             return parsePostfixTypeOrHigher();
30796         }
30797         function parseFunctionOrConstructorTypeToError(isInUnionType) {
30798             // the function type and constructor type shorthand notation
30799             // are not allowed directly in unions and intersections, but we'll
30800             // try to parse them gracefully and issue a helpful message.
30801             if (isStartOfFunctionTypeOrConstructorType()) {
30802                 var type = parseFunctionOrConstructorType();
30803                 var diagnostic = void 0;
30804                 if (ts.isFunctionTypeNode(type)) {
30805                     diagnostic = isInUnionType
30806                         ? ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_a_union_type
30807                         : ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
30808                 }
30809                 else {
30810                     diagnostic = isInUnionType
30811                         ? ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type
30812                         : ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
30813                 }
30814                 parseErrorAtRange(type, diagnostic);
30815                 return type;
30816             }
30817             return undefined;
30818         }
30819         function parseUnionOrIntersectionType(operator, parseConstituentType, createTypeNode) {
30820             var pos = getNodePos();
30821             var isUnionType = operator === 51 /* BarToken */;
30822             var hasLeadingOperator = parseOptional(operator);
30823             var type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType)
30824                 || parseConstituentType();
30825             if (token() === operator || hasLeadingOperator) {
30826                 var types = [type];
30827                 while (parseOptional(operator)) {
30828                     types.push(parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType());
30829                 }
30830                 type = finishNode(createTypeNode(createNodeArray(types, pos)), pos);
30831             }
30832             return type;
30833         }
30834         function parseIntersectionTypeOrHigher() {
30835             return parseUnionOrIntersectionType(50 /* AmpersandToken */, parseTypeOperatorOrHigher, factory.createIntersectionTypeNode);
30836         }
30837         function parseUnionTypeOrHigher() {
30838             return parseUnionOrIntersectionType(51 /* BarToken */, parseIntersectionTypeOrHigher, factory.createUnionTypeNode);
30839         }
30840         function isStartOfFunctionTypeOrConstructorType() {
30841             if (token() === 29 /* LessThanToken */) {
30842                 return true;
30843             }
30844             if (token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) {
30845                 return true;
30846             }
30847             return token() === 102 /* NewKeyword */;
30848         }
30849         function skipParameterStart() {
30850             if (ts.isModifierKind(token())) {
30851                 // Skip modifiers
30852                 parseModifiers();
30853             }
30854             if (isIdentifier() || token() === 107 /* ThisKeyword */) {
30855                 nextToken();
30856                 return true;
30857             }
30858             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
30859                 // Return true if we can parse an array or object binding pattern with no errors
30860                 var previousErrorCount = parseDiagnostics.length;
30861                 parseIdentifierOrPattern();
30862                 return previousErrorCount === parseDiagnostics.length;
30863             }
30864             return false;
30865         }
30866         function isUnambiguouslyStartOfFunctionType() {
30867             nextToken();
30868             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
30869                 // ( )
30870                 // ( ...
30871                 return true;
30872             }
30873             if (skipParameterStart()) {
30874                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
30875                 // now see if we have something that indicates a parameter declaration
30876                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
30877                     token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
30878                     // ( xxx :
30879                     // ( xxx ,
30880                     // ( xxx ?
30881                     // ( xxx =
30882                     return true;
30883                 }
30884                 if (token() === 21 /* CloseParenToken */) {
30885                     nextToken();
30886                     if (token() === 38 /* EqualsGreaterThanToken */) {
30887                         // ( xxx ) =>
30888                         return true;
30889                     }
30890                 }
30891             }
30892             return false;
30893         }
30894         function parseTypeOrTypePredicate() {
30895             var pos = getNodePos();
30896             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
30897             var type = parseType();
30898             if (typePredicateVariable) {
30899                 return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, typePredicateVariable, type), pos);
30900             }
30901             else {
30902                 return type;
30903             }
30904         }
30905         function parseTypePredicatePrefix() {
30906             var id = parseIdentifier();
30907             if (token() === 137 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
30908                 nextToken();
30909                 return id;
30910             }
30911         }
30912         function parseAssertsTypePredicate() {
30913             var pos = getNodePos();
30914             var assertsModifier = parseExpectedToken(127 /* AssertsKeyword */);
30915             var parameterName = token() === 107 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
30916             var type = parseOptional(137 /* IsKeyword */) ? parseType() : undefined;
30917             return finishNode(factory.createTypePredicateNode(assertsModifier, parameterName, type), pos);
30918         }
30919         function parseType() {
30920             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
30921             // apply to 'type' contexts.  So we disable these parameters here before moving on.
30922             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
30923         }
30924         function parseTypeWorker(noConditionalTypes) {
30925             if (isStartOfFunctionTypeOrConstructorType()) {
30926                 return parseFunctionOrConstructorType();
30927             }
30928             var pos = getNodePos();
30929             var type = parseUnionTypeOrHigher();
30930             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(93 /* ExtendsKeyword */)) {
30931                 // The type following 'extends' is not permitted to be another conditional type
30932                 var extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
30933                 parseExpected(57 /* QuestionToken */);
30934                 var trueType = parseTypeWorker();
30935                 parseExpected(58 /* ColonToken */);
30936                 var falseType = parseTypeWorker();
30937                 return finishNode(factory.createConditionalTypeNode(type, extendsType, trueType, falseType), pos);
30938             }
30939             return type;
30940         }
30941         function parseTypeAnnotation() {
30942             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
30943         }
30944         // EXPRESSIONS
30945         function isStartOfLeftHandSideExpression() {
30946             switch (token()) {
30947                 case 107 /* ThisKeyword */:
30948                 case 105 /* SuperKeyword */:
30949                 case 103 /* NullKeyword */:
30950                 case 109 /* TrueKeyword */:
30951                 case 94 /* FalseKeyword */:
30952                 case 8 /* NumericLiteral */:
30953                 case 9 /* BigIntLiteral */:
30954                 case 10 /* StringLiteral */:
30955                 case 14 /* NoSubstitutionTemplateLiteral */:
30956                 case 15 /* TemplateHead */:
30957                 case 20 /* OpenParenToken */:
30958                 case 22 /* OpenBracketToken */:
30959                 case 18 /* OpenBraceToken */:
30960                 case 97 /* FunctionKeyword */:
30961                 case 83 /* ClassKeyword */:
30962                 case 102 /* NewKeyword */:
30963                 case 43 /* SlashToken */:
30964                 case 67 /* SlashEqualsToken */:
30965                 case 78 /* Identifier */:
30966                     return true;
30967                 case 99 /* ImportKeyword */:
30968                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
30969                 default:
30970                     return isIdentifier();
30971             }
30972         }
30973         function isStartOfExpression() {
30974             if (isStartOfLeftHandSideExpression()) {
30975                 return true;
30976             }
30977             switch (token()) {
30978                 case 39 /* PlusToken */:
30979                 case 40 /* MinusToken */:
30980                 case 54 /* TildeToken */:
30981                 case 53 /* ExclamationToken */:
30982                 case 88 /* DeleteKeyword */:
30983                 case 111 /* TypeOfKeyword */:
30984                 case 113 /* VoidKeyword */:
30985                 case 45 /* PlusPlusToken */:
30986                 case 46 /* MinusMinusToken */:
30987                 case 29 /* LessThanToken */:
30988                 case 130 /* AwaitKeyword */:
30989                 case 124 /* YieldKeyword */:
30990                 case 79 /* PrivateIdentifier */:
30991                     // Yield/await always starts an expression.  Either it is an identifier (in which case
30992                     // it is definitely an expression).  Or it's a keyword (either because we're in
30993                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
30994                     return true;
30995                 default:
30996                     // Error tolerance.  If we see the start of some binary operator, we consider
30997                     // that the start of an expression.  That way we'll parse out a missing identifier,
30998                     // give a good message about an identifier being missing, and then consume the
30999                     // rest of the binary expression.
31000                     if (isBinaryOperator()) {
31001                         return true;
31002                     }
31003                     return isIdentifier();
31004             }
31005         }
31006         function isStartOfExpressionStatement() {
31007             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
31008             return token() !== 18 /* OpenBraceToken */ &&
31009                 token() !== 97 /* FunctionKeyword */ &&
31010                 token() !== 83 /* ClassKeyword */ &&
31011                 token() !== 59 /* AtToken */ &&
31012                 isStartOfExpression();
31013         }
31014         function parseExpression() {
31015             // Expression[in]:
31016             //      AssignmentExpression[in]
31017             //      Expression[in] , AssignmentExpression[in]
31018             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
31019             var saveDecoratorContext = inDecoratorContext();
31020             if (saveDecoratorContext) {
31021                 setDecoratorContext(/*val*/ false);
31022             }
31023             var pos = getNodePos();
31024             var expr = parseAssignmentExpressionOrHigher();
31025             var operatorToken;
31026             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
31027                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos);
31028             }
31029             if (saveDecoratorContext) {
31030                 setDecoratorContext(/*val*/ true);
31031             }
31032             return expr;
31033         }
31034         function parseInitializer() {
31035             return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
31036         }
31037         function parseAssignmentExpressionOrHigher() {
31038             //  AssignmentExpression[in,yield]:
31039             //      1) ConditionalExpression[?in,?yield]
31040             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
31041             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
31042             //      4) ArrowFunctionExpression[?in,?yield]
31043             //      5) AsyncArrowFunctionExpression[in,yield,await]
31044             //      6) [+Yield] YieldExpression[?In]
31045             //
31046             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
31047             // (i.e. they're both BinaryExpressions with an assignment operator in it).
31048             // First, do the simple check if we have a YieldExpression (production '6').
31049             if (isYieldExpression()) {
31050                 return parseYieldExpression();
31051             }
31052             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
31053             // parameter list or is an async arrow function.
31054             // AsyncArrowFunctionExpression:
31055             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
31056             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
31057             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
31058             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
31059             //
31060             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
31061             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
31062             // with AssignmentExpression if we see one.
31063             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
31064             if (arrowExpression) {
31065                 return arrowExpression;
31066             }
31067             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
31068             // start with a LogicalOrExpression, while the assignment productions can only start with
31069             // LeftHandSideExpressions.
31070             //
31071             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
31072             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
31073             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
31074             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
31075             // and consumes anything.
31076             var pos = getNodePos();
31077             var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
31078             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
31079             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
31080             // identifier and the current token is an arrow.
31081             if (expr.kind === 78 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
31082                 return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined);
31083             }
31084             // Now see if we might be in cases '2' or '3'.
31085             // If the expression was a LHS expression, and we have an assignment operator, then
31086             // we're in '2' or '3'. Consume the assignment and return.
31087             //
31088             // Note: we call reScanGreaterToken so that we get an appropriately merged token
31089             // for cases like `> > =` becoming `>>=`
31090             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
31091                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos);
31092             }
31093             // It wasn't an assignment or a lambda.  This is a conditional expression:
31094             return parseConditionalExpressionRest(expr, pos);
31095         }
31096         function isYieldExpression() {
31097             if (token() === 124 /* YieldKeyword */) {
31098                 // If we have a 'yield' keyword, and this is a context where yield expressions are
31099                 // allowed, then definitely parse out a yield expression.
31100                 if (inYieldContext()) {
31101                     return true;
31102                 }
31103                 // We're in a context where 'yield expr' is not allowed.  However, if we can
31104                 // definitely tell that the user was trying to parse a 'yield expr' and not
31105                 // just a normal expr that start with a 'yield' identifier, then parse out
31106                 // a 'yield expr'.  We can then report an error later that they are only
31107                 // allowed in generator expressions.
31108                 //
31109                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
31110                 // invocation expression of something called 'yield'.  However, if we have
31111                 // 'yield foo' then that is not legal as a normal expression, so we can
31112                 // definitely recognize this as a yield expression.
31113                 //
31114                 // for now we just check if the next token is an identifier.  More heuristics
31115                 // can be added here later as necessary.  We just need to make sure that we
31116                 // don't accidentally consume something legal.
31117                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
31118             }
31119             return false;
31120         }
31121         function nextTokenIsIdentifierOnSameLine() {
31122             nextToken();
31123             return !scanner.hasPrecedingLineBreak() && isIdentifier();
31124         }
31125         function parseYieldExpression() {
31126             var pos = getNodePos();
31127             // YieldExpression[In] :
31128             //      yield
31129             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
31130             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
31131             nextToken();
31132             if (!scanner.hasPrecedingLineBreak() &&
31133                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
31134                 return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* AsteriskToken */), parseAssignmentExpressionOrHigher()), pos);
31135             }
31136             else {
31137                 // if the next token is not on the same line as yield.  or we don't have an '*' or
31138                 // the start of an expression, then this is just a simple "yield" expression.
31139                 return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos);
31140             }
31141         }
31142         function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) {
31143             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
31144             var parameter = factory.createParameterDeclaration(
31145             /*decorators*/ undefined, 
31146             /*modifiers*/ undefined, 
31147             /*dotDotDotToken*/ undefined, identifier, 
31148             /*questionToken*/ undefined, 
31149             /*type*/ undefined, 
31150             /*initializer*/ undefined);
31151             finishNode(parameter, identifier.pos);
31152             var parameters = createNodeArray([parameter], parameter.pos, parameter.end);
31153             var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
31154             var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
31155             var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body);
31156             return addJSDocComment(finishNode(node, pos));
31157         }
31158         function tryParseParenthesizedArrowFunctionExpression() {
31159             var triState = isParenthesizedArrowFunctionExpression();
31160             if (triState === 0 /* False */) {
31161                 // It's definitely not a parenthesized arrow function expression.
31162                 return undefined;
31163             }
31164             // If we definitely have an arrow function, then we can just parse one, not requiring a
31165             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
31166             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
31167             // expression instead.
31168             return triState === 1 /* True */ ?
31169                 parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) :
31170                 tryParse(parsePossibleParenthesizedArrowFunctionExpression);
31171         }
31172         //  True        -> We definitely expect a parenthesized arrow function here.
31173         //  False       -> There *cannot* be a parenthesized arrow function here.
31174         //  Unknown     -> There *might* be a parenthesized arrow function here.
31175         //                 Speculatively look ahead to be sure, and rollback if not.
31176         function isParenthesizedArrowFunctionExpression() {
31177             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 129 /* AsyncKeyword */) {
31178                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
31179             }
31180             if (token() === 38 /* EqualsGreaterThanToken */) {
31181                 // ERROR RECOVERY TWEAK:
31182                 // If we see a standalone => try to parse it as an arrow function expression as that's
31183                 // likely what the user intended to write.
31184                 return 1 /* True */;
31185             }
31186             // Definitely not a parenthesized arrow function.
31187             return 0 /* False */;
31188         }
31189         function isParenthesizedArrowFunctionExpressionWorker() {
31190             if (token() === 129 /* AsyncKeyword */) {
31191                 nextToken();
31192                 if (scanner.hasPrecedingLineBreak()) {
31193                     return 0 /* False */;
31194                 }
31195                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
31196                     return 0 /* False */;
31197                 }
31198             }
31199             var first = token();
31200             var second = nextToken();
31201             if (first === 20 /* OpenParenToken */) {
31202                 if (second === 21 /* CloseParenToken */) {
31203                     // Simple cases: "() =>", "(): ", and "() {".
31204                     // This is an arrow function with no parameters.
31205                     // The last one is not actually an arrow function,
31206                     // but this is probably what the user intended.
31207                     var third = nextToken();
31208                     switch (third) {
31209                         case 38 /* EqualsGreaterThanToken */:
31210                         case 58 /* ColonToken */:
31211                         case 18 /* OpenBraceToken */:
31212                             return 1 /* True */;
31213                         default:
31214                             return 0 /* False */;
31215                     }
31216                 }
31217                 // If encounter "([" or "({", this could be the start of a binding pattern.
31218                 // Examples:
31219                 //      ([ x ]) => { }
31220                 //      ({ x }) => { }
31221                 //      ([ x ])
31222                 //      ({ x })
31223                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
31224                     return 2 /* Unknown */;
31225                 }
31226                 // Simple case: "(..."
31227                 // This is an arrow function with a rest parameter.
31228                 if (second === 25 /* DotDotDotToken */) {
31229                     return 1 /* True */;
31230                 }
31231                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
31232                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
31233                 // a good error message.
31234                 if (ts.isModifierKind(second) && second !== 129 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
31235                     return 1 /* True */;
31236                 }
31237                 // If we had "(" followed by something that's not an identifier,
31238                 // then this definitely doesn't look like a lambda.  "this" is not
31239                 // valid, but we want to parse it and then give a semantic error.
31240                 if (!isIdentifier() && second !== 107 /* ThisKeyword */) {
31241                     return 0 /* False */;
31242                 }
31243                 switch (nextToken()) {
31244                     case 58 /* ColonToken */:
31245                         // If we have something like "(a:", then we must have a
31246                         // type-annotated parameter in an arrow function expression.
31247                         return 1 /* True */;
31248                     case 57 /* QuestionToken */:
31249                         nextToken();
31250                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
31251                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
31252                             return 1 /* True */;
31253                         }
31254                         // Otherwise it is definitely not a lambda.
31255                         return 0 /* False */;
31256                     case 27 /* CommaToken */:
31257                     case 62 /* EqualsToken */:
31258                     case 21 /* CloseParenToken */:
31259                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
31260                         return 2 /* Unknown */;
31261                 }
31262                 // It is definitely not an arrow function
31263                 return 0 /* False */;
31264             }
31265             else {
31266                 ts.Debug.assert(first === 29 /* LessThanToken */);
31267                 // If we have "<" not followed by an identifier,
31268                 // then this definitely is not an arrow function.
31269                 if (!isIdentifier()) {
31270                     return 0 /* False */;
31271                 }
31272                 // JSX overrides
31273                 if (languageVariant === 1 /* JSX */) {
31274                     var isArrowFunctionInJsx = lookAhead(function () {
31275                         var third = nextToken();
31276                         if (third === 93 /* ExtendsKeyword */) {
31277                             var fourth = nextToken();
31278                             switch (fourth) {
31279                                 case 62 /* EqualsToken */:
31280                                 case 31 /* GreaterThanToken */:
31281                                     return false;
31282                                 default:
31283                                     return true;
31284                             }
31285                         }
31286                         else if (third === 27 /* CommaToken */) {
31287                             return true;
31288                         }
31289                         return false;
31290                     });
31291                     if (isArrowFunctionInJsx) {
31292                         return 1 /* True */;
31293                     }
31294                     return 0 /* False */;
31295                 }
31296                 // This *could* be a parenthesized arrow function.
31297                 return 2 /* Unknown */;
31298             }
31299         }
31300         function parsePossibleParenthesizedArrowFunctionExpression() {
31301             var tokenPos = scanner.getTokenPos();
31302             if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) {
31303                 return undefined;
31304             }
31305             var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false);
31306             if (!result) {
31307                 (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos);
31308             }
31309             return result;
31310         }
31311         function tryParseAsyncSimpleArrowFunctionExpression() {
31312             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
31313             if (token() === 129 /* AsyncKeyword */) {
31314                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
31315                     var pos = getNodePos();
31316                     var asyncModifier = parseModifiersForArrowFunction();
31317                     var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
31318                     return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier);
31319                 }
31320             }
31321             return undefined;
31322         }
31323         function isUnParenthesizedAsyncArrowFunctionWorker() {
31324             // AsyncArrowFunctionExpression:
31325             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
31326             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
31327             if (token() === 129 /* AsyncKeyword */) {
31328                 nextToken();
31329                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
31330                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
31331                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
31332                     return 0 /* False */;
31333                 }
31334                 // Check for un-parenthesized AsyncArrowFunction
31335                 var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
31336                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 78 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
31337                     return 1 /* True */;
31338                 }
31339             }
31340             return 0 /* False */;
31341         }
31342         function parseParenthesizedArrowFunctionExpression(allowAmbiguity) {
31343             var pos = getNodePos();
31344             var hasJSDoc = hasPrecedingJSDocComment();
31345             var modifiers = parseModifiersForArrowFunction();
31346             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
31347             // Arrow functions are never generators.
31348             //
31349             // If we're speculatively parsing a signature for a parenthesized arrow function, then
31350             // we have to have a complete parameter list.  Otherwise we might see something like
31351             // a => (b => c)
31352             // And think that "(b =>" was actually a parenthesized arrow function with a missing
31353             // close paren.
31354             var typeParameters = parseTypeParameters();
31355             var parameters;
31356             if (!parseExpected(20 /* OpenParenToken */)) {
31357                 if (!allowAmbiguity) {
31358                     return undefined;
31359                 }
31360                 parameters = createMissingList();
31361             }
31362             else {
31363                 parameters = parseParametersWorker(isAsync);
31364                 if (!parseExpected(21 /* CloseParenToken */) && !allowAmbiguity) {
31365                     return undefined;
31366                 }
31367             }
31368             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
31369             if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) {
31370                 return undefined;
31371             }
31372             // Parsing a signature isn't enough.
31373             // Parenthesized arrow signatures often look like other valid expressions.
31374             // For instance:
31375             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
31376             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
31377             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
31378             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
31379             //
31380             // So we need just a bit of lookahead to ensure that it can only be a signature.
31381             var hasJSDocFunctionType = type && ts.isJSDocFunctionType(type);
31382             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
31383                 // Returning undefined here will cause our caller to rewind to where we started from.
31384                 return undefined;
31385             }
31386             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
31387             // have an opening brace, just in case we're in an error state.
31388             var lastToken = token();
31389             var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
31390             var body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
31391                 ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier))
31392                 : parseIdentifier();
31393             var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body);
31394             return withJSDoc(finishNode(node, pos), hasJSDoc);
31395         }
31396         function parseArrowFunctionExpressionBody(isAsync) {
31397             if (token() === 18 /* OpenBraceToken */) {
31398                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
31399             }
31400             if (token() !== 26 /* SemicolonToken */ &&
31401                 token() !== 97 /* FunctionKeyword */ &&
31402                 token() !== 83 /* ClassKeyword */ &&
31403                 isStartOfStatement() &&
31404                 !isStartOfExpressionStatement()) {
31405                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
31406                 //
31407                 // Here we try to recover from a potential error situation in the case where the
31408                 // user meant to supply a block. For example, if the user wrote:
31409                 //
31410                 //  a =>
31411                 //      let v = 0;
31412                 //  }
31413                 //
31414                 // they may be missing an open brace.  Check to see if that's the case so we can
31415                 // try to recover better.  If we don't do this, then the next close curly we see may end
31416                 // up preemptively closing the containing construct.
31417                 //
31418                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
31419                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
31420             }
31421             var savedTopLevel = topLevel;
31422             topLevel = false;
31423             var node = isAsync
31424                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
31425                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
31426             topLevel = savedTopLevel;
31427             return node;
31428         }
31429         function parseConditionalExpressionRest(leftOperand, pos) {
31430             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
31431             var questionToken = parseOptionalToken(57 /* QuestionToken */);
31432             if (!questionToken) {
31433                 return leftOperand;
31434             }
31435             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
31436             // we do not that for the 'whenFalse' part.
31437             var colonToken;
31438             return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* ColonToken */), ts.nodeIsPresent(colonToken)
31439                 ? parseAssignmentExpressionOrHigher()
31440                 : createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */))), pos);
31441         }
31442         function parseBinaryExpressionOrHigher(precedence) {
31443             var pos = getNodePos();
31444             var leftOperand = parseUnaryExpressionOrHigher();
31445             return parseBinaryExpressionRest(precedence, leftOperand, pos);
31446         }
31447         function isInOrOfKeyword(t) {
31448             return t === 100 /* InKeyword */ || t === 156 /* OfKeyword */;
31449         }
31450         function parseBinaryExpressionRest(precedence, leftOperand, pos) {
31451             while (true) {
31452                 // We either have a binary operator here, or we're finished.  We call
31453                 // reScanGreaterToken so that we merge token sequences like > and = into >=
31454                 reScanGreaterToken();
31455                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
31456                 // Check the precedence to see if we should "take" this operator
31457                 // - For left associative operator (all operator but **), consume the operator,
31458                 //   recursively call the function below, and parse binaryExpression as a rightOperand
31459                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
31460                 //   For example:
31461                 //      a - b - c;
31462                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
31463                 //      a * b - c
31464                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
31465                 //      a - b * c;
31466                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
31467                 // - For right associative operator (**), consume the operator, recursively call the function
31468                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
31469                 //   the operator is strictly grater than the current precedence
31470                 //   For example:
31471                 //      a ** b ** c;
31472                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
31473                 //      a - b ** c;
31474                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
31475                 //      a ** b - c
31476                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
31477                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
31478                     newPrecedence >= precedence :
31479                     newPrecedence > precedence;
31480                 if (!consumeCurrentOperator) {
31481                     break;
31482                 }
31483                 if (token() === 100 /* InKeyword */ && inDisallowInContext()) {
31484                     break;
31485                 }
31486                 if (token() === 126 /* AsKeyword */) {
31487                     // Make sure we *do* perform ASI for constructs like this:
31488                     //    var x = foo
31489                     //    as (Bar)
31490                     // This should be parsed as an initialized variable, followed
31491                     // by a function call to 'as' with the argument 'Bar'
31492                     if (scanner.hasPrecedingLineBreak()) {
31493                         break;
31494                     }
31495                     else {
31496                         nextToken();
31497                         leftOperand = makeAsExpression(leftOperand, parseType());
31498                     }
31499                 }
31500                 else {
31501                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos);
31502                 }
31503             }
31504             return leftOperand;
31505         }
31506         function isBinaryOperator() {
31507             if (inDisallowInContext() && token() === 100 /* InKeyword */) {
31508                 return false;
31509             }
31510             return ts.getBinaryOperatorPrecedence(token()) > 0;
31511         }
31512         function makeBinaryExpression(left, operatorToken, right, pos) {
31513             return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos);
31514         }
31515         function makeAsExpression(left, right) {
31516             return finishNode(factory.createAsExpression(left, right), left.pos);
31517         }
31518         function parsePrefixUnaryExpression() {
31519             var pos = getNodePos();
31520             return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseSimpleUnaryExpression)), pos);
31521         }
31522         function parseDeleteExpression() {
31523             var pos = getNodePos();
31524             return finishNode(factory.createDeleteExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31525         }
31526         function parseTypeOfExpression() {
31527             var pos = getNodePos();
31528             return finishNode(factory.createTypeOfExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31529         }
31530         function parseVoidExpression() {
31531             var pos = getNodePos();
31532             return finishNode(factory.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31533         }
31534         function isAwaitExpression() {
31535             if (token() === 130 /* AwaitKeyword */) {
31536                 if (inAwaitContext()) {
31537                     return true;
31538                 }
31539                 // here we are using similar heuristics as 'isYieldExpression'
31540                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
31541             }
31542             return false;
31543         }
31544         function parseAwaitExpression() {
31545             var pos = getNodePos();
31546             return finishNode(factory.createAwaitExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31547         }
31548         /**
31549          * Parse ES7 exponential expression and await expression
31550          *
31551          * ES7 ExponentiationExpression:
31552          *      1) UnaryExpression[?Yield]
31553          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
31554          *
31555          */
31556         function parseUnaryExpressionOrHigher() {
31557             /**
31558              * ES7 UpdateExpression:
31559              *      1) LeftHandSideExpression[?Yield]
31560              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
31561              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
31562              *      4) ++UnaryExpression[?Yield]
31563              *      5) --UnaryExpression[?Yield]
31564              */
31565             if (isUpdateExpression()) {
31566                 var pos = getNodePos();
31567                 var updateExpression = parseUpdateExpression();
31568                 return token() === 42 /* AsteriskAsteriskToken */ ?
31569                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression, pos) :
31570                     updateExpression;
31571             }
31572             /**
31573              * ES7 UnaryExpression:
31574              *      1) UpdateExpression[?yield]
31575              *      2) delete UpdateExpression[?yield]
31576              *      3) void UpdateExpression[?yield]
31577              *      4) typeof UpdateExpression[?yield]
31578              *      5) + UpdateExpression[?yield]
31579              *      6) - UpdateExpression[?yield]
31580              *      7) ~ UpdateExpression[?yield]
31581              *      8) ! UpdateExpression[?yield]
31582              */
31583             var unaryOperator = token();
31584             var simpleUnaryExpression = parseSimpleUnaryExpression();
31585             if (token() === 42 /* AsteriskAsteriskToken */) {
31586                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
31587                 var end = simpleUnaryExpression.end;
31588                 if (simpleUnaryExpression.kind === 206 /* TypeAssertionExpression */) {
31589                     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);
31590                 }
31591                 else {
31592                     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));
31593                 }
31594             }
31595             return simpleUnaryExpression;
31596         }
31597         /**
31598          * Parse ES7 simple-unary expression or higher:
31599          *
31600          * ES7 UnaryExpression:
31601          *      1) UpdateExpression[?yield]
31602          *      2) delete UnaryExpression[?yield]
31603          *      3) void UnaryExpression[?yield]
31604          *      4) typeof UnaryExpression[?yield]
31605          *      5) + UnaryExpression[?yield]
31606          *      6) - UnaryExpression[?yield]
31607          *      7) ~ UnaryExpression[?yield]
31608          *      8) ! UnaryExpression[?yield]
31609          *      9) [+Await] await UnaryExpression[?yield]
31610          */
31611         function parseSimpleUnaryExpression() {
31612             switch (token()) {
31613                 case 39 /* PlusToken */:
31614                 case 40 /* MinusToken */:
31615                 case 54 /* TildeToken */:
31616                 case 53 /* ExclamationToken */:
31617                     return parsePrefixUnaryExpression();
31618                 case 88 /* DeleteKeyword */:
31619                     return parseDeleteExpression();
31620                 case 111 /* TypeOfKeyword */:
31621                     return parseTypeOfExpression();
31622                 case 113 /* VoidKeyword */:
31623                     return parseVoidExpression();
31624                 case 29 /* LessThanToken */:
31625                     // This is modified UnaryExpression grammar in TypeScript
31626                     //  UnaryExpression (modified):
31627                     //      < type > UnaryExpression
31628                     return parseTypeAssertion();
31629                 case 130 /* AwaitKeyword */:
31630                     if (isAwaitExpression()) {
31631                         return parseAwaitExpression();
31632                     }
31633                 // falls through
31634                 default:
31635                     return parseUpdateExpression();
31636             }
31637         }
31638         /**
31639          * Check if the current token can possibly be an ES7 increment expression.
31640          *
31641          * ES7 UpdateExpression:
31642          *      LeftHandSideExpression[?Yield]
31643          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
31644          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
31645          *      ++LeftHandSideExpression[?Yield]
31646          *      --LeftHandSideExpression[?Yield]
31647          */
31648         function isUpdateExpression() {
31649             // This function is called inside parseUnaryExpression to decide
31650             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
31651             switch (token()) {
31652                 case 39 /* PlusToken */:
31653                 case 40 /* MinusToken */:
31654                 case 54 /* TildeToken */:
31655                 case 53 /* ExclamationToken */:
31656                 case 88 /* DeleteKeyword */:
31657                 case 111 /* TypeOfKeyword */:
31658                 case 113 /* VoidKeyword */:
31659                 case 130 /* AwaitKeyword */:
31660                     return false;
31661                 case 29 /* LessThanToken */:
31662                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
31663                     if (languageVariant !== 1 /* JSX */) {
31664                         return false;
31665                     }
31666                 // We are in JSX context and the token is part of JSXElement.
31667                 // falls through
31668                 default:
31669                     return true;
31670             }
31671         }
31672         /**
31673          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
31674          *
31675          * ES7 UpdateExpression[yield]:
31676          *      1) LeftHandSideExpression[?yield]
31677          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
31678          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
31679          *      4) ++LeftHandSideExpression[?yield]
31680          *      5) --LeftHandSideExpression[?yield]
31681          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
31682          */
31683         function parseUpdateExpression() {
31684             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
31685                 var pos = getNodePos();
31686                 return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos);
31687             }
31688             else if (languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
31689                 // JSXElement is part of primaryExpression
31690                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
31691             }
31692             var expression = parseLeftHandSideExpressionOrHigher();
31693             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
31694             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
31695                 var operator = token();
31696                 nextToken();
31697                 return finishNode(factory.createPostfixUnaryExpression(expression, operator), expression.pos);
31698             }
31699             return expression;
31700         }
31701         function parseLeftHandSideExpressionOrHigher() {
31702             // Original Ecma:
31703             // LeftHandSideExpression: See 11.2
31704             //      NewExpression
31705             //      CallExpression
31706             //
31707             // Our simplification:
31708             //
31709             // LeftHandSideExpression: See 11.2
31710             //      MemberExpression
31711             //      CallExpression
31712             //
31713             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
31714             // MemberExpression to make our lives easier.
31715             //
31716             // to best understand the below code, it's important to see how CallExpression expands
31717             // out into its own productions:
31718             //
31719             // CallExpression:
31720             //      MemberExpression Arguments
31721             //      CallExpression Arguments
31722             //      CallExpression[Expression]
31723             //      CallExpression.IdentifierName
31724             //      import (AssignmentExpression)
31725             //      super Arguments
31726             //      super.IdentifierName
31727             //
31728             // Because of the recursion in these calls, we need to bottom out first. There are three
31729             // bottom out states we can run into: 1) We see 'super' which must start either of
31730             // the last two CallExpression productions. 2) We see 'import' which must start import call.
31731             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
31732             // or starts the beginning of the first four CallExpression productions.
31733             var pos = getNodePos();
31734             var expression;
31735             if (token() === 99 /* ImportKeyword */) {
31736                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
31737                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
31738                     // For example:
31739                     //      var foo3 = require("subfolder
31740                     //      import * as foo1 from "module-from-node
31741                     // We want this import to be a statement rather than import call expression
31742                     sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
31743                     expression = parseTokenNode();
31744                 }
31745                 else if (lookAhead(nextTokenIsDot)) {
31746                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
31747                     nextToken(); // advance past the 'import'
31748                     nextToken(); // advance past the dot
31749                     expression = finishNode(factory.createMetaProperty(99 /* ImportKeyword */, parseIdentifierName()), pos);
31750                     sourceFlags |= 2097152 /* PossiblyContainsImportMeta */;
31751                 }
31752                 else {
31753                     expression = parseMemberExpressionOrHigher();
31754                 }
31755             }
31756             else {
31757                 expression = token() === 105 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
31758             }
31759             // Now, we *may* be complete.  However, we might have consumed the start of a
31760             // CallExpression or OptionalExpression.  As such, we need to consume the rest
31761             // of it here to be complete.
31762             return parseCallExpressionRest(pos, expression);
31763         }
31764         function parseMemberExpressionOrHigher() {
31765             // Note: to make our lives simpler, we decompose the NewExpression productions and
31766             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
31767             // like so:
31768             //
31769             //   PrimaryExpression : See 11.1
31770             //      this
31771             //      Identifier
31772             //      Literal
31773             //      ArrayLiteral
31774             //      ObjectLiteral
31775             //      (Expression)
31776             //      FunctionExpression
31777             //      new MemberExpression Arguments?
31778             //
31779             //   MemberExpression : See 11.2
31780             //      PrimaryExpression
31781             //      MemberExpression[Expression]
31782             //      MemberExpression.IdentifierName
31783             //
31784             //   CallExpression : See 11.2
31785             //      MemberExpression
31786             //      CallExpression Arguments
31787             //      CallExpression[Expression]
31788             //      CallExpression.IdentifierName
31789             //
31790             // Technically this is ambiguous.  i.e. CallExpression defines:
31791             //
31792             //   CallExpression:
31793             //      CallExpression Arguments
31794             //
31795             // If you see: "new Foo()"
31796             //
31797             // Then that could be treated as a single ObjectCreationExpression, or it could be
31798             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
31799             // the original grammar) by making sure that if we see an ObjectCreationExpression
31800             // we always consume arguments if they are there. So we treat "new Foo()" as an
31801             // object creation only, and not at all as an invocation.  Another way to think
31802             // about this is that for every "new" that we see, we will consume an argument list if
31803             // it is there as part of the *associated* object creation node.  Any additional
31804             // argument lists we see, will become invocation expressions.
31805             //
31806             // Because there are no other places in the grammar now that refer to FunctionExpression
31807             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
31808             // production.
31809             //
31810             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
31811             // of the recursion immediately.  So we parse out a primary expression to start with.
31812             var pos = getNodePos();
31813             var expression = parsePrimaryExpression();
31814             return parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
31815         }
31816         function parseSuperExpression() {
31817             var pos = getNodePos();
31818             var expression = parseTokenNode();
31819             if (token() === 29 /* LessThanToken */) {
31820                 var startPos = getNodePos();
31821                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
31822                 if (typeArguments !== undefined) {
31823                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
31824                 }
31825             }
31826             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
31827                 return expression;
31828             }
31829             // If we have seen "super" it must be followed by '(' or '.'.
31830             // If it wasn't then just try to parse out a '.' and report an error.
31831             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
31832             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
31833             return finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos);
31834         }
31835         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition) {
31836             var pos = getNodePos();
31837             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
31838             var result;
31839             if (opening.kind === 275 /* JsxOpeningElement */) {
31840                 var children = parseJsxChildren(opening);
31841                 var closingElement = parseJsxClosingElement(inExpressionContext);
31842                 if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) {
31843                     parseErrorAtRange(closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, opening.tagName));
31844                 }
31845                 result = finishNode(factory.createJsxElement(opening, children, closingElement), pos);
31846             }
31847             else if (opening.kind === 278 /* JsxOpeningFragment */) {
31848                 result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos);
31849             }
31850             else {
31851                 ts.Debug.assert(opening.kind === 274 /* JsxSelfClosingElement */);
31852                 // Nothing else to do for self-closing elements
31853                 result = opening;
31854             }
31855             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
31856             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
31857             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
31858             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
31859             // does less damage and we can report a better error.
31860             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
31861             // of one sort or another.
31862             if (inExpressionContext && token() === 29 /* LessThanToken */) {
31863                 var topBadPos_1 = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition;
31864                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, topBadPos_1); });
31865                 if (invalidElement) {
31866                     var operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
31867                     ts.setTextRangePosWidth(operatorToken, invalidElement.pos, 0);
31868                     parseErrorAt(ts.skipTrivia(sourceText, topBadPos_1), invalidElement.end, ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
31869                     return finishNode(factory.createBinaryExpression(result, operatorToken, invalidElement), pos);
31870                 }
31871             }
31872             return result;
31873         }
31874         function parseJsxText() {
31875             var pos = getNodePos();
31876             var node = factory.createJsxText(scanner.getTokenValue(), currentToken === 12 /* JsxTextAllWhiteSpaces */);
31877             currentToken = scanner.scanJsxToken();
31878             return finishNode(node, pos);
31879         }
31880         function parseJsxChild(openingTag, token) {
31881             switch (token) {
31882                 case 1 /* EndOfFileToken */:
31883                     // If we hit EOF, issue the error at the tag that lacks the closing element
31884                     // rather than at the end of the file (which is useless)
31885                     if (ts.isJsxOpeningFragment(openingTag)) {
31886                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
31887                     }
31888                     else {
31889                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
31890                         // or to cover only 'Foo' in < Foo >
31891                         var tag = openingTag.tagName;
31892                         var start = ts.skipTrivia(sourceText, tag.pos);
31893                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
31894                     }
31895                     return undefined;
31896                 case 30 /* LessThanSlashToken */:
31897                 case 7 /* ConflictMarkerTrivia */:
31898                     return undefined;
31899                 case 11 /* JsxText */:
31900                 case 12 /* JsxTextAllWhiteSpaces */:
31901                     return parseJsxText();
31902                 case 18 /* OpenBraceToken */:
31903                     return parseJsxExpression(/*inExpressionContext*/ false);
31904                 case 29 /* LessThanToken */:
31905                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
31906                 default:
31907                     return ts.Debug.assertNever(token);
31908             }
31909         }
31910         function parseJsxChildren(openingTag) {
31911             var list = [];
31912             var listPos = getNodePos();
31913             var saveParsingContext = parsingContext;
31914             parsingContext |= 1 << 14 /* JsxChildren */;
31915             while (true) {
31916                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
31917                 if (!child)
31918                     break;
31919                 list.push(child);
31920             }
31921             parsingContext = saveParsingContext;
31922             return createNodeArray(list, listPos);
31923         }
31924         function parseJsxAttributes() {
31925             var pos = getNodePos();
31926             return finishNode(factory.createJsxAttributes(parseList(13 /* JsxAttributes */, parseJsxAttribute)), pos);
31927         }
31928         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
31929             var pos = getNodePos();
31930             parseExpected(29 /* LessThanToken */);
31931             if (token() === 31 /* GreaterThanToken */) {
31932                 // See below for explanation of scanJsxText
31933                 scanJsxText();
31934                 return finishNode(factory.createJsxOpeningFragment(), pos);
31935             }
31936             var tagName = parseJsxElementName();
31937             var typeArguments = tryParseTypeArguments();
31938             var attributes = parseJsxAttributes();
31939             var node;
31940             if (token() === 31 /* GreaterThanToken */) {
31941                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
31942                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
31943                 // scanning errors
31944                 scanJsxText();
31945                 node = factory.createJsxOpeningElement(tagName, typeArguments, attributes);
31946             }
31947             else {
31948                 parseExpected(43 /* SlashToken */);
31949                 if (inExpressionContext) {
31950                     parseExpected(31 /* GreaterThanToken */);
31951                 }
31952                 else {
31953                     parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
31954                     scanJsxText();
31955                 }
31956                 node = factory.createJsxSelfClosingElement(tagName, typeArguments, attributes);
31957             }
31958             return finishNode(node, pos);
31959         }
31960         function parseJsxElementName() {
31961             var pos = getNodePos();
31962             scanJsxIdentifier();
31963             // JsxElement can have name in the form of
31964             //      propertyAccessExpression
31965             //      primaryExpression in the form of an identifier and "this" keyword
31966             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
31967             // We only want to consider "this" as a primaryExpression
31968             var expression = token() === 107 /* ThisKeyword */ ?
31969                 parseTokenNode() : parseIdentifierName();
31970             while (parseOptional(24 /* DotToken */)) {
31971                 expression = finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos);
31972             }
31973             return expression;
31974         }
31975         function parseJsxExpression(inExpressionContext) {
31976             var pos = getNodePos();
31977             if (!parseExpected(18 /* OpenBraceToken */)) {
31978                 return undefined;
31979             }
31980             var dotDotDotToken;
31981             var expression;
31982             if (token() !== 19 /* CloseBraceToken */) {
31983                 dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
31984                 // Only an AssignmentExpression is valid here per the JSX spec,
31985                 // but we can unambiguously parse a comma sequence and provide
31986                 // a better error message in grammar checking.
31987                 expression = parseExpression();
31988             }
31989             if (inExpressionContext) {
31990                 parseExpected(19 /* CloseBraceToken */);
31991             }
31992             else {
31993                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
31994                     scanJsxText();
31995                 }
31996             }
31997             return finishNode(factory.createJsxExpression(dotDotDotToken, expression), pos);
31998         }
31999         function parseJsxAttribute() {
32000             if (token() === 18 /* OpenBraceToken */) {
32001                 return parseJsxSpreadAttribute();
32002             }
32003             scanJsxIdentifier();
32004             var pos = getNodePos();
32005             return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 62 /* EqualsToken */ ? undefined :
32006                 scanJsxAttributeValue() === 10 /* StringLiteral */ ? parseLiteralNode() :
32007                     parseJsxExpression(/*inExpressionContext*/ true)), pos);
32008         }
32009         function parseJsxSpreadAttribute() {
32010             var pos = getNodePos();
32011             parseExpected(18 /* OpenBraceToken */);
32012             parseExpected(25 /* DotDotDotToken */);
32013             var expression = parseExpression();
32014             parseExpected(19 /* CloseBraceToken */);
32015             return finishNode(factory.createJsxSpreadAttribute(expression), pos);
32016         }
32017         function parseJsxClosingElement(inExpressionContext) {
32018             var pos = getNodePos();
32019             parseExpected(30 /* LessThanSlashToken */);
32020             var tagName = parseJsxElementName();
32021             if (inExpressionContext) {
32022                 parseExpected(31 /* GreaterThanToken */);
32023             }
32024             else {
32025                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
32026                 scanJsxText();
32027             }
32028             return finishNode(factory.createJsxClosingElement(tagName), pos);
32029         }
32030         function parseJsxClosingFragment(inExpressionContext) {
32031             var pos = getNodePos();
32032             parseExpected(30 /* LessThanSlashToken */);
32033             if (ts.tokenIsIdentifierOrKeyword(token())) {
32034                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
32035             }
32036             if (inExpressionContext) {
32037                 parseExpected(31 /* GreaterThanToken */);
32038             }
32039             else {
32040                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
32041                 scanJsxText();
32042             }
32043             return finishNode(factory.createJsxJsxClosingFragment(), pos);
32044         }
32045         function parseTypeAssertion() {
32046             var pos = getNodePos();
32047             parseExpected(29 /* LessThanToken */);
32048             var type = parseType();
32049             parseExpected(31 /* GreaterThanToken */);
32050             var expression = parseSimpleUnaryExpression();
32051             return finishNode(factory.createTypeAssertion(type, expression), pos);
32052         }
32053         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
32054             nextToken();
32055             return ts.tokenIsIdentifierOrKeyword(token())
32056                 || token() === 22 /* OpenBracketToken */
32057                 || isTemplateStartOfTaggedTemplate();
32058         }
32059         function isStartOfOptionalPropertyOrElementAccessChain() {
32060             return token() === 28 /* QuestionDotToken */
32061                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
32062         }
32063         function tryReparseOptionalChain(node) {
32064             if (node.flags & 32 /* OptionalChain */) {
32065                 return true;
32066             }
32067             // check for an optional chain in a non-null expression
32068             if (ts.isNonNullExpression(node)) {
32069                 var expr = node.expression;
32070                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
32071                     expr = expr.expression;
32072                 }
32073                 if (expr.flags & 32 /* OptionalChain */) {
32074                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
32075                     while (ts.isNonNullExpression(node)) {
32076                         node.flags |= 32 /* OptionalChain */;
32077                         node = node.expression;
32078                     }
32079                     return true;
32080                 }
32081             }
32082             return false;
32083         }
32084         function parsePropertyAccessExpressionRest(pos, expression, questionDotToken) {
32085             var name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
32086             var isOptionalChain = questionDotToken || tryReparseOptionalChain(expression);
32087             var propertyAccess = isOptionalChain ?
32088                 factory.createPropertyAccessChain(expression, questionDotToken, name) :
32089                 factory.createPropertyAccessExpression(expression, name);
32090             if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) {
32091                 parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
32092             }
32093             return finishNode(propertyAccess, pos);
32094         }
32095         function parseElementAccessExpressionRest(pos, expression, questionDotToken) {
32096             var argumentExpression;
32097             if (token() === 23 /* CloseBracketToken */) {
32098                 argumentExpression = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
32099             }
32100             else {
32101                 var argument = allowInAnd(parseExpression);
32102                 if (ts.isStringOrNumericLiteralLike(argument)) {
32103                     argument.text = internIdentifier(argument.text);
32104                 }
32105                 argumentExpression = argument;
32106             }
32107             parseExpected(23 /* CloseBracketToken */);
32108             var indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ?
32109                 factory.createElementAccessChain(expression, questionDotToken, argumentExpression) :
32110                 factory.createElementAccessExpression(expression, argumentExpression);
32111             return finishNode(indexedAccess, pos);
32112         }
32113         function parseMemberExpressionRest(pos, expression, allowOptionalChain) {
32114             while (true) {
32115                 var questionDotToken = void 0;
32116                 var isPropertyAccess = false;
32117                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
32118                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
32119                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
32120                 }
32121                 else {
32122                     isPropertyAccess = parseOptional(24 /* DotToken */);
32123                 }
32124                 if (isPropertyAccess) {
32125                     expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken);
32126                     continue;
32127                 }
32128                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
32129                     nextToken();
32130                     expression = finishNode(factory.createNonNullExpression(expression), pos);
32131                     continue;
32132                 }
32133                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
32134                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
32135                     expression = parseElementAccessExpressionRest(pos, expression, questionDotToken);
32136                     continue;
32137                 }
32138                 if (isTemplateStartOfTaggedTemplate()) {
32139                     expression = parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined);
32140                     continue;
32141                 }
32142                 return expression;
32143             }
32144         }
32145         function isTemplateStartOfTaggedTemplate() {
32146             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
32147         }
32148         function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) {
32149             var tagExpression = factory.createTaggedTemplateExpression(tag, typeArguments, token() === 14 /* NoSubstitutionTemplateLiteral */ ?
32150                 (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode()) :
32151                 parseTemplateExpression(/*isTaggedTemplate*/ true));
32152             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
32153                 tagExpression.flags |= 32 /* OptionalChain */;
32154             }
32155             tagExpression.questionDotToken = questionDotToken;
32156             return finishNode(tagExpression, pos);
32157         }
32158         function parseCallExpressionRest(pos, expression) {
32159             while (true) {
32160                 expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
32161                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
32162                 // handle 'foo<<T>()'
32163                 if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
32164                     // See if this is the start of a generic invocation.  If so, consume it and
32165                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
32166                     // part of an arithmetic expression.  Break out so we consume it higher in the
32167                     // stack.
32168                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
32169                     if (typeArguments) {
32170                         if (isTemplateStartOfTaggedTemplate()) {
32171                             expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments);
32172                             continue;
32173                         }
32174                         var argumentList = parseArgumentList();
32175                         var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
32176                             factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) :
32177                             factory.createCallExpression(expression, typeArguments, argumentList);
32178                         expression = finishNode(callExpr, pos);
32179                         continue;
32180                     }
32181                 }
32182                 else if (token() === 20 /* OpenParenToken */) {
32183                     var argumentList = parseArgumentList();
32184                     var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
32185                         factory.createCallChain(expression, questionDotToken, /*typeArguments*/ undefined, argumentList) :
32186                         factory.createCallExpression(expression, /*typeArguments*/ undefined, argumentList);
32187                     expression = finishNode(callExpr, pos);
32188                     continue;
32189                 }
32190                 if (questionDotToken) {
32191                     // We failed to parse anything, so report a missing identifier here.
32192                     var name = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
32193                     expression = finishNode(factory.createPropertyAccessChain(expression, questionDotToken, name), pos);
32194                 }
32195                 break;
32196             }
32197             return expression;
32198         }
32199         function parseArgumentList() {
32200             parseExpected(20 /* OpenParenToken */);
32201             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
32202             parseExpected(21 /* CloseParenToken */);
32203             return result;
32204         }
32205         function parseTypeArgumentsInExpression() {
32206             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
32207                 return undefined;
32208             }
32209             nextToken();
32210             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
32211             if (!parseExpected(31 /* GreaterThanToken */)) {
32212                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
32213                 return undefined;
32214             }
32215             // If we have a '<', then only parse this as a argument list if the type arguments
32216             // are complete and we have an open paren.  if we don't, rewind and return nothing.
32217             return typeArguments && canFollowTypeArgumentsInExpression()
32218                 ? typeArguments
32219                 : undefined;
32220         }
32221         function canFollowTypeArgumentsInExpression() {
32222             switch (token()) {
32223                 case 20 /* OpenParenToken */: // foo<x>(
32224                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
32225                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
32226                 // these are the only tokens can legally follow a type argument
32227                 // list. So we definitely want to treat them as type arg lists.
32228                 // falls through
32229                 case 24 /* DotToken */: // foo<x>.
32230                 case 21 /* CloseParenToken */: // foo<x>)
32231                 case 23 /* CloseBracketToken */: // foo<x>]
32232                 case 58 /* ColonToken */: // foo<x>:
32233                 case 26 /* SemicolonToken */: // foo<x>;
32234                 case 57 /* QuestionToken */: // foo<x>?
32235                 case 34 /* EqualsEqualsToken */: // foo<x> ==
32236                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
32237                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
32238                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
32239                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
32240                 case 56 /* BarBarToken */: // foo<x> ||
32241                 case 60 /* QuestionQuestionToken */: // foo<x> ??
32242                 case 52 /* CaretToken */: // foo<x> ^
32243                 case 50 /* AmpersandToken */: // foo<x> &
32244                 case 51 /* BarToken */: // foo<x> |
32245                 case 19 /* CloseBraceToken */: // foo<x> }
32246                 case 1 /* EndOfFileToken */: // foo<x>
32247                     // these cases can't legally follow a type arg list.  However, they're not legal
32248                     // expressions either.  The user is probably in the middle of a generic type. So
32249                     // treat it as such.
32250                     return true;
32251                 case 27 /* CommaToken */: // foo<x>,
32252                 case 18 /* OpenBraceToken */: // foo<x> {
32253                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
32254                 // as an invocation expression.  Instead, we want to parse out the expression
32255                 // in isolation from the type arguments.
32256                 // falls through
32257                 default:
32258                     // Anything else treat as an expression.
32259                     return false;
32260             }
32261         }
32262         function parsePrimaryExpression() {
32263             switch (token()) {
32264                 case 8 /* NumericLiteral */:
32265                 case 9 /* BigIntLiteral */:
32266                 case 10 /* StringLiteral */:
32267                 case 14 /* NoSubstitutionTemplateLiteral */:
32268                     return parseLiteralNode();
32269                 case 107 /* ThisKeyword */:
32270                 case 105 /* SuperKeyword */:
32271                 case 103 /* NullKeyword */:
32272                 case 109 /* TrueKeyword */:
32273                 case 94 /* FalseKeyword */:
32274                     return parseTokenNode();
32275                 case 20 /* OpenParenToken */:
32276                     return parseParenthesizedExpression();
32277                 case 22 /* OpenBracketToken */:
32278                     return parseArrayLiteralExpression();
32279                 case 18 /* OpenBraceToken */:
32280                     return parseObjectLiteralExpression();
32281                 case 129 /* AsyncKeyword */:
32282                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
32283                     // If we encounter `async [no LineTerminator here] function` then this is an async
32284                     // function; otherwise, its an identifier.
32285                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
32286                         break;
32287                     }
32288                     return parseFunctionExpression();
32289                 case 83 /* ClassKeyword */:
32290                     return parseClassExpression();
32291                 case 97 /* FunctionKeyword */:
32292                     return parseFunctionExpression();
32293                 case 102 /* NewKeyword */:
32294                     return parseNewExpressionOrNewDotTarget();
32295                 case 43 /* SlashToken */:
32296                 case 67 /* SlashEqualsToken */:
32297                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
32298                         return parseLiteralNode();
32299                     }
32300                     break;
32301                 case 15 /* TemplateHead */:
32302                     return parseTemplateExpression(/* isTaggedTemplate */ false);
32303             }
32304             return parseIdentifier(ts.Diagnostics.Expression_expected);
32305         }
32306         function parseParenthesizedExpression() {
32307             var pos = getNodePos();
32308             var hasJSDoc = hasPrecedingJSDocComment();
32309             parseExpected(20 /* OpenParenToken */);
32310             var expression = allowInAnd(parseExpression);
32311             parseExpected(21 /* CloseParenToken */);
32312             return withJSDoc(finishNode(factory.createParenthesizedExpression(expression), pos), hasJSDoc);
32313         }
32314         function parseSpreadElement() {
32315             var pos = getNodePos();
32316             parseExpected(25 /* DotDotDotToken */);
32317             var expression = parseAssignmentExpressionOrHigher();
32318             return finishNode(factory.createSpreadElement(expression), pos);
32319         }
32320         function parseArgumentOrArrayLiteralElement() {
32321             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
32322                 token() === 27 /* CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) :
32323                     parseAssignmentExpressionOrHigher();
32324         }
32325         function parseArgumentExpression() {
32326             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
32327         }
32328         function parseArrayLiteralExpression() {
32329             var pos = getNodePos();
32330             parseExpected(22 /* OpenBracketToken */);
32331             var multiLine = scanner.hasPrecedingLineBreak();
32332             var elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
32333             parseExpected(23 /* CloseBracketToken */);
32334             return finishNode(factory.createArrayLiteralExpression(elements, multiLine), pos);
32335         }
32336         function parseObjectLiteralElement() {
32337             var pos = getNodePos();
32338             var hasJSDoc = hasPrecedingJSDocComment();
32339             if (parseOptionalToken(25 /* DotDotDotToken */)) {
32340                 var expression = parseAssignmentExpressionOrHigher();
32341                 return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc);
32342             }
32343             var decorators = parseDecorators();
32344             var modifiers = parseModifiers();
32345             if (parseContextualModifier(134 /* GetKeyword */)) {
32346                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */);
32347             }
32348             if (parseContextualModifier(146 /* SetKeyword */)) {
32349                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */);
32350             }
32351             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
32352             var tokenIsIdentifier = isIdentifier();
32353             var name = parsePropertyName();
32354             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
32355             var questionToken = parseOptionalToken(57 /* QuestionToken */);
32356             var exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
32357             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
32358                 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken);
32359             }
32360             // check if it is short-hand property assignment or normal property assignment
32361             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
32362             // CoverInitializedName[Yield] :
32363             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
32364             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
32365             var node;
32366             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
32367             if (isShorthandPropertyAssignment) {
32368                 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
32369                 var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined;
32370                 node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer);
32371                 // Save equals token for error reporting.
32372                 // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful.
32373                 node.equalsToken = equalsToken;
32374             }
32375             else {
32376                 parseExpected(58 /* ColonToken */);
32377                 var initializer = allowInAnd(parseAssignmentExpressionOrHigher);
32378                 node = factory.createPropertyAssignment(name, initializer);
32379             }
32380             // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker
32381             node.decorators = decorators;
32382             node.modifiers = modifiers;
32383             node.questionToken = questionToken;
32384             node.exclamationToken = exclamationToken;
32385             return withJSDoc(finishNode(node, pos), hasJSDoc);
32386         }
32387         function parseObjectLiteralExpression() {
32388             var pos = getNodePos();
32389             var openBracePosition = scanner.getTokenPos();
32390             parseExpected(18 /* OpenBraceToken */);
32391             var multiLine = scanner.hasPrecedingLineBreak();
32392             var properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
32393             if (!parseExpected(19 /* CloseBraceToken */)) {
32394                 var lastError = ts.lastOrUndefined(parseDiagnostics);
32395                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
32396                     ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
32397                 }
32398             }
32399             return finishNode(factory.createObjectLiteralExpression(properties, multiLine), pos);
32400         }
32401         function parseFunctionExpression() {
32402             // GeneratorExpression:
32403             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
32404             //
32405             // FunctionExpression:
32406             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
32407             var saveDecoratorContext = inDecoratorContext();
32408             if (saveDecoratorContext) {
32409                 setDecoratorContext(/*val*/ false);
32410             }
32411             var pos = getNodePos();
32412             var hasJSDoc = hasPrecedingJSDocComment();
32413             var modifiers = parseModifiers();
32414             parseExpected(97 /* FunctionKeyword */);
32415             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
32416             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
32417             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
32418             var name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) :
32419                 isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) :
32420                     isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) :
32421                         parseOptionalBindingIdentifier();
32422             var typeParameters = parseTypeParameters();
32423             var parameters = parseParameters(isGenerator | isAsync);
32424             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
32425             var body = parseFunctionBlock(isGenerator | isAsync);
32426             if (saveDecoratorContext) {
32427                 setDecoratorContext(/*val*/ true);
32428             }
32429             var node = factory.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body);
32430             return withJSDoc(finishNode(node, pos), hasJSDoc);
32431         }
32432         function parseOptionalBindingIdentifier() {
32433             return isBindingIdentifier() ? parseBindingIdentifier() : undefined;
32434         }
32435         function parseNewExpressionOrNewDotTarget() {
32436             var pos = getNodePos();
32437             parseExpected(102 /* NewKeyword */);
32438             if (parseOptional(24 /* DotToken */)) {
32439                 var name = parseIdentifierName();
32440                 return finishNode(factory.createMetaProperty(102 /* NewKeyword */, name), pos);
32441             }
32442             var expressionPos = getNodePos();
32443             var expression = parsePrimaryExpression();
32444             var typeArguments;
32445             while (true) {
32446                 expression = parseMemberExpressionRest(expressionPos, expression, /*allowOptionalChain*/ false);
32447                 typeArguments = tryParse(parseTypeArgumentsInExpression);
32448                 if (isTemplateStartOfTaggedTemplate()) {
32449                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
32450                     expression = parseTaggedTemplateRest(expressionPos, expression, /*optionalChain*/ undefined, typeArguments);
32451                     typeArguments = undefined;
32452                 }
32453                 break;
32454             }
32455             var argumentsArray;
32456             if (token() === 20 /* OpenParenToken */) {
32457                 argumentsArray = parseArgumentList();
32458             }
32459             else if (typeArguments) {
32460                 parseErrorAt(pos, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
32461             }
32462             return finishNode(factory.createNewExpression(expression, typeArguments, argumentsArray), pos);
32463         }
32464         // STATEMENTS
32465         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
32466             var pos = getNodePos();
32467             var openBracePosition = scanner.getTokenPos();
32468             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
32469                 var multiLine = scanner.hasPrecedingLineBreak();
32470                 var statements = parseList(1 /* BlockStatements */, parseStatement);
32471                 if (!parseExpected(19 /* CloseBraceToken */)) {
32472                     var lastError = ts.lastOrUndefined(parseDiagnostics);
32473                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
32474                         ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
32475                     }
32476                 }
32477                 return finishNode(factory.createBlock(statements, multiLine), pos);
32478             }
32479             else {
32480                 var statements = createMissingList();
32481                 return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos);
32482             }
32483         }
32484         function parseFunctionBlock(flags, diagnosticMessage) {
32485             var savedYieldContext = inYieldContext();
32486             setYieldContext(!!(flags & 1 /* Yield */));
32487             var savedAwaitContext = inAwaitContext();
32488             setAwaitContext(!!(flags & 2 /* Await */));
32489             var savedTopLevel = topLevel;
32490             topLevel = false;
32491             // We may be in a [Decorator] context when parsing a function expression or
32492             // arrow function. The body of the function is not in [Decorator] context.
32493             var saveDecoratorContext = inDecoratorContext();
32494             if (saveDecoratorContext) {
32495                 setDecoratorContext(/*val*/ false);
32496             }
32497             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
32498             if (saveDecoratorContext) {
32499                 setDecoratorContext(/*val*/ true);
32500             }
32501             topLevel = savedTopLevel;
32502             setYieldContext(savedYieldContext);
32503             setAwaitContext(savedAwaitContext);
32504             return block;
32505         }
32506         function parseEmptyStatement() {
32507             var pos = getNodePos();
32508             parseExpected(26 /* SemicolonToken */);
32509             return finishNode(factory.createEmptyStatement(), pos);
32510         }
32511         function parseIfStatement() {
32512             var pos = getNodePos();
32513             parseExpected(98 /* IfKeyword */);
32514             parseExpected(20 /* OpenParenToken */);
32515             var expression = allowInAnd(parseExpression);
32516             parseExpected(21 /* CloseParenToken */);
32517             var thenStatement = parseStatement();
32518             var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined;
32519             return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos);
32520         }
32521         function parseDoStatement() {
32522             var pos = getNodePos();
32523             parseExpected(89 /* DoKeyword */);
32524             var statement = parseStatement();
32525             parseExpected(114 /* WhileKeyword */);
32526             parseExpected(20 /* OpenParenToken */);
32527             var expression = allowInAnd(parseExpression);
32528             parseExpected(21 /* CloseParenToken */);
32529             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
32530             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
32531             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
32532             //  do;while(0)x will have a semicolon inserted before x.
32533             parseOptional(26 /* SemicolonToken */);
32534             return finishNode(factory.createDoStatement(statement, expression), pos);
32535         }
32536         function parseWhileStatement() {
32537             var pos = getNodePos();
32538             parseExpected(114 /* WhileKeyword */);
32539             parseExpected(20 /* OpenParenToken */);
32540             var expression = allowInAnd(parseExpression);
32541             parseExpected(21 /* CloseParenToken */);
32542             var statement = parseStatement();
32543             return finishNode(factory.createWhileStatement(expression, statement), pos);
32544         }
32545         function parseForOrForInOrForOfStatement() {
32546             var pos = getNodePos();
32547             parseExpected(96 /* ForKeyword */);
32548             var awaitToken = parseOptionalToken(130 /* AwaitKeyword */);
32549             parseExpected(20 /* OpenParenToken */);
32550             var initializer;
32551             if (token() !== 26 /* SemicolonToken */) {
32552                 if (token() === 112 /* VarKeyword */ || token() === 118 /* LetKeyword */ || token() === 84 /* ConstKeyword */) {
32553                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
32554                 }
32555                 else {
32556                     initializer = disallowInAnd(parseExpression);
32557                 }
32558             }
32559             var node;
32560             if (awaitToken ? parseExpected(156 /* OfKeyword */) : parseOptional(156 /* OfKeyword */)) {
32561                 var expression = allowInAnd(parseAssignmentExpressionOrHigher);
32562                 parseExpected(21 /* CloseParenToken */);
32563                 node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement());
32564             }
32565             else if (parseOptional(100 /* InKeyword */)) {
32566                 var expression = allowInAnd(parseExpression);
32567                 parseExpected(21 /* CloseParenToken */);
32568                 node = factory.createForInStatement(initializer, expression, parseStatement());
32569             }
32570             else {
32571                 parseExpected(26 /* SemicolonToken */);
32572                 var condition = token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */
32573                     ? allowInAnd(parseExpression)
32574                     : undefined;
32575                 parseExpected(26 /* SemicolonToken */);
32576                 var incrementor = token() !== 21 /* CloseParenToken */
32577                     ? allowInAnd(parseExpression)
32578                     : undefined;
32579                 parseExpected(21 /* CloseParenToken */);
32580                 node = factory.createForStatement(initializer, condition, incrementor, parseStatement());
32581             }
32582             return finishNode(node, pos);
32583         }
32584         function parseBreakOrContinueStatement(kind) {
32585             var pos = getNodePos();
32586             parseExpected(kind === 241 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */);
32587             var label = canParseSemicolon() ? undefined : parseIdentifier();
32588             parseSemicolon();
32589             var node = kind === 241 /* BreakStatement */
32590                 ? factory.createBreakStatement(label)
32591                 : factory.createContinueStatement(label);
32592             return finishNode(node, pos);
32593         }
32594         function parseReturnStatement() {
32595             var pos = getNodePos();
32596             parseExpected(104 /* ReturnKeyword */);
32597             var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression);
32598             parseSemicolon();
32599             return finishNode(factory.createReturnStatement(expression), pos);
32600         }
32601         function parseWithStatement() {
32602             var pos = getNodePos();
32603             parseExpected(115 /* WithKeyword */);
32604             parseExpected(20 /* OpenParenToken */);
32605             var expression = allowInAnd(parseExpression);
32606             parseExpected(21 /* CloseParenToken */);
32607             var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
32608             return finishNode(factory.createWithStatement(expression, statement), pos);
32609         }
32610         function parseCaseClause() {
32611             var pos = getNodePos();
32612             parseExpected(81 /* CaseKeyword */);
32613             var expression = allowInAnd(parseExpression);
32614             parseExpected(58 /* ColonToken */);
32615             var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
32616             return finishNode(factory.createCaseClause(expression, statements), pos);
32617         }
32618         function parseDefaultClause() {
32619             var pos = getNodePos();
32620             parseExpected(87 /* DefaultKeyword */);
32621             parseExpected(58 /* ColonToken */);
32622             var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
32623             return finishNode(factory.createDefaultClause(statements), pos);
32624         }
32625         function parseCaseOrDefaultClause() {
32626             return token() === 81 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
32627         }
32628         function parseCaseBlock() {
32629             var pos = getNodePos();
32630             parseExpected(18 /* OpenBraceToken */);
32631             var clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
32632             parseExpected(19 /* CloseBraceToken */);
32633             return finishNode(factory.createCaseBlock(clauses), pos);
32634         }
32635         function parseSwitchStatement() {
32636             var pos = getNodePos();
32637             parseExpected(106 /* SwitchKeyword */);
32638             parseExpected(20 /* OpenParenToken */);
32639             var expression = allowInAnd(parseExpression);
32640             parseExpected(21 /* CloseParenToken */);
32641             var caseBlock = parseCaseBlock();
32642             return finishNode(factory.createSwitchStatement(expression, caseBlock), pos);
32643         }
32644         function parseThrowStatement() {
32645             // ThrowStatement[Yield] :
32646             //      throw [no LineTerminator here]Expression[In, ?Yield];
32647             var pos = getNodePos();
32648             parseExpected(108 /* ThrowKeyword */);
32649             // Because of automatic semicolon insertion, we need to report error if this
32650             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
32651             // directly as that might consume an expression on the following line.
32652             // Instead, we create a "missing" identifier, but don't report an error. The actual error
32653             // will be reported in the grammar walker.
32654             var expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
32655             if (expression === undefined) {
32656                 identifierCount++;
32657                 expression = finishNode(factory.createIdentifier(""), getNodePos());
32658             }
32659             parseSemicolon();
32660             return finishNode(factory.createThrowStatement(expression), pos);
32661         }
32662         // TODO: Review for error recovery
32663         function parseTryStatement() {
32664             var pos = getNodePos();
32665             parseExpected(110 /* TryKeyword */);
32666             var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
32667             var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined;
32668             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
32669             // one out no matter what.
32670             var finallyBlock;
32671             if (!catchClause || token() === 95 /* FinallyKeyword */) {
32672                 parseExpected(95 /* FinallyKeyword */);
32673                 finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
32674             }
32675             return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos);
32676         }
32677         function parseCatchClause() {
32678             var pos = getNodePos();
32679             parseExpected(82 /* CatchKeyword */);
32680             var variableDeclaration;
32681             if (parseOptional(20 /* OpenParenToken */)) {
32682                 variableDeclaration = parseVariableDeclaration();
32683                 parseExpected(21 /* CloseParenToken */);
32684             }
32685             else {
32686                 // Keep shape of node to avoid degrading performance.
32687                 variableDeclaration = undefined;
32688             }
32689             var block = parseBlock(/*ignoreMissingOpenBrace*/ false);
32690             return finishNode(factory.createCatchClause(variableDeclaration, block), pos);
32691         }
32692         function parseDebuggerStatement() {
32693             var pos = getNodePos();
32694             parseExpected(86 /* DebuggerKeyword */);
32695             parseSemicolon();
32696             return finishNode(factory.createDebuggerStatement(), pos);
32697         }
32698         function parseExpressionOrLabeledStatement() {
32699             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
32700             // out an expression, seeing if it is identifier and then seeing if it is followed by
32701             // a colon.
32702             var pos = getNodePos();
32703             var hasJSDoc = hasPrecedingJSDocComment();
32704             var node;
32705             var hasParen = token() === 20 /* OpenParenToken */;
32706             var expression = allowInAnd(parseExpression);
32707             if (ts.isIdentifier(expression) && parseOptional(58 /* ColonToken */)) {
32708                 node = factory.createLabeledStatement(expression, parseStatement());
32709             }
32710             else {
32711                 parseSemicolon();
32712                 node = factory.createExpressionStatement(expression);
32713                 if (hasParen) {
32714                     // do not parse the same jsdoc twice
32715                     hasJSDoc = false;
32716                 }
32717             }
32718             return withJSDoc(finishNode(node, pos), hasJSDoc);
32719         }
32720         function nextTokenIsIdentifierOrKeywordOnSameLine() {
32721             nextToken();
32722             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
32723         }
32724         function nextTokenIsClassKeywordOnSameLine() {
32725             nextToken();
32726             return token() === 83 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
32727         }
32728         function nextTokenIsFunctionKeywordOnSameLine() {
32729             nextToken();
32730             return token() === 97 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
32731         }
32732         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
32733             nextToken();
32734             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
32735         }
32736         function isDeclaration() {
32737             while (true) {
32738                 switch (token()) {
32739                     case 112 /* VarKeyword */:
32740                     case 118 /* LetKeyword */:
32741                     case 84 /* ConstKeyword */:
32742                     case 97 /* FunctionKeyword */:
32743                     case 83 /* ClassKeyword */:
32744                     case 91 /* EnumKeyword */:
32745                         return true;
32746                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
32747                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
32748                     // count on to parse out the respective declarations. For instance, we exploit this to say that
32749                     //
32750                     //    namespace n
32751                     //
32752                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
32753                     //
32754                     //    namespace
32755                     //    n
32756                     //
32757                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
32758                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
32759                     //
32760                     // *Note*: 'interface' is actually a strict mode reserved word. So while
32761                     //
32762                     //   "use strict"
32763                     //   interface
32764                     //   I {}
32765                     //
32766                     // could be legal, it would add complexity for very little gain.
32767                     case 117 /* InterfaceKeyword */:
32768                     case 149 /* TypeKeyword */:
32769                         return nextTokenIsIdentifierOnSameLine();
32770                     case 139 /* ModuleKeyword */:
32771                     case 140 /* NamespaceKeyword */:
32772                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
32773                     case 125 /* AbstractKeyword */:
32774                     case 129 /* AsyncKeyword */:
32775                     case 133 /* DeclareKeyword */:
32776                     case 120 /* PrivateKeyword */:
32777                     case 121 /* ProtectedKeyword */:
32778                     case 122 /* PublicKeyword */:
32779                     case 142 /* ReadonlyKeyword */:
32780                         nextToken();
32781                         // ASI takes effect for this modifier.
32782                         if (scanner.hasPrecedingLineBreak()) {
32783                             return false;
32784                         }
32785                         continue;
32786                     case 154 /* GlobalKeyword */:
32787                         nextToken();
32788                         return token() === 18 /* OpenBraceToken */ || token() === 78 /* Identifier */ || token() === 92 /* ExportKeyword */;
32789                     case 99 /* ImportKeyword */:
32790                         nextToken();
32791                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
32792                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
32793                     case 92 /* ExportKeyword */:
32794                         var currentToken_1 = nextToken();
32795                         if (currentToken_1 === 149 /* TypeKeyword */) {
32796                             currentToken_1 = lookAhead(nextToken);
32797                         }
32798                         if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
32799                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 87 /* DefaultKeyword */ ||
32800                             currentToken_1 === 126 /* AsKeyword */) {
32801                             return true;
32802                         }
32803                         continue;
32804                     case 123 /* StaticKeyword */:
32805                         nextToken();
32806                         continue;
32807                     default:
32808                         return false;
32809                 }
32810             }
32811         }
32812         function isStartOfDeclaration() {
32813             return lookAhead(isDeclaration);
32814         }
32815         function isStartOfStatement() {
32816             switch (token()) {
32817                 case 59 /* AtToken */:
32818                 case 26 /* SemicolonToken */:
32819                 case 18 /* OpenBraceToken */:
32820                 case 112 /* VarKeyword */:
32821                 case 118 /* LetKeyword */:
32822                 case 97 /* FunctionKeyword */:
32823                 case 83 /* ClassKeyword */:
32824                 case 91 /* EnumKeyword */:
32825                 case 98 /* IfKeyword */:
32826                 case 89 /* DoKeyword */:
32827                 case 114 /* WhileKeyword */:
32828                 case 96 /* ForKeyword */:
32829                 case 85 /* ContinueKeyword */:
32830                 case 80 /* BreakKeyword */:
32831                 case 104 /* ReturnKeyword */:
32832                 case 115 /* WithKeyword */:
32833                 case 106 /* SwitchKeyword */:
32834                 case 108 /* ThrowKeyword */:
32835                 case 110 /* TryKeyword */:
32836                 case 86 /* DebuggerKeyword */:
32837                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
32838                 // however, we say they are here so that we may gracefully parse them and error later.
32839                 // falls through
32840                 case 82 /* CatchKeyword */:
32841                 case 95 /* FinallyKeyword */:
32842                     return true;
32843                 case 99 /* ImportKeyword */:
32844                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
32845                 case 84 /* ConstKeyword */:
32846                 case 92 /* ExportKeyword */:
32847                     return isStartOfDeclaration();
32848                 case 129 /* AsyncKeyword */:
32849                 case 133 /* DeclareKeyword */:
32850                 case 117 /* InterfaceKeyword */:
32851                 case 139 /* ModuleKeyword */:
32852                 case 140 /* NamespaceKeyword */:
32853                 case 149 /* TypeKeyword */:
32854                 case 154 /* GlobalKeyword */:
32855                     // When these don't start a declaration, they're an identifier in an expression statement
32856                     return true;
32857                 case 122 /* PublicKeyword */:
32858                 case 120 /* PrivateKeyword */:
32859                 case 121 /* ProtectedKeyword */:
32860                 case 123 /* StaticKeyword */:
32861                 case 142 /* ReadonlyKeyword */:
32862                     // When these don't start a declaration, they may be the start of a class member if an identifier
32863                     // immediately follows. Otherwise they're an identifier in an expression statement.
32864                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
32865                 default:
32866                     return isStartOfExpression();
32867             }
32868         }
32869         function nextTokenIsIdentifierOrStartOfDestructuring() {
32870             nextToken();
32871             return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
32872         }
32873         function isLetDeclaration() {
32874             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
32875             // or [.
32876             return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
32877         }
32878         function parseStatement() {
32879             switch (token()) {
32880                 case 26 /* SemicolonToken */:
32881                     return parseEmptyStatement();
32882                 case 18 /* OpenBraceToken */:
32883                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
32884                 case 112 /* VarKeyword */:
32885                     return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32886                 case 118 /* LetKeyword */:
32887                     if (isLetDeclaration()) {
32888                         return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32889                     }
32890                     break;
32891                 case 97 /* FunctionKeyword */:
32892                     return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32893                 case 83 /* ClassKeyword */:
32894                     return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32895                 case 98 /* IfKeyword */:
32896                     return parseIfStatement();
32897                 case 89 /* DoKeyword */:
32898                     return parseDoStatement();
32899                 case 114 /* WhileKeyword */:
32900                     return parseWhileStatement();
32901                 case 96 /* ForKeyword */:
32902                     return parseForOrForInOrForOfStatement();
32903                 case 85 /* ContinueKeyword */:
32904                     return parseBreakOrContinueStatement(240 /* ContinueStatement */);
32905                 case 80 /* BreakKeyword */:
32906                     return parseBreakOrContinueStatement(241 /* BreakStatement */);
32907                 case 104 /* ReturnKeyword */:
32908                     return parseReturnStatement();
32909                 case 115 /* WithKeyword */:
32910                     return parseWithStatement();
32911                 case 106 /* SwitchKeyword */:
32912                     return parseSwitchStatement();
32913                 case 108 /* ThrowKeyword */:
32914                     return parseThrowStatement();
32915                 case 110 /* TryKeyword */:
32916                 // Include 'catch' and 'finally' for error recovery.
32917                 // falls through
32918                 case 82 /* CatchKeyword */:
32919                 case 95 /* FinallyKeyword */:
32920                     return parseTryStatement();
32921                 case 86 /* DebuggerKeyword */:
32922                     return parseDebuggerStatement();
32923                 case 59 /* AtToken */:
32924                     return parseDeclaration();
32925                 case 129 /* AsyncKeyword */:
32926                 case 117 /* InterfaceKeyword */:
32927                 case 149 /* TypeKeyword */:
32928                 case 139 /* ModuleKeyword */:
32929                 case 140 /* NamespaceKeyword */:
32930                 case 133 /* DeclareKeyword */:
32931                 case 84 /* ConstKeyword */:
32932                 case 91 /* EnumKeyword */:
32933                 case 92 /* ExportKeyword */:
32934                 case 99 /* ImportKeyword */:
32935                 case 120 /* PrivateKeyword */:
32936                 case 121 /* ProtectedKeyword */:
32937                 case 122 /* PublicKeyword */:
32938                 case 125 /* AbstractKeyword */:
32939                 case 123 /* StaticKeyword */:
32940                 case 142 /* ReadonlyKeyword */:
32941                 case 154 /* GlobalKeyword */:
32942                     if (isStartOfDeclaration()) {
32943                         return parseDeclaration();
32944                     }
32945                     break;
32946             }
32947             return parseExpressionOrLabeledStatement();
32948         }
32949         function isDeclareModifier(modifier) {
32950             return modifier.kind === 133 /* DeclareKeyword */;
32951         }
32952         function parseDeclaration() {
32953             // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner
32954             //       if we can't reuse the declaration, so that we don't do this work twice?
32955             //
32956             // `parseListElement` attempted to get the reused node at this position,
32957             // but the ambient context flag was not yet set, so the node appeared
32958             // not reusable in that context.
32959             var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier);
32960             if (isAmbient) {
32961                 var node = tryReuseAmbientDeclaration();
32962                 if (node) {
32963                     return node;
32964                 }
32965             }
32966             var pos = getNodePos();
32967             var hasJSDoc = hasPrecedingJSDocComment();
32968             var decorators = parseDecorators();
32969             var modifiers = parseModifiers();
32970             if (isAmbient) {
32971                 for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
32972                     var m = _a[_i];
32973                     m.flags |= 8388608 /* Ambient */;
32974                 }
32975                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); });
32976             }
32977             else {
32978                 return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers);
32979             }
32980         }
32981         function tryReuseAmbientDeclaration() {
32982             return doInsideOfContext(8388608 /* Ambient */, function () {
32983                 var node = currentNode(parsingContext);
32984                 if (node) {
32985                     return consumeNode(node);
32986                 }
32987             });
32988         }
32989         function parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers) {
32990             switch (token()) {
32991                 case 112 /* VarKeyword */:
32992                 case 118 /* LetKeyword */:
32993                 case 84 /* ConstKeyword */:
32994                     return parseVariableStatement(pos, hasJSDoc, decorators, modifiers);
32995                 case 97 /* FunctionKeyword */:
32996                     return parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers);
32997                 case 83 /* ClassKeyword */:
32998                     return parseClassDeclaration(pos, hasJSDoc, decorators, modifiers);
32999                 case 117 /* InterfaceKeyword */:
33000                     return parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers);
33001                 case 149 /* TypeKeyword */:
33002                     return parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers);
33003                 case 91 /* EnumKeyword */:
33004                     return parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers);
33005                 case 154 /* GlobalKeyword */:
33006                 case 139 /* ModuleKeyword */:
33007                 case 140 /* NamespaceKeyword */:
33008                     return parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
33009                 case 99 /* ImportKeyword */:
33010                     return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers);
33011                 case 92 /* ExportKeyword */:
33012                     nextToken();
33013                     switch (token()) {
33014                         case 87 /* DefaultKeyword */:
33015                         case 62 /* EqualsToken */:
33016                             return parseExportAssignment(pos, hasJSDoc, decorators, modifiers);
33017                         case 126 /* AsKeyword */:
33018                             return parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers);
33019                         default:
33020                             return parseExportDeclaration(pos, hasJSDoc, decorators, modifiers);
33021                     }
33022                 default:
33023                     if (decorators || modifiers) {
33024                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
33025                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
33026                         var missing = createMissingNode(271 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
33027                         ts.setTextRangePos(missing, pos);
33028                         missing.decorators = decorators;
33029                         missing.modifiers = modifiers;
33030                         return missing;
33031                     }
33032                     return undefined; // TODO: GH#18217
33033             }
33034         }
33035         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
33036             nextToken();
33037             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
33038         }
33039         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
33040             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
33041                 parseSemicolon();
33042                 return;
33043             }
33044             return parseFunctionBlock(flags, diagnosticMessage);
33045         }
33046         // DECLARATIONS
33047         function parseArrayBindingElement() {
33048             var pos = getNodePos();
33049             if (token() === 27 /* CommaToken */) {
33050                 return finishNode(factory.createOmittedExpression(), pos);
33051             }
33052             var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
33053             var name = parseIdentifierOrPattern();
33054             var initializer = parseInitializer();
33055             return finishNode(factory.createBindingElement(dotDotDotToken, /*propertyName*/ undefined, name, initializer), pos);
33056         }
33057         function parseObjectBindingElement() {
33058             var pos = getNodePos();
33059             var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
33060             var tokenIsIdentifier = isBindingIdentifier();
33061             var propertyName = parsePropertyName();
33062             var name;
33063             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
33064                 name = propertyName;
33065                 propertyName = undefined;
33066             }
33067             else {
33068                 parseExpected(58 /* ColonToken */);
33069                 name = parseIdentifierOrPattern();
33070             }
33071             var initializer = parseInitializer();
33072             return finishNode(factory.createBindingElement(dotDotDotToken, propertyName, name, initializer), pos);
33073         }
33074         function parseObjectBindingPattern() {
33075             var pos = getNodePos();
33076             parseExpected(18 /* OpenBraceToken */);
33077             var elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
33078             parseExpected(19 /* CloseBraceToken */);
33079             return finishNode(factory.createObjectBindingPattern(elements), pos);
33080         }
33081         function parseArrayBindingPattern() {
33082             var pos = getNodePos();
33083             parseExpected(22 /* OpenBracketToken */);
33084             var elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
33085             parseExpected(23 /* CloseBracketToken */);
33086             return finishNode(factory.createArrayBindingPattern(elements), pos);
33087         }
33088         function isBindingIdentifierOrPrivateIdentifierOrPattern() {
33089             return token() === 18 /* OpenBraceToken */
33090                 || token() === 22 /* OpenBracketToken */
33091                 || token() === 79 /* PrivateIdentifier */
33092                 || isBindingIdentifier();
33093         }
33094         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
33095             if (token() === 22 /* OpenBracketToken */) {
33096                 return parseArrayBindingPattern();
33097             }
33098             if (token() === 18 /* OpenBraceToken */) {
33099                 return parseObjectBindingPattern();
33100             }
33101             return parseBindingIdentifier(privateIdentifierDiagnosticMessage);
33102         }
33103         function parseVariableDeclarationAllowExclamation() {
33104             return parseVariableDeclaration(/*allowExclamation*/ true);
33105         }
33106         function parseVariableDeclaration(allowExclamation) {
33107             var pos = getNodePos();
33108             var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
33109             var exclamationToken;
33110             if (allowExclamation && name.kind === 78 /* Identifier */ &&
33111                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
33112                 exclamationToken = parseTokenNode();
33113             }
33114             var type = parseTypeAnnotation();
33115             var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer();
33116             var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer);
33117             return finishNode(node, pos);
33118         }
33119         function parseVariableDeclarationList(inForStatementInitializer) {
33120             var pos = getNodePos();
33121             var flags = 0;
33122             switch (token()) {
33123                 case 112 /* VarKeyword */:
33124                     break;
33125                 case 118 /* LetKeyword */:
33126                     flags |= 1 /* Let */;
33127                     break;
33128                 case 84 /* ConstKeyword */:
33129                     flags |= 2 /* Const */;
33130                     break;
33131                 default:
33132                     ts.Debug.fail();
33133             }
33134             nextToken();
33135             // The user may have written the following:
33136             //
33137             //    for (let of X) { }
33138             //
33139             // In this case, we want to parse an empty declaration list, and then parse 'of'
33140             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
33141             // So we need to look ahead to determine if 'of' should be treated as a keyword in
33142             // this context.
33143             // The checker will then give an error that there is an empty declaration list.
33144             var declarations;
33145             if (token() === 156 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
33146                 declarations = createMissingList();
33147             }
33148             else {
33149                 var savedDisallowIn = inDisallowInContext();
33150                 setDisallowInContext(inForStatementInitializer);
33151                 declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
33152                 setDisallowInContext(savedDisallowIn);
33153             }
33154             return finishNode(factory.createVariableDeclarationList(declarations, flags), pos);
33155         }
33156         function canFollowContextualOfKeyword() {
33157             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
33158         }
33159         function parseVariableStatement(pos, hasJSDoc, decorators, modifiers) {
33160             var declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
33161             parseSemicolon();
33162             var node = factory.createVariableStatement(modifiers, declarationList);
33163             // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker.
33164             node.decorators = decorators;
33165             return withJSDoc(finishNode(node, pos), hasJSDoc);
33166         }
33167         function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) {
33168             var savedAwaitContext = inAwaitContext();
33169             var modifierFlags = ts.modifiersToFlags(modifiers);
33170             parseExpected(97 /* FunctionKeyword */);
33171             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
33172             // We don't parse the name here in await context, instead we will report a grammar error in the checker.
33173             var name = modifierFlags & 512 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier();
33174             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
33175             var isAsync = modifierFlags & 256 /* Async */ ? 2 /* Await */ : 0 /* None */;
33176             var typeParameters = parseTypeParameters();
33177             if (modifierFlags & 1 /* Export */)
33178                 setAwaitContext(/*value*/ true);
33179             var parameters = parseParameters(isGenerator | isAsync);
33180             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33181             var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
33182             setAwaitContext(savedAwaitContext);
33183             var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body);
33184             return withJSDoc(finishNode(node, pos), hasJSDoc);
33185         }
33186         function parseConstructorName() {
33187             if (token() === 132 /* ConstructorKeyword */) {
33188                 return parseExpected(132 /* ConstructorKeyword */);
33189             }
33190             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
33191                 return tryParse(function () {
33192                     var literalNode = parseLiteralNode();
33193                     return literalNode.text === "constructor" ? literalNode : undefined;
33194                 });
33195             }
33196         }
33197         function tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers) {
33198             return tryParse(function () {
33199                 if (parseConstructorName()) {
33200                     var typeParameters = parseTypeParameters();
33201                     var parameters = parseParameters(0 /* None */);
33202                     var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33203                     var body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
33204                     var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body);
33205                     // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker.
33206                     node.typeParameters = typeParameters;
33207                     node.type = type;
33208                     return withJSDoc(finishNode(node, pos), hasJSDoc);
33209                 }
33210             });
33211         }
33212         function parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken, diagnosticMessage) {
33213             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
33214             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
33215             var typeParameters = parseTypeParameters();
33216             var parameters = parseParameters(isGenerator | isAsync);
33217             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33218             var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
33219             var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body);
33220             // An exclamation token on a method is invalid syntax and will be handled by the grammar checker
33221             node.exclamationToken = exclamationToken;
33222             return withJSDoc(finishNode(node, pos), hasJSDoc);
33223         }
33224         function parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken) {
33225             var exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(53 /* ExclamationToken */) : undefined;
33226             var type = parseTypeAnnotation();
33227             var initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
33228             parseSemicolon();
33229             var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer);
33230             return withJSDoc(finishNode(node, pos), hasJSDoc);
33231         }
33232         function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) {
33233             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
33234             var name = parsePropertyName();
33235             // Note: this is not legal as per the grammar.  But we allow it in the parser and
33236             // report an error in the grammar checker.
33237             var questionToken = parseOptionalToken(57 /* QuestionToken */);
33238             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
33239                 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ undefined, ts.Diagnostics.or_expected);
33240             }
33241             return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken);
33242         }
33243         function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) {
33244             var name = parsePropertyName();
33245             var typeParameters = parseTypeParameters();
33246             var parameters = parseParameters(0 /* None */);
33247             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33248             var body = parseFunctionBlockOrSemicolon(0 /* None */);
33249             var node = kind === 167 /* GetAccessor */
33250                 ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body)
33251                 : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body);
33252             // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors
33253             node.typeParameters = typeParameters;
33254             if (type && node.kind === 168 /* SetAccessor */)
33255                 node.type = type;
33256             return withJSDoc(finishNode(node, pos), hasJSDoc);
33257         }
33258         function isClassMemberStart() {
33259             var idToken;
33260             if (token() === 59 /* AtToken */) {
33261                 return true;
33262             }
33263             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
33264             while (ts.isModifierKind(token())) {
33265                 idToken = token();
33266                 // If the idToken is a class modifier (protected, private, public, and static), it is
33267                 // certain that we are starting to parse class member. This allows better error recovery
33268                 // Example:
33269                 //      public foo() ...     // true
33270                 //      public @dec blah ... // true; we will then report an error later
33271                 //      export public ...    // true; we will then report an error later
33272                 if (ts.isClassMemberModifier(idToken)) {
33273                     return true;
33274                 }
33275                 nextToken();
33276             }
33277             if (token() === 41 /* AsteriskToken */) {
33278                 return true;
33279             }
33280             // Try to get the first property-like token following all modifiers.
33281             // This can either be an identifier or the 'get' or 'set' keywords.
33282             if (isLiteralPropertyName()) {
33283                 idToken = token();
33284                 nextToken();
33285             }
33286             // Index signatures and computed properties are class members; we can parse.
33287             if (token() === 22 /* OpenBracketToken */) {
33288                 return true;
33289             }
33290             // If we were able to get any potential identifier...
33291             if (idToken !== undefined) {
33292                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
33293                 if (!ts.isKeyword(idToken) || idToken === 146 /* SetKeyword */ || idToken === 134 /* GetKeyword */) {
33294                     return true;
33295                 }
33296                 // If it *is* a keyword, but not an accessor, check a little farther along
33297                 // to see if it should actually be parsed as a class member.
33298                 switch (token()) {
33299                     case 20 /* OpenParenToken */: // Method declaration
33300                     case 29 /* LessThanToken */: // Generic Method declaration
33301                     case 53 /* ExclamationToken */: // Non-null assertion on property name
33302                     case 58 /* ColonToken */: // Type Annotation for declaration
33303                     case 62 /* EqualsToken */: // Initializer for declaration
33304                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
33305                         return true;
33306                     default:
33307                         // Covers
33308                         //  - Semicolons     (declaration termination)
33309                         //  - Closing braces (end-of-class, must be declaration)
33310                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
33311                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
33312                         return canParseSemicolon();
33313                 }
33314             }
33315             return false;
33316         }
33317         function parseDecoratorExpression() {
33318             if (inAwaitContext() && token() === 130 /* AwaitKeyword */) {
33319                 // `@await` is is disallowed in an [Await] context, but can cause parsing to go off the rails
33320                 // This simply parses the missing identifier and moves on.
33321                 var pos = getNodePos();
33322                 var awaitExpression = parseIdentifier(ts.Diagnostics.Expression_expected);
33323                 nextToken();
33324                 var memberExpression = parseMemberExpressionRest(pos, awaitExpression, /*allowOptionalChain*/ true);
33325                 return parseCallExpressionRest(pos, memberExpression);
33326             }
33327             return parseLeftHandSideExpressionOrHigher();
33328         }
33329         function tryParseDecorator() {
33330             var pos = getNodePos();
33331             if (!parseOptional(59 /* AtToken */)) {
33332                 return undefined;
33333             }
33334             var expression = doInDecoratorContext(parseDecoratorExpression);
33335             return finishNode(factory.createDecorator(expression), pos);
33336         }
33337         function parseDecorators() {
33338             var pos = getNodePos();
33339             var list, decorator;
33340             while (decorator = tryParseDecorator()) {
33341                 list = ts.append(list, decorator);
33342             }
33343             return list && createNodeArray(list, pos);
33344         }
33345         function tryParseModifier(permitInvalidConstAsModifier) {
33346             var pos = getNodePos();
33347             var kind = token();
33348             if (token() === 84 /* ConstKeyword */ && permitInvalidConstAsModifier) {
33349                 // We need to ensure that any subsequent modifiers appear on the same line
33350                 // so that when 'const' is a standalone declaration, we don't issue an error.
33351                 if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
33352                     return undefined;
33353                 }
33354             }
33355             else {
33356                 if (!parseAnyContextualModifier()) {
33357                     return undefined;
33358                 }
33359             }
33360             return finishNode(factory.createToken(kind), pos);
33361         }
33362         /*
33363          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
33364          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
33365          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
33366          *
33367          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
33368          */
33369         function parseModifiers(permitInvalidConstAsModifier) {
33370             var pos = getNodePos();
33371             var list, modifier;
33372             while (modifier = tryParseModifier(permitInvalidConstAsModifier)) {
33373                 list = ts.append(list, modifier);
33374             }
33375             return list && createNodeArray(list, pos);
33376         }
33377         function parseModifiersForArrowFunction() {
33378             var modifiers;
33379             if (token() === 129 /* AsyncKeyword */) {
33380                 var pos = getNodePos();
33381                 nextToken();
33382                 var modifier = finishNode(factory.createToken(129 /* AsyncKeyword */), pos);
33383                 modifiers = createNodeArray([modifier], pos);
33384             }
33385             return modifiers;
33386         }
33387         function parseClassElement() {
33388             var pos = getNodePos();
33389             if (token() === 26 /* SemicolonToken */) {
33390                 nextToken();
33391                 return finishNode(factory.createSemicolonClassElement(), pos);
33392             }
33393             var hasJSDoc = hasPrecedingJSDocComment();
33394             var decorators = parseDecorators();
33395             var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
33396             if (parseContextualModifier(134 /* GetKeyword */)) {
33397                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */);
33398             }
33399             if (parseContextualModifier(146 /* SetKeyword */)) {
33400                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */);
33401             }
33402             if (token() === 132 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
33403                 var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers);
33404                 if (constructorDeclaration) {
33405                     return constructorDeclaration;
33406                 }
33407             }
33408             if (isIndexSignature()) {
33409                 return parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers);
33410             }
33411             // It is very important that we check this *after* checking indexers because
33412             // the [ token can start an index signature or a computed property name
33413             if (ts.tokenIsIdentifierOrKeyword(token()) ||
33414                 token() === 10 /* StringLiteral */ ||
33415                 token() === 8 /* NumericLiteral */ ||
33416                 token() === 41 /* AsteriskToken */ ||
33417                 token() === 22 /* OpenBracketToken */) {
33418                 var isAmbient = ts.some(modifiers, isDeclareModifier);
33419                 if (isAmbient) {
33420                     for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
33421                         var m = _a[_i];
33422                         m.flags |= 8388608 /* Ambient */;
33423                     }
33424                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers); });
33425                 }
33426                 else {
33427                     return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers);
33428                 }
33429             }
33430             if (decorators || modifiers) {
33431                 // treat this as a property declaration with a missing name.
33432                 var name = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
33433                 return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, /*questionToken*/ undefined);
33434             }
33435             // 'isClassMemberStart' should have hinted not to attempt parsing.
33436             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
33437         }
33438         function parseClassExpression() {
33439             return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 221 /* ClassExpression */);
33440         }
33441         function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) {
33442             return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 252 /* ClassDeclaration */);
33443         }
33444         function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) {
33445             var savedAwaitContext = inAwaitContext();
33446             parseExpected(83 /* ClassKeyword */);
33447             // We don't parse the name here in await context, instead we will report a grammar error in the checker.
33448             var name = parseNameOfClassDeclarationOrExpression();
33449             var typeParameters = parseTypeParameters();
33450             if (ts.some(modifiers, ts.isExportModifier))
33451                 setAwaitContext(/*value*/ true);
33452             var heritageClauses = parseHeritageClauses();
33453             var members;
33454             if (parseExpected(18 /* OpenBraceToken */)) {
33455                 // ClassTail[Yield,Await] : (Modified) See 14.5
33456                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
33457                 members = parseClassMembers();
33458                 parseExpected(19 /* CloseBraceToken */);
33459             }
33460             else {
33461                 members = createMissingList();
33462             }
33463             setAwaitContext(savedAwaitContext);
33464             var node = kind === 252 /* ClassDeclaration */
33465                 ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members)
33466                 : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members);
33467             return withJSDoc(finishNode(node, pos), hasJSDoc);
33468         }
33469         function parseNameOfClassDeclarationOrExpression() {
33470             // implements is a future reserved word so
33471             // 'class implements' might mean either
33472             // - class expression with omitted name, 'implements' starts heritage clause
33473             // - class with name 'implements'
33474             // 'isImplementsClause' helps to disambiguate between these two cases
33475             return isBindingIdentifier() && !isImplementsClause()
33476                 ? createIdentifier(isBindingIdentifier())
33477                 : undefined;
33478         }
33479         function isImplementsClause() {
33480             return token() === 116 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
33481         }
33482         function parseHeritageClauses() {
33483             // ClassTail[Yield,Await] : (Modified) See 14.5
33484             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
33485             if (isHeritageClause()) {
33486                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
33487             }
33488             return undefined;
33489         }
33490         function parseHeritageClause() {
33491             var pos = getNodePos();
33492             var tok = token();
33493             ts.Debug.assert(tok === 93 /* ExtendsKeyword */ || tok === 116 /* ImplementsKeyword */); // isListElement() should ensure this.
33494             nextToken();
33495             var types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
33496             return finishNode(factory.createHeritageClause(tok, types), pos);
33497         }
33498         function parseExpressionWithTypeArguments() {
33499             var pos = getNodePos();
33500             var expression = parseLeftHandSideExpressionOrHigher();
33501             var typeArguments = tryParseTypeArguments();
33502             return finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos);
33503         }
33504         function tryParseTypeArguments() {
33505             return token() === 29 /* LessThanToken */ ?
33506                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
33507         }
33508         function isHeritageClause() {
33509             return token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
33510         }
33511         function parseClassMembers() {
33512             return parseList(5 /* ClassMembers */, parseClassElement);
33513         }
33514         function parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers) {
33515             parseExpected(117 /* InterfaceKeyword */);
33516             var name = parseIdentifier();
33517             var typeParameters = parseTypeParameters();
33518             var heritageClauses = parseHeritageClauses();
33519             var members = parseObjectTypeMembers();
33520             var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members);
33521             return withJSDoc(finishNode(node, pos), hasJSDoc);
33522         }
33523         function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) {
33524             parseExpected(149 /* TypeKeyword */);
33525             var name = parseIdentifier();
33526             var typeParameters = parseTypeParameters();
33527             parseExpected(62 /* EqualsToken */);
33528             var type = token() === 136 /* IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType();
33529             parseSemicolon();
33530             var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type);
33531             return withJSDoc(finishNode(node, pos), hasJSDoc);
33532         }
33533         // In an ambient declaration, the grammar only allows integer literals as initializers.
33534         // In a non-ambient declaration, the grammar allows uninitialized members only in a
33535         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
33536         // or any time an integer literal initializer is encountered.
33537         function parseEnumMember() {
33538             var pos = getNodePos();
33539             var hasJSDoc = hasPrecedingJSDocComment();
33540             var name = parsePropertyName();
33541             var initializer = allowInAnd(parseInitializer);
33542             return withJSDoc(finishNode(factory.createEnumMember(name, initializer), pos), hasJSDoc);
33543         }
33544         function parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers) {
33545             parseExpected(91 /* EnumKeyword */);
33546             var name = parseIdentifier();
33547             var members;
33548             if (parseExpected(18 /* OpenBraceToken */)) {
33549                 members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
33550                 parseExpected(19 /* CloseBraceToken */);
33551             }
33552             else {
33553                 members = createMissingList();
33554             }
33555             var node = factory.createEnumDeclaration(decorators, modifiers, name, members);
33556             return withJSDoc(finishNode(node, pos), hasJSDoc);
33557         }
33558         function parseModuleBlock() {
33559             var pos = getNodePos();
33560             var statements;
33561             if (parseExpected(18 /* OpenBraceToken */)) {
33562                 statements = parseList(1 /* BlockStatements */, parseStatement);
33563                 parseExpected(19 /* CloseBraceToken */);
33564             }
33565             else {
33566                 statements = createMissingList();
33567             }
33568             return finishNode(factory.createModuleBlock(statements), pos);
33569         }
33570         function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags) {
33571             // If we are parsing a dotted namespace name, we want to
33572             // propagate the 'Namespace' flag across the names if set.
33573             var namespaceFlag = flags & 16 /* Namespace */;
33574             var name = parseIdentifier();
33575             var body = parseOptional(24 /* DotToken */)
33576                 ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag)
33577                 : parseModuleBlock();
33578             var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
33579             return withJSDoc(finishNode(node, pos), hasJSDoc);
33580         }
33581         function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
33582             var flags = 0;
33583             var name;
33584             if (token() === 154 /* GlobalKeyword */) {
33585                 // parse 'global' as name of global scope augmentation
33586                 name = parseIdentifier();
33587                 flags |= 1024 /* GlobalAugmentation */;
33588             }
33589             else {
33590                 name = parseLiteralNode();
33591                 name.text = internIdentifier(name.text);
33592             }
33593             var body;
33594             if (token() === 18 /* OpenBraceToken */) {
33595                 body = parseModuleBlock();
33596             }
33597             else {
33598                 parseSemicolon();
33599             }
33600             var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
33601             return withJSDoc(finishNode(node, pos), hasJSDoc);
33602         }
33603         function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
33604             var flags = 0;
33605             if (token() === 154 /* GlobalKeyword */) {
33606                 // global augmentation
33607                 return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
33608             }
33609             else if (parseOptional(140 /* NamespaceKeyword */)) {
33610                 flags |= 16 /* Namespace */;
33611             }
33612             else {
33613                 parseExpected(139 /* ModuleKeyword */);
33614                 if (token() === 10 /* StringLiteral */) {
33615                     return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
33616                 }
33617             }
33618             return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags);
33619         }
33620         function isExternalModuleReference() {
33621             return token() === 143 /* RequireKeyword */ &&
33622                 lookAhead(nextTokenIsOpenParen);
33623         }
33624         function nextTokenIsOpenParen() {
33625             return nextToken() === 20 /* OpenParenToken */;
33626         }
33627         function nextTokenIsSlash() {
33628             return nextToken() === 43 /* SlashToken */;
33629         }
33630         function parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
33631             parseExpected(126 /* AsKeyword */);
33632             parseExpected(140 /* NamespaceKeyword */);
33633             var name = parseIdentifier();
33634             parseSemicolon();
33635             var node = factory.createNamespaceExportDeclaration(name);
33636             // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker
33637             node.decorators = decorators;
33638             node.modifiers = modifiers;
33639             return withJSDoc(finishNode(node, pos), hasJSDoc);
33640         }
33641         function parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers) {
33642             parseExpected(99 /* ImportKeyword */);
33643             var afterImportPos = scanner.getStartPos();
33644             // We don't parse the identifier here in await context, instead we will report a grammar error in the checker.
33645             var identifier;
33646             if (isIdentifier()) {
33647                 identifier = parseIdentifier();
33648             }
33649             var isTypeOnly = false;
33650             if (token() !== 153 /* FromKeyword */ &&
33651                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
33652                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
33653                 isTypeOnly = true;
33654                 identifier = isIdentifier() ? parseIdentifier() : undefined;
33655             }
33656             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
33657                 return parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly);
33658             }
33659             // ImportDeclaration:
33660             //  import ImportClause from ModuleSpecifier ;
33661             //  import ModuleSpecifier;
33662             var importClause;
33663             if (identifier || // import id
33664                 token() === 41 /* AsteriskToken */ || // import *
33665                 token() === 18 /* OpenBraceToken */ // import {
33666             ) {
33667                 importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
33668                 parseExpected(153 /* FromKeyword */);
33669             }
33670             var moduleSpecifier = parseModuleSpecifier();
33671             parseSemicolon();
33672             var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier);
33673             return withJSDoc(finishNode(node, pos), hasJSDoc);
33674         }
33675         function tokenAfterImportDefinitelyProducesImportDeclaration() {
33676             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
33677         }
33678         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
33679             // In `import id ___`, the current token decides whether to produce
33680             // an ImportDeclaration or ImportEqualsDeclaration.
33681             return token() === 27 /* CommaToken */ || token() === 153 /* FromKeyword */;
33682         }
33683         function parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly) {
33684             parseExpected(62 /* EqualsToken */);
33685             var moduleReference = parseModuleReference();
33686             parseSemicolon();
33687             var node = factory.createImportEqualsDeclaration(decorators, modifiers, identifier, moduleReference);
33688             var finished = withJSDoc(finishNode(node, pos), hasJSDoc);
33689             if (isTypeOnly) {
33690                 parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
33691             }
33692             return finished;
33693         }
33694         function parseImportClause(identifier, pos, isTypeOnly) {
33695             // ImportClause:
33696             //  ImportedDefaultBinding
33697             //  NameSpaceImport
33698             //  NamedImports
33699             //  ImportedDefaultBinding, NameSpaceImport
33700             //  ImportedDefaultBinding, NamedImports
33701             // If there was no default import or if there is comma token after default import
33702             // parse namespace or named imports
33703             var namedBindings;
33704             if (!identifier ||
33705                 parseOptional(27 /* CommaToken */)) {
33706                 namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(264 /* NamedImports */);
33707             }
33708             return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos);
33709         }
33710         function parseModuleReference() {
33711             return isExternalModuleReference()
33712                 ? parseExternalModuleReference()
33713                 : parseEntityName(/*allowReservedWords*/ false);
33714         }
33715         function parseExternalModuleReference() {
33716             var pos = getNodePos();
33717             parseExpected(143 /* RequireKeyword */);
33718             parseExpected(20 /* OpenParenToken */);
33719             var expression = parseModuleSpecifier();
33720             parseExpected(21 /* CloseParenToken */);
33721             return finishNode(factory.createExternalModuleReference(expression), pos);
33722         }
33723         function parseModuleSpecifier() {
33724             if (token() === 10 /* StringLiteral */) {
33725                 var result = parseLiteralNode();
33726                 result.text = internIdentifier(result.text);
33727                 return result;
33728             }
33729             else {
33730                 // We allow arbitrary expressions here, even though the grammar only allows string
33731                 // literals.  We check to ensure that it is only a string literal later in the grammar
33732                 // check pass.
33733                 return parseExpression();
33734             }
33735         }
33736         function parseNamespaceImport() {
33737             // NameSpaceImport:
33738             //  * as ImportedBinding
33739             var pos = getNodePos();
33740             parseExpected(41 /* AsteriskToken */);
33741             parseExpected(126 /* AsKeyword */);
33742             var name = parseIdentifier();
33743             return finishNode(factory.createNamespaceImport(name), pos);
33744         }
33745         function parseNamedImportsOrExports(kind) {
33746             var pos = getNodePos();
33747             // NamedImports:
33748             //  { }
33749             //  { ImportsList }
33750             //  { ImportsList, }
33751             // ImportsList:
33752             //  ImportSpecifier
33753             //  ImportsList, ImportSpecifier
33754             var node = kind === 264 /* NamedImports */
33755                 ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */))
33756                 : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */));
33757             return finishNode(node, pos);
33758         }
33759         function parseExportSpecifier() {
33760             return parseImportOrExportSpecifier(270 /* ExportSpecifier */);
33761         }
33762         function parseImportSpecifier() {
33763             return parseImportOrExportSpecifier(265 /* ImportSpecifier */);
33764         }
33765         function parseImportOrExportSpecifier(kind) {
33766             var pos = getNodePos();
33767             // ImportSpecifier:
33768             //   BindingIdentifier
33769             //   IdentifierName as BindingIdentifier
33770             // ExportSpecifier:
33771             //   IdentifierName
33772             //   IdentifierName as IdentifierName
33773             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
33774             var checkIdentifierStart = scanner.getTokenPos();
33775             var checkIdentifierEnd = scanner.getTextPos();
33776             var identifierName = parseIdentifierName();
33777             var propertyName;
33778             var name;
33779             if (token() === 126 /* AsKeyword */) {
33780                 propertyName = identifierName;
33781                 parseExpected(126 /* AsKeyword */);
33782                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
33783                 checkIdentifierStart = scanner.getTokenPos();
33784                 checkIdentifierEnd = scanner.getTextPos();
33785                 name = parseIdentifierName();
33786             }
33787             else {
33788                 name = identifierName;
33789             }
33790             if (kind === 265 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
33791                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
33792             }
33793             var node = kind === 265 /* ImportSpecifier */
33794                 ? factory.createImportSpecifier(propertyName, name)
33795                 : factory.createExportSpecifier(propertyName, name);
33796             return finishNode(node, pos);
33797         }
33798         function parseNamespaceExport(pos) {
33799             return finishNode(factory.createNamespaceExport(parseIdentifierName()), pos);
33800         }
33801         function parseExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
33802             var savedAwaitContext = inAwaitContext();
33803             setAwaitContext(/*value*/ true);
33804             var exportClause;
33805             var moduleSpecifier;
33806             var isTypeOnly = parseOptional(149 /* TypeKeyword */);
33807             var namespaceExportPos = getNodePos();
33808             if (parseOptional(41 /* AsteriskToken */)) {
33809                 if (parseOptional(126 /* AsKeyword */)) {
33810                     exportClause = parseNamespaceExport(namespaceExportPos);
33811                 }
33812                 parseExpected(153 /* FromKeyword */);
33813                 moduleSpecifier = parseModuleSpecifier();
33814             }
33815             else {
33816                 exportClause = parseNamedImportsOrExports(268 /* NamedExports */);
33817                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
33818                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
33819                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
33820                 if (token() === 153 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
33821                     parseExpected(153 /* FromKeyword */);
33822                     moduleSpecifier = parseModuleSpecifier();
33823                 }
33824             }
33825             parseSemicolon();
33826             setAwaitContext(savedAwaitContext);
33827             var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier);
33828             return withJSDoc(finishNode(node, pos), hasJSDoc);
33829         }
33830         function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) {
33831             var savedAwaitContext = inAwaitContext();
33832             setAwaitContext(/*value*/ true);
33833             var isExportEquals;
33834             if (parseOptional(62 /* EqualsToken */)) {
33835                 isExportEquals = true;
33836             }
33837             else {
33838                 parseExpected(87 /* DefaultKeyword */);
33839             }
33840             var expression = parseAssignmentExpressionOrHigher();
33841             parseSemicolon();
33842             setAwaitContext(savedAwaitContext);
33843             var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression);
33844             return withJSDoc(finishNode(node, pos), hasJSDoc);
33845         }
33846         function setExternalModuleIndicator(sourceFile) {
33847             // Try to use the first top-level import/export when available, then
33848             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
33849             sourceFile.externalModuleIndicator =
33850                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
33851                     getImportMetaIfNecessary(sourceFile);
33852         }
33853         function isAnExternalModuleIndicatorNode(node) {
33854             return hasModifierOfKind(node, 92 /* ExportKeyword */)
33855                 || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)
33856                 || ts.isImportDeclaration(node)
33857                 || ts.isExportAssignment(node)
33858                 || ts.isExportDeclaration(node) ? node : undefined;
33859         }
33860         function getImportMetaIfNecessary(sourceFile) {
33861             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
33862                 walkTreeForExternalModuleIndicators(sourceFile) :
33863                 undefined;
33864         }
33865         function walkTreeForExternalModuleIndicators(node) {
33866             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
33867         }
33868         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
33869         function hasModifierOfKind(node, kind) {
33870             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
33871         }
33872         function isImportMeta(node) {
33873             return ts.isMetaProperty(node) && node.keywordToken === 99 /* ImportKeyword */ && node.name.escapedText === "meta";
33874         }
33875         var ParsingContext;
33876         (function (ParsingContext) {
33877             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
33878             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
33879             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
33880             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
33881             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
33882             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
33883             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
33884             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
33885             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
33886             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
33887             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
33888             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
33889             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
33890             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
33891             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
33892             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
33893             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
33894             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
33895             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
33896             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
33897             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
33898             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
33899             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
33900             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
33901             ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
33902         })(ParsingContext || (ParsingContext = {}));
33903         var Tristate;
33904         (function (Tristate) {
33905             Tristate[Tristate["False"] = 0] = "False";
33906             Tristate[Tristate["True"] = 1] = "True";
33907             Tristate[Tristate["Unknown"] = 2] = "Unknown";
33908         })(Tristate || (Tristate = {}));
33909         var JSDocParser;
33910         (function (JSDocParser) {
33911             function parseJSDocTypeExpressionForTests(content, start, length) {
33912                 initializeState("file.js", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
33913                 scanner.setText(content, start, length);
33914                 currentToken = scanner.scan();
33915                 var jsDocTypeExpression = parseJSDocTypeExpression();
33916                 var sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false, [], factory.createToken(1 /* EndOfFileToken */), 0 /* None */);
33917                 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
33918                 if (jsDocDiagnostics) {
33919                     sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
33920                 }
33921                 clearState();
33922                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
33923             }
33924             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
33925             // Parses out a JSDoc type expression.
33926             function parseJSDocTypeExpression(mayOmitBraces) {
33927                 var pos = getNodePos();
33928                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
33929                 var type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
33930                 if (!mayOmitBraces || hasBrace) {
33931                     parseExpectedJSDoc(19 /* CloseBraceToken */);
33932                 }
33933                 var result = factory.createJSDocTypeExpression(type);
33934                 fixupParentReferences(result);
33935                 return finishNode(result, pos);
33936             }
33937             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
33938             function parseJSDocNameReference() {
33939                 var pos = getNodePos();
33940                 var hasBrace = parseOptional(18 /* OpenBraceToken */);
33941                 var entityName = parseEntityName(/* allowReservedWords*/ false);
33942                 if (hasBrace) {
33943                     parseExpectedJSDoc(19 /* CloseBraceToken */);
33944                 }
33945                 var result = factory.createJSDocNameReference(entityName);
33946                 fixupParentReferences(result);
33947                 return finishNode(result, pos);
33948             }
33949             JSDocParser.parseJSDocNameReference = parseJSDocNameReference;
33950             function parseIsolatedJSDocComment(content, start, length) {
33951                 initializeState("", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
33952                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
33953                 var sourceFile = { languageVariant: 0 /* Standard */, text: content };
33954                 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
33955                 clearState();
33956                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
33957             }
33958             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
33959             function parseJSDocComment(parent, start, length) {
33960                 var saveToken = currentToken;
33961                 var saveParseDiagnosticsLength = parseDiagnostics.length;
33962                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
33963                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
33964                 ts.setParent(comment, parent);
33965                 if (contextFlags & 131072 /* JavaScriptFile */) {
33966                     if (!jsDocDiagnostics) {
33967                         jsDocDiagnostics = [];
33968                     }
33969                     jsDocDiagnostics.push.apply(jsDocDiagnostics, parseDiagnostics);
33970                 }
33971                 currentToken = saveToken;
33972                 parseDiagnostics.length = saveParseDiagnosticsLength;
33973                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
33974                 return comment;
33975             }
33976             JSDocParser.parseJSDocComment = parseJSDocComment;
33977             var JSDocState;
33978             (function (JSDocState) {
33979                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
33980                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
33981                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
33982                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
33983             })(JSDocState || (JSDocState = {}));
33984             var PropertyLikeParse;
33985             (function (PropertyLikeParse) {
33986                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
33987                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
33988                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
33989             })(PropertyLikeParse || (PropertyLikeParse = {}));
33990             function parseJSDocCommentWorker(start, length) {
33991                 if (start === void 0) { start = 0; }
33992                 var content = sourceText;
33993                 var end = length === undefined ? content.length : start + length;
33994                 length = end - start;
33995                 ts.Debug.assert(start >= 0);
33996                 ts.Debug.assert(start <= end);
33997                 ts.Debug.assert(end <= content.length);
33998                 // Check for /** (JSDoc opening part)
33999                 if (!isJSDocLikeText(content, start)) {
34000                     return undefined;
34001                 }
34002                 var tags;
34003                 var tagsPos;
34004                 var tagsEnd;
34005                 var comments = [];
34006                 // + 3 for leading /**, - 5 in total for /** */
34007                 return scanner.scanRange(start + 3, length - 5, function () {
34008                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
34009                     // This is so that /** * @type */ doesn't parse.
34010                     var state = 1 /* SawAsterisk */;
34011                     var margin;
34012                     // + 4 for leading '/** '
34013                     // + 1 because the last index of \n is always one index before the first character in the line and coincidentally, if there is no \n before start, it is -1, which is also one index before the first character
34014                     var indent = start - (content.lastIndexOf("\n", start) + 1) + 4;
34015                     function pushComment(text) {
34016                         if (!margin) {
34017                             margin = indent;
34018                         }
34019                         comments.push(text);
34020                         indent += text.length;
34021                     }
34022                     nextTokenJSDoc();
34023                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
34024                         ;
34025                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
34026                         state = 0 /* BeginningOfLine */;
34027                         indent = 0;
34028                     }
34029                     loop: while (true) {
34030                         switch (token()) {
34031                             case 59 /* AtToken */:
34032                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
34033                                     removeTrailingWhitespace(comments);
34034                                     addTag(parseTag(indent));
34035                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
34036                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
34037                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
34038                                     state = 0 /* BeginningOfLine */;
34039                                     margin = undefined;
34040                                 }
34041                                 else {
34042                                     pushComment(scanner.getTokenText());
34043                                 }
34044                                 break;
34045                             case 4 /* NewLineTrivia */:
34046                                 comments.push(scanner.getTokenText());
34047                                 state = 0 /* BeginningOfLine */;
34048                                 indent = 0;
34049                                 break;
34050                             case 41 /* AsteriskToken */:
34051                                 var asterisk = scanner.getTokenText();
34052                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
34053                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
34054                                     state = 2 /* SavingComments */;
34055                                     pushComment(asterisk);
34056                                 }
34057                                 else {
34058                                     // Ignore the first asterisk on a line
34059                                     state = 1 /* SawAsterisk */;
34060                                     indent += asterisk.length;
34061                                 }
34062                                 break;
34063                             case 5 /* WhitespaceTrivia */:
34064                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
34065                                 var whitespace = scanner.getTokenText();
34066                                 if (state === 2 /* SavingComments */) {
34067                                     comments.push(whitespace);
34068                                 }
34069                                 else if (margin !== undefined && indent + whitespace.length > margin) {
34070                                     comments.push(whitespace.slice(margin - indent));
34071                                 }
34072                                 indent += whitespace.length;
34073                                 break;
34074                             case 1 /* EndOfFileToken */:
34075                                 break loop;
34076                             default:
34077                                 // Anything else is doc comment text. We just save it. Because it
34078                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
34079                                 // line break.
34080                                 state = 2 /* SavingComments */;
34081                                 pushComment(scanner.getTokenText());
34082                                 break;
34083                         }
34084                         nextTokenJSDoc();
34085                     }
34086                     removeLeadingNewlines(comments);
34087                     removeTrailingWhitespace(comments);
34088                     return createJSDocComment();
34089                 });
34090                 function removeLeadingNewlines(comments) {
34091                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
34092                         comments.shift();
34093                     }
34094                 }
34095                 function removeTrailingWhitespace(comments) {
34096                     while (comments.length && comments[comments.length - 1].trim() === "") {
34097                         comments.pop();
34098                     }
34099                 }
34100                 function createJSDocComment() {
34101                     var comment = comments.length ? comments.join("") : undefined;
34102                     var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd);
34103                     return finishNode(factory.createJSDocComment(comment, tagsArray), start, end);
34104                 }
34105                 function isNextNonwhitespaceTokenEndOfFile() {
34106                     // We must use infinite lookahead, as there could be any number of newlines :(
34107                     while (true) {
34108                         nextTokenJSDoc();
34109                         if (token() === 1 /* EndOfFileToken */) {
34110                             return true;
34111                         }
34112                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
34113                             return false;
34114                         }
34115                     }
34116                 }
34117                 function skipWhitespace() {
34118                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34119                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
34120                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
34121                         }
34122                     }
34123                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34124                         nextTokenJSDoc();
34125                     }
34126                 }
34127                 function skipWhitespaceOrAsterisk() {
34128                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34129                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
34130                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
34131                         }
34132                     }
34133                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
34134                     var seenLineBreak = false;
34135                     var indentText = "";
34136                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34137                         indentText += scanner.getTokenText();
34138                         if (token() === 4 /* NewLineTrivia */) {
34139                             precedingLineBreak = true;
34140                             seenLineBreak = true;
34141                             indentText = "";
34142                         }
34143                         else if (token() === 41 /* AsteriskToken */) {
34144                             precedingLineBreak = false;
34145                         }
34146                         nextTokenJSDoc();
34147                     }
34148                     return seenLineBreak ? indentText : "";
34149                 }
34150                 function parseTag(margin) {
34151                     ts.Debug.assert(token() === 59 /* AtToken */);
34152                     var start = scanner.getTokenPos();
34153                     nextTokenJSDoc();
34154                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
34155                     var indentText = skipWhitespaceOrAsterisk();
34156                     var tag;
34157                     switch (tagName.escapedText) {
34158                         case "author":
34159                             tag = parseAuthorTag(start, tagName, margin, indentText);
34160                             break;
34161                         case "implements":
34162                             tag = parseImplementsTag(start, tagName, margin, indentText);
34163                             break;
34164                         case "augments":
34165                         case "extends":
34166                             tag = parseAugmentsTag(start, tagName, margin, indentText);
34167                             break;
34168                         case "class":
34169                         case "constructor":
34170                             tag = parseSimpleTag(start, factory.createJSDocClassTag, tagName, margin, indentText);
34171                             break;
34172                         case "public":
34173                             tag = parseSimpleTag(start, factory.createJSDocPublicTag, tagName, margin, indentText);
34174                             break;
34175                         case "private":
34176                             tag = parseSimpleTag(start, factory.createJSDocPrivateTag, tagName, margin, indentText);
34177                             break;
34178                         case "protected":
34179                             tag = parseSimpleTag(start, factory.createJSDocProtectedTag, tagName, margin, indentText);
34180                             break;
34181                         case "readonly":
34182                             tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText);
34183                             break;
34184                         case "deprecated":
34185                             hasDeprecatedTag = true;
34186                             tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText);
34187                             break;
34188                         case "this":
34189                             tag = parseThisTag(start, tagName, margin, indentText);
34190                             break;
34191                         case "enum":
34192                             tag = parseEnumTag(start, tagName, margin, indentText);
34193                             break;
34194                         case "arg":
34195                         case "argument":
34196                         case "param":
34197                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
34198                         case "return":
34199                         case "returns":
34200                             tag = parseReturnTag(start, tagName, margin, indentText);
34201                             break;
34202                         case "template":
34203                             tag = parseTemplateTag(start, tagName, margin, indentText);
34204                             break;
34205                         case "type":
34206                             tag = parseTypeTag(start, tagName, margin, indentText);
34207                             break;
34208                         case "typedef":
34209                             tag = parseTypedefTag(start, tagName, margin, indentText);
34210                             break;
34211                         case "callback":
34212                             tag = parseCallbackTag(start, tagName, margin, indentText);
34213                             break;
34214                         case "see":
34215                             tag = parseSeeTag(start, tagName, margin, indentText);
34216                             break;
34217                         default:
34218                             tag = parseUnknownTag(start, tagName, margin, indentText);
34219                             break;
34220                     }
34221                     return tag;
34222                 }
34223                 function parseTrailingTagComments(pos, end, margin, indentText) {
34224                     // some tags, like typedef and callback, have already parsed their comments earlier
34225                     if (!indentText) {
34226                         margin += end - pos;
34227                     }
34228                     return parseTagComments(margin, indentText.slice(margin));
34229                 }
34230                 function parseTagComments(indent, initialMargin) {
34231                     var comments = [];
34232                     var state = 0 /* BeginningOfLine */;
34233                     var margin;
34234                     function pushComment(text) {
34235                         if (!margin) {
34236                             margin = indent;
34237                         }
34238                         comments.push(text);
34239                         indent += text.length;
34240                     }
34241                     if (initialMargin !== undefined) {
34242                         // jump straight to saving comments if there is some initial indentation
34243                         if (initialMargin !== "") {
34244                             pushComment(initialMargin);
34245                         }
34246                         state = 1 /* SawAsterisk */;
34247                     }
34248                     var tok = token();
34249                     loop: while (true) {
34250                         switch (tok) {
34251                             case 4 /* NewLineTrivia */:
34252                                 state = 0 /* BeginningOfLine */;
34253                                 // don't use pushComment here because we want to keep the margin unchanged
34254                                 comments.push(scanner.getTokenText());
34255                                 indent = 0;
34256                                 break;
34257                             case 59 /* AtToken */:
34258                                 if (state === 3 /* SavingBackticks */) {
34259                                     comments.push(scanner.getTokenText());
34260                                     break;
34261                                 }
34262                                 scanner.setTextPos(scanner.getTextPos() - 1);
34263                             // falls through
34264                             case 1 /* EndOfFileToken */:
34265                                 // Done
34266                                 break loop;
34267                             case 5 /* WhitespaceTrivia */:
34268                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
34269                                     pushComment(scanner.getTokenText());
34270                                 }
34271                                 else {
34272                                     var whitespace = scanner.getTokenText();
34273                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
34274                                     if (margin !== undefined && indent + whitespace.length > margin) {
34275                                         comments.push(whitespace.slice(margin - indent));
34276                                     }
34277                                     indent += whitespace.length;
34278                                 }
34279                                 break;
34280                             case 18 /* OpenBraceToken */:
34281                                 state = 2 /* SavingComments */;
34282                                 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
34283                                     pushComment(scanner.getTokenText());
34284                                     nextTokenJSDoc();
34285                                     pushComment(scanner.getTokenText());
34286                                     nextTokenJSDoc();
34287                                 }
34288                                 pushComment(scanner.getTokenText());
34289                                 break;
34290                             case 61 /* BacktickToken */:
34291                                 if (state === 3 /* SavingBackticks */) {
34292                                     state = 2 /* SavingComments */;
34293                                 }
34294                                 else {
34295                                     state = 3 /* SavingBackticks */;
34296                                 }
34297                                 pushComment(scanner.getTokenText());
34298                                 break;
34299                             case 41 /* AsteriskToken */:
34300                                 if (state === 0 /* BeginningOfLine */) {
34301                                     // leading asterisks start recording on the *next* (non-whitespace) token
34302                                     state = 1 /* SawAsterisk */;
34303                                     indent += 1;
34304                                     break;
34305                                 }
34306                             // record the * as a comment
34307                             // falls through
34308                             default:
34309                                 if (state !== 3 /* SavingBackticks */) {
34310                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
34311                                 }
34312                                 pushComment(scanner.getTokenText());
34313                                 break;
34314                         }
34315                         tok = nextTokenJSDoc();
34316                     }
34317                     removeLeadingNewlines(comments);
34318                     removeTrailingWhitespace(comments);
34319                     return comments.length === 0 ? undefined : comments.join("");
34320                 }
34321                 function parseUnknownTag(start, tagName, indent, indentText) {
34322                     var end = getNodePos();
34323                     return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end);
34324                 }
34325                 function addTag(tag) {
34326                     if (!tag) {
34327                         return;
34328                     }
34329                     if (!tags) {
34330                         tags = [tag];
34331                         tagsPos = tag.pos;
34332                     }
34333                     else {
34334                         tags.push(tag);
34335                     }
34336                     tagsEnd = tag.end;
34337                 }
34338                 function tryParseTypeExpression() {
34339                     skipWhitespaceOrAsterisk();
34340                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
34341                 }
34342                 function parseBracketNameInPropertyAndParamTag() {
34343                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
34344                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
34345                     if (isBracketed) {
34346                         skipWhitespace();
34347                     }
34348                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
34349                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
34350                     var name = parseJSDocEntityName();
34351                     if (isBackquoted) {
34352                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
34353                     }
34354                     if (isBracketed) {
34355                         skipWhitespace();
34356                         // May have an optional default, e.g. '[foo = 42]'
34357                         if (parseOptionalToken(62 /* EqualsToken */)) {
34358                             parseExpression();
34359                         }
34360                         parseExpected(23 /* CloseBracketToken */);
34361                     }
34362                     return { name: name, isBracketed: isBracketed };
34363                 }
34364                 function isObjectOrObjectArrayTypeReference(node) {
34365                     switch (node.kind) {
34366                         case 145 /* ObjectKeyword */:
34367                             return true;
34368                         case 178 /* ArrayType */:
34369                             return isObjectOrObjectArrayTypeReference(node.elementType);
34370                         default:
34371                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
34372                     }
34373                 }
34374                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
34375                     var typeExpression = tryParseTypeExpression();
34376                     var isNameFirst = !typeExpression;
34377                     skipWhitespaceOrAsterisk();
34378                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
34379                     skipWhitespace();
34380                     if (isNameFirst) {
34381                         typeExpression = tryParseTypeExpression();
34382                     }
34383                     var comment = parseTagComments(indent + scanner.getStartPos() - start);
34384                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
34385                     if (nestedTypeLiteral) {
34386                         typeExpression = nestedTypeLiteral;
34387                         isNameFirst = true;
34388                     }
34389                     var result = target === 1 /* Property */
34390                         ? factory.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment)
34391                         : factory.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment);
34392                     return finishNode(result, start);
34393                 }
34394                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
34395                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
34396                         var pos = getNodePos();
34397                         var child = void 0;
34398                         var children = void 0;
34399                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
34400                             if (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) {
34401                                 children = ts.append(children, child);
34402                             }
34403                         }
34404                         if (children) {
34405                             var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 178 /* ArrayType */), pos);
34406                             return finishNode(factory.createJSDocTypeExpression(literal), pos);
34407                         }
34408                     }
34409                 }
34410                 function parseReturnTag(start, tagName, indent, indentText) {
34411                     if (ts.some(tags, ts.isJSDocReturnTag)) {
34412                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
34413                     }
34414                     var typeExpression = tryParseTypeExpression();
34415                     var end = getNodePos();
34416                     return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end);
34417                 }
34418                 function parseTypeTag(start, tagName, indent, indentText) {
34419                     if (ts.some(tags, ts.isJSDocTypeTag)) {
34420                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
34421                     }
34422                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
34423                     var end = getNodePos();
34424                     var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined;
34425                     return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end);
34426                 }
34427                 function parseSeeTag(start, tagName, indent, indentText) {
34428                     var nameExpression = parseJSDocNameReference();
34429                     var end = getNodePos();
34430                     var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined;
34431                     return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end);
34432                 }
34433                 function parseAuthorTag(start, tagName, indent, indentText) {
34434                     var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
34435                     if (!authorInfoWithEmail) {
34436                         var end_1 = getNodePos();
34437                         return finishNode(factory.createJSDocAuthorTag(tagName, parseTrailingTagComments(start, end_1, indent, indentText)), start, end_1);
34438                     }
34439                     var comments = authorInfoWithEmail;
34440                     if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
34441                         var comment = parseTagComments(indent);
34442                         if (comment) {
34443                             comments += comment;
34444                         }
34445                     }
34446                     return finishNode(factory.createJSDocAuthorTag(tagName, comments), start);
34447                 }
34448                 function tryParseAuthorNameAndEmail() {
34449                     var comments = [];
34450                     var seenLessThan = false;
34451                     var seenGreaterThan = false;
34452                     var token = scanner.getToken();
34453                     loop: while (true) {
34454                         switch (token) {
34455                             case 78 /* Identifier */:
34456                             case 5 /* WhitespaceTrivia */:
34457                             case 24 /* DotToken */:
34458                             case 59 /* AtToken */:
34459                                 comments.push(scanner.getTokenText());
34460                                 break;
34461                             case 29 /* LessThanToken */:
34462                                 if (seenLessThan || seenGreaterThan) {
34463                                     return;
34464                                 }
34465                                 seenLessThan = true;
34466                                 comments.push(scanner.getTokenText());
34467                                 break;
34468                             case 31 /* GreaterThanToken */:
34469                                 if (!seenLessThan || seenGreaterThan) {
34470                                     return;
34471                                 }
34472                                 seenGreaterThan = true;
34473                                 comments.push(scanner.getTokenText());
34474                                 scanner.setTextPos(scanner.getTokenPos() + 1);
34475                                 break loop;
34476                             case 4 /* NewLineTrivia */:
34477                             case 1 /* EndOfFileToken */:
34478                                 break loop;
34479                         }
34480                         token = nextTokenJSDoc();
34481                     }
34482                     if (seenLessThan && seenGreaterThan) {
34483                         return comments.length === 0 ? undefined : comments.join("");
34484                     }
34485                 }
34486                 function parseImplementsTag(start, tagName, margin, indentText) {
34487                     var className = parseExpressionWithTypeArgumentsForAugments();
34488                     var end = getNodePos();
34489                     return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34490                 }
34491                 function parseAugmentsTag(start, tagName, margin, indentText) {
34492                     var className = parseExpressionWithTypeArgumentsForAugments();
34493                     var end = getNodePos();
34494                     return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34495                 }
34496                 function parseExpressionWithTypeArgumentsForAugments() {
34497                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
34498                     var pos = getNodePos();
34499                     var expression = parsePropertyAccessEntityNameExpression();
34500                     var typeArguments = tryParseTypeArguments();
34501                     var node = factory.createExpressionWithTypeArguments(expression, typeArguments);
34502                     var res = finishNode(node, pos);
34503                     if (usedBrace) {
34504                         parseExpected(19 /* CloseBraceToken */);
34505                     }
34506                     return res;
34507                 }
34508                 function parsePropertyAccessEntityNameExpression() {
34509                     var pos = getNodePos();
34510                     var node = parseJSDocIdentifierName();
34511                     while (parseOptional(24 /* DotToken */)) {
34512                         var name = parseJSDocIdentifierName();
34513                         node = finishNode(factory.createPropertyAccessExpression(node, name), pos);
34514                     }
34515                     return node;
34516                 }
34517                 function parseSimpleTag(start, createTag, tagName, margin, indentText) {
34518                     var end = getNodePos();
34519                     return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34520                 }
34521                 function parseThisTag(start, tagName, margin, indentText) {
34522                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
34523                     skipWhitespace();
34524                     var end = getNodePos();
34525                     return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34526                 }
34527                 function parseEnumTag(start, tagName, margin, indentText) {
34528                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
34529                     skipWhitespace();
34530                     var end = getNodePos();
34531                     return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34532                 }
34533                 function parseTypedefTag(start, tagName, indent, indentText) {
34534                     var _a;
34535                     var typeExpression = tryParseTypeExpression();
34536                     skipWhitespaceOrAsterisk();
34537                     var fullName = parseJSDocTypeNameWithNamespace();
34538                     skipWhitespace();
34539                     var comment = parseTagComments(indent);
34540                     var end;
34541                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
34542                         var child = void 0;
34543                         var childTypeTag = void 0;
34544                         var jsDocPropertyTags = void 0;
34545                         var hasChildren = false;
34546                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
34547                             hasChildren = true;
34548                             if (child.kind === 329 /* JSDocTypeTag */) {
34549                                 if (childTypeTag) {
34550                                     parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags);
34551                                     var lastError = ts.lastOrUndefined(parseDiagnostics);
34552                                     if (lastError) {
34553                                         ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, 0, 0, ts.Diagnostics.The_tag_was_first_specified_here));
34554                                     }
34555                                     break;
34556                                 }
34557                                 else {
34558                                     childTypeTag = child;
34559                                 }
34560                             }
34561                             else {
34562                                 jsDocPropertyTags = ts.append(jsDocPropertyTags, child);
34563                             }
34564                         }
34565                         if (hasChildren) {
34566                             var isArrayType = typeExpression && typeExpression.type.kind === 178 /* ArrayType */;
34567                             var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType);
34568                             typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
34569                                 childTypeTag.typeExpression :
34570                                 finishNode(jsdocTypeLiteral, start);
34571                             end = typeExpression.end;
34572                         }
34573                     }
34574                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
34575                     end = end || comment !== undefined ?
34576                         getNodePos() :
34577                         ((_a = fullName !== null && fullName !== void 0 ? fullName : typeExpression) !== null && _a !== void 0 ? _a : tagName).end;
34578                     if (!comment) {
34579                         comment = parseTrailingTagComments(start, end, indent, indentText);
34580                     }
34581                     var typedefTag = factory.createJSDocTypedefTag(tagName, typeExpression, fullName, comment);
34582                     return finishNode(typedefTag, start, end);
34583                 }
34584                 function parseJSDocTypeNameWithNamespace(nested) {
34585                     var pos = scanner.getTokenPos();
34586                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
34587                         return undefined;
34588                     }
34589                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
34590                     if (parseOptional(24 /* DotToken */)) {
34591                         var body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
34592                         var jsDocNamespaceNode = factory.createModuleDeclaration(
34593                         /*decorators*/ undefined, 
34594                         /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NestedNamespace */ : undefined);
34595                         return finishNode(jsDocNamespaceNode, pos);
34596                     }
34597                     if (nested) {
34598                         typeNameOrNamespaceName.isInJSDocNamespace = true;
34599                     }
34600                     return typeNameOrNamespaceName;
34601                 }
34602                 function parseCallbackTagParameters(indent) {
34603                     var pos = getNodePos();
34604                     var child;
34605                     var parameters;
34606                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
34607                         parameters = ts.append(parameters, child);
34608                     }
34609                     return createNodeArray(parameters || [], pos);
34610                 }
34611                 function parseCallbackTag(start, tagName, indent, indentText) {
34612                     var fullName = parseJSDocTypeNameWithNamespace();
34613                     skipWhitespace();
34614                     var comment = parseTagComments(indent);
34615                     var parameters = parseCallbackTagParameters(indent);
34616                     var returnTag = tryParse(function () {
34617                         if (parseOptionalJsdoc(59 /* AtToken */)) {
34618                             var tag = parseTag(indent);
34619                             if (tag && tag.kind === 327 /* JSDocReturnTag */) {
34620                                 return tag;
34621                             }
34622                         }
34623                     });
34624                     var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start);
34625                     var end = getNodePos();
34626                     if (!comment) {
34627                         comment = parseTrailingTagComments(start, end, indent, indentText);
34628                     }
34629                     return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end);
34630                 }
34631                 function escapedTextsEqual(a, b) {
34632                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
34633                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
34634                             a = a.left;
34635                             b = b.left;
34636                         }
34637                         else {
34638                             return false;
34639                         }
34640                     }
34641                     return a.escapedText === b.escapedText;
34642                 }
34643                 function parseChildPropertyTag(indent) {
34644                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
34645                 }
34646                 function parseChildParameterOrPropertyTag(target, indent, name) {
34647                     var canParseTag = true;
34648                     var seenAsterisk = false;
34649                     while (true) {
34650                         switch (nextTokenJSDoc()) {
34651                             case 59 /* AtToken */:
34652                                 if (canParseTag) {
34653                                     var child = tryParseChildTag(target, indent);
34654                                     if (child && (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) &&
34655                                         target !== 4 /* CallbackParameter */ &&
34656                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
34657                                         return false;
34658                                     }
34659                                     return child;
34660                                 }
34661                                 seenAsterisk = false;
34662                                 break;
34663                             case 4 /* NewLineTrivia */:
34664                                 canParseTag = true;
34665                                 seenAsterisk = false;
34666                                 break;
34667                             case 41 /* AsteriskToken */:
34668                                 if (seenAsterisk) {
34669                                     canParseTag = false;
34670                                 }
34671                                 seenAsterisk = true;
34672                                 break;
34673                             case 78 /* Identifier */:
34674                                 canParseTag = false;
34675                                 break;
34676                             case 1 /* EndOfFileToken */:
34677                                 return false;
34678                         }
34679                     }
34680                 }
34681                 function tryParseChildTag(target, indent) {
34682                     ts.Debug.assert(token() === 59 /* AtToken */);
34683                     var start = scanner.getStartPos();
34684                     nextTokenJSDoc();
34685                     var tagName = parseJSDocIdentifierName();
34686                     skipWhitespace();
34687                     var t;
34688                     switch (tagName.escapedText) {
34689                         case "type":
34690                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
34691                         case "prop":
34692                         case "property":
34693                             t = 1 /* Property */;
34694                             break;
34695                         case "arg":
34696                         case "argument":
34697                         case "param":
34698                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
34699                             break;
34700                         default:
34701                             return false;
34702                     }
34703                     if (!(target & t)) {
34704                         return false;
34705                     }
34706                     return parseParameterOrPropertyTag(start, tagName, target, indent);
34707                 }
34708                 function parseTemplateTagTypeParameter() {
34709                     var typeParameterPos = getNodePos();
34710                     var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
34711                     return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos);
34712                 }
34713                 function parseTemplateTagTypeParameters() {
34714                     var pos = getNodePos();
34715                     var typeParameters = [];
34716                     do {
34717                         skipWhitespace();
34718                         typeParameters.push(parseTemplateTagTypeParameter());
34719                         skipWhitespaceOrAsterisk();
34720                     } while (parseOptionalJsdoc(27 /* CommaToken */));
34721                     return createNodeArray(typeParameters, pos);
34722                 }
34723                 function parseTemplateTag(start, tagName, indent, indentText) {
34724                     // The template tag looks like one of the following:
34725                     //   @template T,U,V
34726                     //   @template {Constraint} T
34727                     //
34728                     // According to the [closure docs](https://github.com/google/closure-compiler/wiki/Generic-Types#multiple-bounded-template-types):
34729                     //   > Multiple bounded generics cannot be declared on the same line. For the sake of clarity, if multiple templates share the same
34730                     //   > type bound they must be declared on separate lines.
34731                     //
34732                     // TODO: Determine whether we should enforce this in the checker.
34733                     // TODO: Consider moving the `constraint` to the first type parameter as we could then remove `getEffectiveConstraintOfTypeParameter`.
34734                     // TODO: Consider only parsing a single type parameter if there is a constraint.
34735                     var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
34736                     var typeParameters = parseTemplateTagTypeParameters();
34737                     var end = getNodePos();
34738                     return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end);
34739                 }
34740                 function parseOptionalJsdoc(t) {
34741                     if (token() === t) {
34742                         nextTokenJSDoc();
34743                         return true;
34744                     }
34745                     return false;
34746                 }
34747                 function parseJSDocEntityName() {
34748                     var entity = parseJSDocIdentifierName();
34749                     if (parseOptional(22 /* OpenBracketToken */)) {
34750                         parseExpected(23 /* CloseBracketToken */);
34751                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
34752                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
34753                         // but it's not worth it to enforce that restriction.
34754                     }
34755                     while (parseOptional(24 /* DotToken */)) {
34756                         var name = parseJSDocIdentifierName();
34757                         if (parseOptional(22 /* OpenBracketToken */)) {
34758                             parseExpected(23 /* CloseBracketToken */);
34759                         }
34760                         entity = createQualifiedName(entity, name);
34761                     }
34762                     return entity;
34763                 }
34764                 function parseJSDocIdentifierName(message) {
34765                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
34766                         return createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
34767                     }
34768                     identifierCount++;
34769                     var pos = scanner.getTokenPos();
34770                     var end = scanner.getTextPos();
34771                     var originalKeywordKind = token();
34772                     var text = internIdentifier(scanner.getTokenValue());
34773                     var result = finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos, end);
34774                     nextTokenJSDoc();
34775                     return result;
34776                 }
34777             }
34778         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
34779     })(Parser || (Parser = {}));
34780     var IncrementalParser;
34781     (function (IncrementalParser) {
34782         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
34783             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
34784             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
34785             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
34786                 // if the text didn't change, then we can just return our current source file as-is.
34787                 return sourceFile;
34788             }
34789             if (sourceFile.statements.length === 0) {
34790                 // If we don't have any statements in the current source file, then there's no real
34791                 // way to incrementally parse.  So just do a full parse instead.
34792                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
34793             }
34794             // Make sure we're not trying to incrementally update a source file more than once.  Once
34795             // we do an update the original source file is considered unusable from that point onwards.
34796             //
34797             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
34798             // tree and give them new positions and parents.  From that point on, trusting the old
34799             // tree at all is not possible as far too much of it may violate invariants.
34800             var incrementalSourceFile = sourceFile;
34801             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
34802             incrementalSourceFile.hasBeenIncrementallyParsed = true;
34803             Parser.fixupParentReferences(incrementalSourceFile);
34804             var oldText = sourceFile.text;
34805             var syntaxCursor = createSyntaxCursor(sourceFile);
34806             // Make the actual change larger so that we know to reparse anything whose lookahead
34807             // might have intersected the change.
34808             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
34809             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
34810             // Ensure that extending the affected range only moved the start of the change range
34811             // earlier in the file.
34812             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
34813             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
34814             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
34815             // The is the amount the nodes after the edit range need to be adjusted.  It can be
34816             // positive (if the edit added characters), negative (if the edit deleted characters)
34817             // or zero (if this was a pure overwrite with nothing added/removed).
34818             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
34819             // If we added or removed characters during the edit, then we need to go and adjust all
34820             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
34821             // may move backward (if we deleted chars).
34822             //
34823             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
34824             // to reuse are already at the appropriate position in the new text.  That way when we
34825             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
34826             // it very easy to determine if we can reuse a node.  If the node's position is at where
34827             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
34828             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
34829             // us, then we'll need to skip it or crumble it as appropriate
34830             //
34831             // We will also adjust the positions of nodes that intersect the change range as well.
34832             // By doing this, we ensure that all the positions in the old tree are consistent, not
34833             // just the positions of nodes entirely before/after the change range.  By being
34834             // consistent, we can then easily map from positions to nodes in the old tree easily.
34835             //
34836             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
34837             // that we cannot reuse these elements.
34838             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
34839             // Now that we've set up our internal incremental state just proceed and parse the
34840             // source file in the normal fashion.  When possible the parser will retrieve and
34841             // reuse nodes from the old tree.
34842             //
34843             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
34844             // parsing, we will be reusing nodes from the old tree, and placing it into new
34845             // parents.  If we don't set the parents now, we'll end up with an observably
34846             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
34847             // will immediately bail out of walking any subtrees when we can see that their parents
34848             // are already correct.
34849             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
34850             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
34851             return result;
34852         }
34853         IncrementalParser.updateSourceFile = updateSourceFile;
34854         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
34855             if (!oldDirectives)
34856                 return newDirectives;
34857             var commentDirectives;
34858             var addedNewlyScannedDirectives = false;
34859             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
34860                 var directive = oldDirectives_1[_i];
34861                 var range = directive.range, type = directive.type;
34862                 // Range before the change
34863                 if (range.end < changeStart) {
34864                     commentDirectives = ts.append(commentDirectives, directive);
34865                 }
34866                 else if (range.pos > changeRangeOldEnd) {
34867                     addNewlyScannedDirectives();
34868                     // Node is entirely past the change range.  We need to move both its pos and
34869                     // end, forward or backward appropriately.
34870                     var updatedDirective = {
34871                         range: { pos: range.pos + delta, end: range.end + delta },
34872                         type: type
34873                     };
34874                     commentDirectives = ts.append(commentDirectives, updatedDirective);
34875                     if (aggressiveChecks) {
34876                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
34877                     }
34878                 }
34879                 // Ignore ranges that fall in change range
34880             }
34881             addNewlyScannedDirectives();
34882             return commentDirectives;
34883             function addNewlyScannedDirectives() {
34884                 if (addedNewlyScannedDirectives)
34885                     return;
34886                 addedNewlyScannedDirectives = true;
34887                 if (!commentDirectives) {
34888                     commentDirectives = newDirectives;
34889                 }
34890                 else if (newDirectives) {
34891                     commentDirectives.push.apply(commentDirectives, newDirectives);
34892                 }
34893             }
34894         }
34895         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
34896             if (isArray) {
34897                 visitArray(element);
34898             }
34899             else {
34900                 visitNode(element);
34901             }
34902             return;
34903             function visitNode(node) {
34904                 var text = "";
34905                 if (aggressiveChecks && shouldCheckNode(node)) {
34906                     text = oldText.substring(node.pos, node.end);
34907                 }
34908                 // Ditch any existing LS children we may have created.  This way we can avoid
34909                 // moving them forward.
34910                 if (node._children) {
34911                     node._children = undefined;
34912                 }
34913                 ts.setTextRangePosEnd(node, node.pos + delta, node.end + delta);
34914                 if (aggressiveChecks && shouldCheckNode(node)) {
34915                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
34916                 }
34917                 forEachChild(node, visitNode, visitArray);
34918                 if (ts.hasJSDocNodes(node)) {
34919                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
34920                         var jsDocComment = _a[_i];
34921                         visitNode(jsDocComment);
34922                     }
34923                 }
34924                 checkNodePositions(node, aggressiveChecks);
34925             }
34926             function visitArray(array) {
34927                 array._children = undefined;
34928                 ts.setTextRangePosEnd(array, array.pos + delta, array.end + delta);
34929                 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
34930                     var node = array_8[_i];
34931                     visitNode(node);
34932                 }
34933             }
34934         }
34935         function shouldCheckNode(node) {
34936             switch (node.kind) {
34937                 case 10 /* StringLiteral */:
34938                 case 8 /* NumericLiteral */:
34939                 case 78 /* Identifier */:
34940                     return true;
34941             }
34942             return false;
34943         }
34944         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
34945             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
34946             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
34947             ts.Debug.assert(element.pos <= element.end);
34948             // We have an element that intersects the change range in some way.  It may have its
34949             // start, or its end (or both) in the changed range.  We want to adjust any part
34950             // that intersects such that the final tree is in a consistent state.  i.e. all
34951             // children have spans within the span of their parent, and all siblings are ordered
34952             // properly.
34953             // We may need to update both the 'pos' and the 'end' of the element.
34954             // If the 'pos' is before the start of the change, then we don't need to touch it.
34955             // If it isn't, then the 'pos' must be inside the change.  How we update it will
34956             // depend if delta is positive or negative. If delta is positive then we have
34957             // something like:
34958             //
34959             //  -------------------AAA-----------------
34960             //  -------------------BBBCCCCCCC-----------------
34961             //
34962             // In this case, we consider any node that started in the change range to still be
34963             // starting at the same position.
34964             //
34965             // however, if the delta is negative, then we instead have something like this:
34966             //
34967             //  -------------------XXXYYYYYYY-----------------
34968             //  -------------------ZZZ-----------------
34969             //
34970             // In this case, any element that started in the 'X' range will keep its position.
34971             // However any element that started after that will have their pos adjusted to be
34972             // at the end of the new range.  i.e. any node that started in the 'Y' range will
34973             // be adjusted to have their start at the end of the 'Z' range.
34974             //
34975             // The element will keep its position if possible.  Or Move backward to the new-end
34976             // if it's in the 'Y' range.
34977             var pos = Math.min(element.pos, changeRangeNewEnd);
34978             // If the 'end' is after the change range, then we always adjust it by the delta
34979             // amount.  However, if the end is in the change range, then how we adjust it
34980             // will depend on if delta is positive or negative.  If delta is positive then we
34981             // have something like:
34982             //
34983             //  -------------------AAA-----------------
34984             //  -------------------BBBCCCCCCC-----------------
34985             //
34986             // In this case, we consider any node that ended inside the change range to keep its
34987             // end position.
34988             //
34989             // however, if the delta is negative, then we instead have something like this:
34990             //
34991             //  -------------------XXXYYYYYYY-----------------
34992             //  -------------------ZZZ-----------------
34993             //
34994             // In this case, any element that ended in the 'X' range will keep its position.
34995             // However any element that ended after that will have their pos adjusted to be
34996             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
34997             // be adjusted to have their end at the end of the 'Z' range.
34998             var end = element.end >= changeRangeOldEnd ?
34999                 // Element ends after the change range.  Always adjust the end pos.
35000                 element.end + delta :
35001                 // Element ends in the change range.  The element will keep its position if
35002                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
35003                 Math.min(element.end, changeRangeNewEnd);
35004             ts.Debug.assert(pos <= end);
35005             if (element.parent) {
35006                 ts.Debug.assertGreaterThanOrEqual(pos, element.parent.pos);
35007                 ts.Debug.assertLessThanOrEqual(end, element.parent.end);
35008             }
35009             ts.setTextRangePosEnd(element, pos, end);
35010         }
35011         function checkNodePositions(node, aggressiveChecks) {
35012             if (aggressiveChecks) {
35013                 var pos_2 = node.pos;
35014                 var visitNode_1 = function (child) {
35015                     ts.Debug.assert(child.pos >= pos_2);
35016                     pos_2 = child.end;
35017                 };
35018                 if (ts.hasJSDocNodes(node)) {
35019                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
35020                         var jsDocComment = _a[_i];
35021                         visitNode_1(jsDocComment);
35022                     }
35023                 }
35024                 forEachChild(node, visitNode_1);
35025                 ts.Debug.assert(pos_2 <= node.end);
35026             }
35027         }
35028         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
35029             visitNode(sourceFile);
35030             return;
35031             function visitNode(child) {
35032                 ts.Debug.assert(child.pos <= child.end);
35033                 if (child.pos > changeRangeOldEnd) {
35034                     // Node is entirely past the change range.  We need to move both its pos and
35035                     // end, forward or backward appropriately.
35036                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
35037                     return;
35038                 }
35039                 // Check if the element intersects the change range.  If it does, then it is not
35040                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
35041                 // be able to use.
35042                 var fullEnd = child.end;
35043                 if (fullEnd >= changeStart) {
35044                     child.intersectsChange = true;
35045                     child._children = undefined;
35046                     // Adjust the pos or end (or both) of the intersecting element accordingly.
35047                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
35048                     forEachChild(child, visitNode, visitArray);
35049                     if (ts.hasJSDocNodes(child)) {
35050                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
35051                             var jsDocComment = _a[_i];
35052                             visitNode(jsDocComment);
35053                         }
35054                     }
35055                     checkNodePositions(child, aggressiveChecks);
35056                     return;
35057                 }
35058                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
35059                 ts.Debug.assert(fullEnd < changeStart);
35060             }
35061             function visitArray(array) {
35062                 ts.Debug.assert(array.pos <= array.end);
35063                 if (array.pos > changeRangeOldEnd) {
35064                     // Array is entirely after the change range.  We need to move it, and move any of
35065                     // its children.
35066                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
35067                     return;
35068                 }
35069                 // Check if the element intersects the change range.  If it does, then it is not
35070                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
35071                 // be able to use.
35072                 var fullEnd = array.end;
35073                 if (fullEnd >= changeStart) {
35074                     array.intersectsChange = true;
35075                     array._children = undefined;
35076                     // Adjust the pos or end (or both) of the intersecting array accordingly.
35077                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
35078                     for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
35079                         var node = array_9[_i];
35080                         visitNode(node);
35081                     }
35082                     return;
35083                 }
35084                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
35085                 ts.Debug.assert(fullEnd < changeStart);
35086             }
35087         }
35088         function extendToAffectedRange(sourceFile, changeRange) {
35089             // Consider the following code:
35090             //      void foo() { /; }
35091             //
35092             // If the text changes with an insertion of / just before the semicolon then we end up with:
35093             //      void foo() { //; }
35094             //
35095             // If we were to just use the changeRange a is, then we would not rescan the { token
35096             // (as it does not intersect the actual original change range).  Because an edit may
35097             // change the token touching it, we actually need to look back *at least* one token so
35098             // that the prior token sees that change.
35099             var maxLookahead = 1;
35100             var start = changeRange.span.start;
35101             // the first iteration aligns us with the change start. subsequent iteration move us to
35102             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
35103             // start of the tree.
35104             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
35105                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
35106                 ts.Debug.assert(nearestNode.pos <= start);
35107                 var position = nearestNode.pos;
35108                 start = Math.max(0, position - 1);
35109             }
35110             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
35111             var finalLength = changeRange.newLength + (changeRange.span.start - start);
35112             return ts.createTextChangeRange(finalSpan, finalLength);
35113         }
35114         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
35115             var bestResult = sourceFile;
35116             var lastNodeEntirelyBeforePosition;
35117             forEachChild(sourceFile, visit);
35118             if (lastNodeEntirelyBeforePosition) {
35119                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
35120                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
35121                     bestResult = lastChildOfLastEntireNodeBeforePosition;
35122                 }
35123             }
35124             return bestResult;
35125             function getLastDescendant(node) {
35126                 while (true) {
35127                     var lastChild = ts.getLastChild(node);
35128                     if (lastChild) {
35129                         node = lastChild;
35130                     }
35131                     else {
35132                         return node;
35133                     }
35134                 }
35135             }
35136             function visit(child) {
35137                 if (ts.nodeIsMissing(child)) {
35138                     // Missing nodes are effectively invisible to us.  We never even consider them
35139                     // When trying to find the nearest node before us.
35140                     return;
35141                 }
35142                 // If the child intersects this position, then this node is currently the nearest
35143                 // node that starts before the position.
35144                 if (child.pos <= position) {
35145                     if (child.pos >= bestResult.pos) {
35146                         // This node starts before the position, and is closer to the position than
35147                         // the previous best node we found.  It is now the new best node.
35148                         bestResult = child;
35149                     }
35150                     // Now, the node may overlap the position, or it may end entirely before the
35151                     // position.  If it overlaps with the position, then either it, or one of its
35152                     // children must be the nearest node before the position.  So we can just
35153                     // recurse into this child to see if we can find something better.
35154                     if (position < child.end) {
35155                         // The nearest node is either this child, or one of the children inside
35156                         // of it.  We've already marked this child as the best so far.  Recurse
35157                         // in case one of the children is better.
35158                         forEachChild(child, visit);
35159                         // Once we look at the children of this node, then there's no need to
35160                         // continue any further.
35161                         return true;
35162                     }
35163                     else {
35164                         ts.Debug.assert(child.end <= position);
35165                         // The child ends entirely before this position.  Say you have the following
35166                         // (where $ is the position)
35167                         //
35168                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
35169                         //
35170                         // We would want to find the nearest preceding node in "complex expr 2".
35171                         // To support that, we keep track of this node, and once we're done searching
35172                         // for a best node, we recurse down this node to see if we can find a good
35173                         // result in it.
35174                         //
35175                         // This approach allows us to quickly skip over nodes that are entirely
35176                         // before the position, while still allowing us to find any nodes in the
35177                         // last one that might be what we want.
35178                         lastNodeEntirelyBeforePosition = child;
35179                     }
35180                 }
35181                 else {
35182                     ts.Debug.assert(child.pos > position);
35183                     // We're now at a node that is entirely past the position we're searching for.
35184                     // This node (and all following nodes) could never contribute to the result,
35185                     // so just skip them by returning 'true' here.
35186                     return true;
35187                 }
35188             }
35189         }
35190         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
35191             var oldText = sourceFile.text;
35192             if (textChangeRange) {
35193                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
35194                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
35195                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
35196                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
35197                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
35198                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
35199                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
35200                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
35201                 }
35202             }
35203         }
35204         function createSyntaxCursor(sourceFile) {
35205             var currentArray = sourceFile.statements;
35206             var currentArrayIndex = 0;
35207             ts.Debug.assert(currentArrayIndex < currentArray.length);
35208             var current = currentArray[currentArrayIndex];
35209             var lastQueriedPosition = -1 /* Value */;
35210             return {
35211                 currentNode: function (position) {
35212                     // Only compute the current node if the position is different than the last time
35213                     // we were asked.  The parser commonly asks for the node at the same position
35214                     // twice.  Once to know if can read an appropriate list element at a certain point,
35215                     // and then to actually read and consume the node.
35216                     if (position !== lastQueriedPosition) {
35217                         // Much of the time the parser will need the very next node in the array that
35218                         // we just returned a node from.So just simply check for that case and move
35219                         // forward in the array instead of searching for the node again.
35220                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
35221                             currentArrayIndex++;
35222                             current = currentArray[currentArrayIndex];
35223                         }
35224                         // If we don't have a node, or the node we have isn't in the right position,
35225                         // then try to find a viable node at the position requested.
35226                         if (!current || current.pos !== position) {
35227                             findHighestListElementThatStartsAtPosition(position);
35228                         }
35229                     }
35230                     // Cache this query so that we don't do any extra work if the parser calls back
35231                     // into us.  Note: this is very common as the parser will make pairs of calls like
35232                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
35233                     // called with 'isListElement', we don't want to redo the work when parseListElement
35234                     // is called immediately after.
35235                     lastQueriedPosition = position;
35236                     // Either we don'd have a node, or we have a node at the position being asked for.
35237                     ts.Debug.assert(!current || current.pos === position);
35238                     return current;
35239                 }
35240             };
35241             // Finds the highest element in the tree we can find that starts at the provided position.
35242             // The element must be a direct child of some node list in the tree.  This way after we
35243             // return it, we can easily return its next sibling in the list.
35244             function findHighestListElementThatStartsAtPosition(position) {
35245                 // Clear out any cached state about the last node we found.
35246                 currentArray = undefined;
35247                 currentArrayIndex = -1 /* Value */;
35248                 current = undefined;
35249                 // Recurse into the source file to find the highest node at this position.
35250                 forEachChild(sourceFile, visitNode, visitArray);
35251                 return;
35252                 function visitNode(node) {
35253                     if (position >= node.pos && position < node.end) {
35254                         // Position was within this node.  Keep searching deeper to find the node.
35255                         forEachChild(node, visitNode, visitArray);
35256                         // don't proceed any further in the search.
35257                         return true;
35258                     }
35259                     // position wasn't in this node, have to keep searching.
35260                     return false;
35261                 }
35262                 function visitArray(array) {
35263                     if (position >= array.pos && position < array.end) {
35264                         // position was in this array.  Search through this array to see if we find a
35265                         // viable element.
35266                         for (var i = 0; i < array.length; i++) {
35267                             var child = array[i];
35268                             if (child) {
35269                                 if (child.pos === position) {
35270                                     // Found the right node.  We're done.
35271                                     currentArray = array;
35272                                     currentArrayIndex = i;
35273                                     current = child;
35274                                     return true;
35275                                 }
35276                                 else {
35277                                     if (child.pos < position && position < child.end) {
35278                                         // Position in somewhere within this child.  Search in it and
35279                                         // stop searching in this array.
35280                                         forEachChild(child, visitNode, visitArray);
35281                                         return true;
35282                                     }
35283                                 }
35284                             }
35285                         }
35286                     }
35287                     // position wasn't in this array, have to keep searching.
35288                     return false;
35289                 }
35290             }
35291         }
35292         IncrementalParser.createSyntaxCursor = createSyntaxCursor;
35293         var InvalidPosition;
35294         (function (InvalidPosition) {
35295             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
35296         })(InvalidPosition || (InvalidPosition = {}));
35297     })(IncrementalParser || (IncrementalParser = {}));
35298     /** @internal */
35299     function isDeclarationFileName(fileName) {
35300         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
35301     }
35302     ts.isDeclarationFileName = isDeclarationFileName;
35303     /*@internal*/
35304     function processCommentPragmas(context, sourceText) {
35305         var pragmas = [];
35306         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
35307             var range = _a[_i];
35308             var comment = sourceText.substring(range.pos, range.end);
35309             extractPragmas(pragmas, range, comment);
35310         }
35311         context.pragmas = new ts.Map();
35312         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
35313             var pragma = pragmas_1[_b];
35314             if (context.pragmas.has(pragma.name)) {
35315                 var currentValue = context.pragmas.get(pragma.name);
35316                 if (currentValue instanceof Array) {
35317                     currentValue.push(pragma.args);
35318                 }
35319                 else {
35320                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
35321                 }
35322                 continue;
35323             }
35324             context.pragmas.set(pragma.name, pragma.args);
35325         }
35326     }
35327     ts.processCommentPragmas = processCommentPragmas;
35328     /*@internal*/
35329     function processPragmasIntoFields(context, reportDiagnostic) {
35330         context.checkJsDirective = undefined;
35331         context.referencedFiles = [];
35332         context.typeReferenceDirectives = [];
35333         context.libReferenceDirectives = [];
35334         context.amdDependencies = [];
35335         context.hasNoDefaultLib = false;
35336         context.pragmas.forEach(function (entryOrList, key) {
35337             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
35338             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
35339             switch (key) {
35340                 case "reference": {
35341                     var referencedFiles_1 = context.referencedFiles;
35342                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
35343                     var libReferenceDirectives_1 = context.libReferenceDirectives;
35344                     ts.forEach(ts.toArray(entryOrList), function (arg) {
35345                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
35346                         if (arg.arguments["no-default-lib"]) {
35347                             context.hasNoDefaultLib = true;
35348                         }
35349                         else if (types) {
35350                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
35351                         }
35352                         else if (lib) {
35353                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
35354                         }
35355                         else if (path) {
35356                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
35357                         }
35358                         else {
35359                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
35360                         }
35361                     });
35362                     break;
35363                 }
35364                 case "amd-dependency": {
35365                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
35366                     break;
35367                 }
35368                 case "amd-module": {
35369                     if (entryOrList instanceof Array) {
35370                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
35371                             var entry = entryOrList_1[_i];
35372                             if (context.moduleName) {
35373                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
35374                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
35375                             }
35376                             context.moduleName = entry.arguments.name;
35377                         }
35378                     }
35379                     else {
35380                         context.moduleName = entryOrList.arguments.name;
35381                     }
35382                     break;
35383                 }
35384                 case "ts-nocheck":
35385                 case "ts-check": {
35386                     // _last_ of either nocheck or check in a file is the "winner"
35387                     ts.forEach(ts.toArray(entryOrList), function (entry) {
35388                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
35389                             context.checkJsDirective = {
35390                                 enabled: key === "ts-check",
35391                                 end: entry.range.end,
35392                                 pos: entry.range.pos
35393                             };
35394                         }
35395                     });
35396                     break;
35397                 }
35398                 case "jsx":
35399                 case "jsxfrag":
35400                 case "jsximportsource":
35401                 case "jsxruntime":
35402                     return; // Accessed directly
35403                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
35404             }
35405         });
35406     }
35407     ts.processPragmasIntoFields = processPragmasIntoFields;
35408     var namedArgRegExCache = new ts.Map();
35409     function getNamedArgRegEx(name) {
35410         if (namedArgRegExCache.has(name)) {
35411             return namedArgRegExCache.get(name);
35412         }
35413         var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
35414         namedArgRegExCache.set(name, result);
35415         return result;
35416     }
35417     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
35418     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
35419     function extractPragmas(pragmas, range, text) {
35420         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
35421         if (tripleSlash) {
35422             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
35423             var pragma = ts.commentPragmas[name];
35424             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
35425                 return;
35426             }
35427             if (pragma.args) {
35428                 var argument = {};
35429                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
35430                     var arg = _a[_i];
35431                     var matcher = getNamedArgRegEx(arg.name);
35432                     var matchResult = matcher.exec(text);
35433                     if (!matchResult && !arg.optional) {
35434                         return; // Missing required argument, don't parse
35435                     }
35436                     else if (matchResult) {
35437                         if (arg.captureSpan) {
35438                             var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
35439                             argument[arg.name] = {
35440                                 value: matchResult[3],
35441                                 pos: startPos,
35442                                 end: startPos + matchResult[3].length
35443                             };
35444                         }
35445                         else {
35446                             argument[arg.name] = matchResult[3];
35447                         }
35448                     }
35449                 }
35450                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
35451             }
35452             else {
35453                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
35454             }
35455             return;
35456         }
35457         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
35458         if (singleLine) {
35459             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
35460         }
35461         if (range.kind === 3 /* MultiLineCommentTrivia */) {
35462             var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
35463             var multiLineMatch = void 0;
35464             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
35465                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
35466             }
35467         }
35468     }
35469     function addPragmaForMatch(pragmas, range, kind, match) {
35470         if (!match)
35471             return;
35472         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
35473         var pragma = ts.commentPragmas[name];
35474         if (!pragma || !(pragma.kind & kind)) {
35475             return;
35476         }
35477         var args = match[2]; // Split on spaces and match up positionally with definition
35478         var argument = getNamedPragmaArguments(pragma, args);
35479         if (argument === "fail")
35480             return; // Missing required argument, fail to parse it
35481         pragmas.push({ name: name, args: { arguments: argument, range: range } });
35482         return;
35483     }
35484     function getNamedPragmaArguments(pragma, text) {
35485         if (!text)
35486             return {};
35487         if (!pragma.args)
35488             return {};
35489         var args = text.split(/\s+/);
35490         var argMap = {};
35491         for (var i = 0; i < pragma.args.length; i++) {
35492             var argument = pragma.args[i];
35493             if (!args[i] && !argument.optional) {
35494                 return "fail";
35495             }
35496             if (argument.captureSpan) {
35497                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
35498             }
35499             argMap[argument.name] = args[i];
35500         }
35501         return argMap;
35502     }
35503     /** @internal */
35504     function tagNamesAreEquivalent(lhs, rhs) {
35505         if (lhs.kind !== rhs.kind) {
35506             return false;
35507         }
35508         if (lhs.kind === 78 /* Identifier */) {
35509             return lhs.escapedText === rhs.escapedText;
35510         }
35511         if (lhs.kind === 107 /* ThisKeyword */) {
35512             return true;
35513         }
35514         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
35515         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
35516         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
35517         return lhs.name.escapedText === rhs.name.escapedText &&
35518             tagNamesAreEquivalent(lhs.expression, rhs.expression);
35519     }
35520     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
35521 })(ts || (ts = {}));
35522 var ts;
35523 (function (ts) {
35524     /* @internal */
35525     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
35526     var jsxOptionMap = new ts.Map(ts.getEntries({
35527         "preserve": 1 /* Preserve */,
35528         "react-native": 3 /* ReactNative */,
35529         "react": 2 /* React */,
35530         "react-jsx": 4 /* ReactJSX */,
35531         "react-jsxdev": 5 /* ReactJSXDev */,
35532     }));
35533     /* @internal */
35534     ts.inverseJsxOptionMap = new ts.Map(ts.arrayFrom(ts.mapIterator(jsxOptionMap.entries(), function (_a) {
35535         var key = _a[0], value = _a[1];
35536         return ["" + value, key];
35537     })));
35538     // NOTE: The order here is important to default lib ordering as entries will have the same
35539     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
35540     //       order also affects overload resolution when a type declared in one lib is
35541     //       augmented in another lib.
35542     var libEntries = [
35543         // JavaScript only
35544         ["es5", "lib.es5.d.ts"],
35545         ["es6", "lib.es2015.d.ts"],
35546         ["es2015", "lib.es2015.d.ts"],
35547         ["es7", "lib.es2016.d.ts"],
35548         ["es2016", "lib.es2016.d.ts"],
35549         ["es2017", "lib.es2017.d.ts"],
35550         ["es2018", "lib.es2018.d.ts"],
35551         ["es2019", "lib.es2019.d.ts"],
35552         ["es2020", "lib.es2020.d.ts"],
35553         ["esnext", "lib.esnext.d.ts"],
35554         // Host only
35555         ["dom", "lib.dom.d.ts"],
35556         ["dom.iterable", "lib.dom.iterable.d.ts"],
35557         ["webworker", "lib.webworker.d.ts"],
35558         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
35559         ["webworker.iterable", "lib.webworker.iterable.d.ts"],
35560         ["scripthost", "lib.scripthost.d.ts"],
35561         // ES2015 Or ESNext By-feature options
35562         ["es2015.core", "lib.es2015.core.d.ts"],
35563         ["es2015.collection", "lib.es2015.collection.d.ts"],
35564         ["es2015.generator", "lib.es2015.generator.d.ts"],
35565         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
35566         ["es2015.promise", "lib.es2015.promise.d.ts"],
35567         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
35568         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
35569         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
35570         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
35571         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
35572         ["es2017.object", "lib.es2017.object.d.ts"],
35573         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
35574         ["es2017.string", "lib.es2017.string.d.ts"],
35575         ["es2017.intl", "lib.es2017.intl.d.ts"],
35576         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
35577         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
35578         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
35579         ["es2018.intl", "lib.es2018.intl.d.ts"],
35580         ["es2018.promise", "lib.es2018.promise.d.ts"],
35581         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
35582         ["es2019.array", "lib.es2019.array.d.ts"],
35583         ["es2019.object", "lib.es2019.object.d.ts"],
35584         ["es2019.string", "lib.es2019.string.d.ts"],
35585         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
35586         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
35587         ["es2020.promise", "lib.es2020.promise.d.ts"],
35588         ["es2020.sharedmemory", "lib.es2020.sharedmemory.d.ts"],
35589         ["es2020.string", "lib.es2020.string.d.ts"],
35590         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
35591         ["es2020.intl", "lib.es2020.intl.d.ts"],
35592         ["esnext.array", "lib.es2019.array.d.ts"],
35593         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
35594         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
35595         ["esnext.intl", "lib.esnext.intl.d.ts"],
35596         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
35597         ["esnext.string", "lib.esnext.string.d.ts"],
35598         ["esnext.promise", "lib.esnext.promise.d.ts"],
35599         ["esnext.weakref", "lib.esnext.weakref.d.ts"]
35600     ];
35601     /**
35602      * An array of supported "lib" reference file names used to determine the order for inclusion
35603      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
35604      * overload resolution when a type declared in one lib is extended by another.
35605      */
35606     /* @internal */
35607     ts.libs = libEntries.map(function (entry) { return entry[0]; });
35608     /**
35609      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
35610      * option as well as for resolving lib reference directives.
35611      */
35612     /* @internal */
35613     ts.libMap = new ts.Map(libEntries);
35614     // Watch related options
35615     /* @internal */
35616     ts.optionsForWatch = [
35617         {
35618             name: "watchFile",
35619             type: new ts.Map(ts.getEntries({
35620                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
35621                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
35622                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
35623                 usefsevents: ts.WatchFileKind.UseFsEvents,
35624                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
35625             })),
35626             category: ts.Diagnostics.Advanced_Options,
35627             description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
35628         },
35629         {
35630             name: "watchDirectory",
35631             type: new ts.Map(ts.getEntries({
35632                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
35633                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
35634                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
35635             })),
35636             category: ts.Diagnostics.Advanced_Options,
35637             description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
35638         },
35639         {
35640             name: "fallbackPolling",
35641             type: new ts.Map(ts.getEntries({
35642                 fixedinterval: ts.PollingWatchKind.FixedInterval,
35643                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
35644                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
35645             })),
35646             category: ts.Diagnostics.Advanced_Options,
35647             description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
35648         },
35649         {
35650             name: "synchronousWatchDirectory",
35651             type: "boolean",
35652             category: ts.Diagnostics.Advanced_Options,
35653             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
35654         },
35655     ];
35656     /* @internal */
35657     ts.commonOptionsWithBuild = [
35658         {
35659             name: "help",
35660             shortName: "h",
35661             type: "boolean",
35662             showInSimplifiedHelpView: true,
35663             category: ts.Diagnostics.Command_line_Options,
35664             description: ts.Diagnostics.Print_this_message,
35665         },
35666         {
35667             name: "help",
35668             shortName: "?",
35669             type: "boolean"
35670         },
35671         {
35672             name: "watch",
35673             shortName: "w",
35674             type: "boolean",
35675             showInSimplifiedHelpView: true,
35676             category: ts.Diagnostics.Command_line_Options,
35677             description: ts.Diagnostics.Watch_input_files,
35678         },
35679         {
35680             name: "preserveWatchOutput",
35681             type: "boolean",
35682             showInSimplifiedHelpView: false,
35683             category: ts.Diagnostics.Command_line_Options,
35684             description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
35685         },
35686         {
35687             name: "listFiles",
35688             type: "boolean",
35689             category: ts.Diagnostics.Advanced_Options,
35690             description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
35691         },
35692         {
35693             name: "listEmittedFiles",
35694             type: "boolean",
35695             category: ts.Diagnostics.Advanced_Options,
35696             description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
35697         },
35698         {
35699             name: "pretty",
35700             type: "boolean",
35701             showInSimplifiedHelpView: true,
35702             category: ts.Diagnostics.Command_line_Options,
35703             description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
35704         },
35705         {
35706             name: "traceResolution",
35707             type: "boolean",
35708             category: ts.Diagnostics.Advanced_Options,
35709             description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
35710         },
35711         {
35712             name: "diagnostics",
35713             type: "boolean",
35714             category: ts.Diagnostics.Advanced_Options,
35715             description: ts.Diagnostics.Show_diagnostic_information
35716         },
35717         {
35718             name: "extendedDiagnostics",
35719             type: "boolean",
35720             category: ts.Diagnostics.Advanced_Options,
35721             description: ts.Diagnostics.Show_verbose_diagnostic_information
35722         },
35723         {
35724             name: "generateCpuProfile",
35725             type: "string",
35726             isFilePath: true,
35727             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
35728             category: ts.Diagnostics.Advanced_Options,
35729             description: ts.Diagnostics.Generates_a_CPU_profile
35730         },
35731         {
35732             name: "generateTrace",
35733             type: "string",
35734             isFilePath: true,
35735             isCommandLineOnly: true,
35736             paramType: ts.Diagnostics.DIRECTORY,
35737             category: ts.Diagnostics.Advanced_Options,
35738             description: ts.Diagnostics.Generates_an_event_trace_and_a_list_of_types
35739         },
35740         {
35741             name: "incremental",
35742             shortName: "i",
35743             type: "boolean",
35744             category: ts.Diagnostics.Basic_Options,
35745             description: ts.Diagnostics.Enable_incremental_compilation,
35746             transpileOptionValue: undefined
35747         },
35748         {
35749             name: "assumeChangesOnlyAffectDirectDependencies",
35750             type: "boolean",
35751             affectsSemanticDiagnostics: true,
35752             affectsEmit: true,
35753             category: ts.Diagnostics.Advanced_Options,
35754             description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
35755         },
35756         {
35757             name: "locale",
35758             type: "string",
35759             category: ts.Diagnostics.Advanced_Options,
35760             description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
35761         },
35762     ];
35763     /* @internal */
35764     ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
35765         {
35766             name: "all",
35767             type: "boolean",
35768             showInSimplifiedHelpView: true,
35769             category: ts.Diagnostics.Command_line_Options,
35770             description: ts.Diagnostics.Show_all_compiler_options,
35771         },
35772         {
35773             name: "version",
35774             shortName: "v",
35775             type: "boolean",
35776             showInSimplifiedHelpView: true,
35777             category: ts.Diagnostics.Command_line_Options,
35778             description: ts.Diagnostics.Print_the_compiler_s_version,
35779         },
35780         {
35781             name: "init",
35782             type: "boolean",
35783             showInSimplifiedHelpView: true,
35784             category: ts.Diagnostics.Command_line_Options,
35785             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
35786         },
35787         {
35788             name: "project",
35789             shortName: "p",
35790             type: "string",
35791             isFilePath: true,
35792             showInSimplifiedHelpView: true,
35793             category: ts.Diagnostics.Command_line_Options,
35794             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
35795             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
35796         },
35797         {
35798             name: "build",
35799             type: "boolean",
35800             shortName: "b",
35801             showInSimplifiedHelpView: true,
35802             category: ts.Diagnostics.Command_line_Options,
35803             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
35804         },
35805         {
35806             name: "showConfig",
35807             type: "boolean",
35808             category: ts.Diagnostics.Command_line_Options,
35809             isCommandLineOnly: true,
35810             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
35811         },
35812         {
35813             name: "listFilesOnly",
35814             type: "boolean",
35815             category: ts.Diagnostics.Command_line_Options,
35816             affectsSemanticDiagnostics: true,
35817             affectsEmit: true,
35818             isCommandLineOnly: true,
35819             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
35820         },
35821         // Basic
35822         {
35823             name: "target",
35824             shortName: "t",
35825             type: new ts.Map(ts.getEntries({
35826                 es3: 0 /* ES3 */,
35827                 es5: 1 /* ES5 */,
35828                 es6: 2 /* ES2015 */,
35829                 es2015: 2 /* ES2015 */,
35830                 es2016: 3 /* ES2016 */,
35831                 es2017: 4 /* ES2017 */,
35832                 es2018: 5 /* ES2018 */,
35833                 es2019: 6 /* ES2019 */,
35834                 es2020: 7 /* ES2020 */,
35835                 esnext: 99 /* ESNext */,
35836             })),
35837             affectsSourceFile: true,
35838             affectsModuleResolution: true,
35839             affectsEmit: true,
35840             paramType: ts.Diagnostics.VERSION,
35841             showInSimplifiedHelpView: true,
35842             category: ts.Diagnostics.Basic_Options,
35843             description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
35844         },
35845         {
35846             name: "module",
35847             shortName: "m",
35848             type: new ts.Map(ts.getEntries({
35849                 none: ts.ModuleKind.None,
35850                 commonjs: ts.ModuleKind.CommonJS,
35851                 amd: ts.ModuleKind.AMD,
35852                 system: ts.ModuleKind.System,
35853                 umd: ts.ModuleKind.UMD,
35854                 es6: ts.ModuleKind.ES2015,
35855                 es2015: ts.ModuleKind.ES2015,
35856                 es2020: ts.ModuleKind.ES2020,
35857                 esnext: ts.ModuleKind.ESNext
35858             })),
35859             affectsModuleResolution: true,
35860             affectsEmit: true,
35861             paramType: ts.Diagnostics.KIND,
35862             showInSimplifiedHelpView: true,
35863             category: ts.Diagnostics.Basic_Options,
35864             description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
35865         },
35866         {
35867             name: "lib",
35868             type: "list",
35869             element: {
35870                 name: "lib",
35871                 type: ts.libMap
35872             },
35873             affectsModuleResolution: true,
35874             showInSimplifiedHelpView: true,
35875             category: ts.Diagnostics.Basic_Options,
35876             description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
35877             transpileOptionValue: undefined
35878         },
35879         {
35880             name: "allowJs",
35881             type: "boolean",
35882             affectsModuleResolution: true,
35883             showInSimplifiedHelpView: true,
35884             category: ts.Diagnostics.Basic_Options,
35885             description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
35886         },
35887         {
35888             name: "checkJs",
35889             type: "boolean",
35890             category: ts.Diagnostics.Basic_Options,
35891             description: ts.Diagnostics.Report_errors_in_js_files
35892         },
35893         {
35894             name: "jsx",
35895             type: jsxOptionMap,
35896             affectsSourceFile: true,
35897             affectsEmit: true,
35898             affectsModuleResolution: true,
35899             paramType: ts.Diagnostics.KIND,
35900             showInSimplifiedHelpView: true,
35901             category: ts.Diagnostics.Basic_Options,
35902             description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
35903         },
35904         {
35905             name: "declaration",
35906             shortName: "d",
35907             type: "boolean",
35908             affectsEmit: true,
35909             showInSimplifiedHelpView: true,
35910             category: ts.Diagnostics.Basic_Options,
35911             description: ts.Diagnostics.Generates_corresponding_d_ts_file,
35912             transpileOptionValue: undefined
35913         },
35914         {
35915             name: "declarationMap",
35916             type: "boolean",
35917             affectsEmit: true,
35918             showInSimplifiedHelpView: true,
35919             category: ts.Diagnostics.Basic_Options,
35920             description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
35921             transpileOptionValue: undefined
35922         },
35923         {
35924             name: "emitDeclarationOnly",
35925             type: "boolean",
35926             affectsEmit: true,
35927             category: ts.Diagnostics.Advanced_Options,
35928             description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
35929             transpileOptionValue: undefined
35930         },
35931         {
35932             name: "sourceMap",
35933             type: "boolean",
35934             affectsEmit: true,
35935             showInSimplifiedHelpView: true,
35936             category: ts.Diagnostics.Basic_Options,
35937             description: ts.Diagnostics.Generates_corresponding_map_file,
35938         },
35939         {
35940             name: "outFile",
35941             type: "string",
35942             affectsEmit: true,
35943             isFilePath: true,
35944             paramType: ts.Diagnostics.FILE,
35945             showInSimplifiedHelpView: true,
35946             category: ts.Diagnostics.Basic_Options,
35947             description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
35948             transpileOptionValue: undefined
35949         },
35950         {
35951             name: "outDir",
35952             type: "string",
35953             affectsEmit: true,
35954             isFilePath: true,
35955             paramType: ts.Diagnostics.DIRECTORY,
35956             showInSimplifiedHelpView: true,
35957             category: ts.Diagnostics.Basic_Options,
35958             description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
35959         },
35960         {
35961             name: "rootDir",
35962             type: "string",
35963             affectsEmit: true,
35964             isFilePath: true,
35965             paramType: ts.Diagnostics.LOCATION,
35966             category: ts.Diagnostics.Basic_Options,
35967             description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
35968         },
35969         {
35970             name: "composite",
35971             type: "boolean",
35972             affectsEmit: true,
35973             isTSConfigOnly: true,
35974             category: ts.Diagnostics.Basic_Options,
35975             description: ts.Diagnostics.Enable_project_compilation,
35976             transpileOptionValue: undefined
35977         },
35978         {
35979             name: "tsBuildInfoFile",
35980             type: "string",
35981             affectsEmit: true,
35982             isFilePath: true,
35983             paramType: ts.Diagnostics.FILE,
35984             category: ts.Diagnostics.Basic_Options,
35985             description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
35986             transpileOptionValue: undefined
35987         },
35988         {
35989             name: "removeComments",
35990             type: "boolean",
35991             affectsEmit: true,
35992             showInSimplifiedHelpView: true,
35993             category: ts.Diagnostics.Basic_Options,
35994             description: ts.Diagnostics.Do_not_emit_comments_to_output,
35995         },
35996         {
35997             name: "noEmit",
35998             type: "boolean",
35999             showInSimplifiedHelpView: true,
36000             category: ts.Diagnostics.Basic_Options,
36001             description: ts.Diagnostics.Do_not_emit_outputs,
36002             transpileOptionValue: undefined
36003         },
36004         {
36005             name: "importHelpers",
36006             type: "boolean",
36007             affectsEmit: true,
36008             category: ts.Diagnostics.Basic_Options,
36009             description: ts.Diagnostics.Import_emit_helpers_from_tslib
36010         },
36011         {
36012             name: "importsNotUsedAsValues",
36013             type: new ts.Map(ts.getEntries({
36014                 remove: 0 /* Remove */,
36015                 preserve: 1 /* Preserve */,
36016                 error: 2 /* Error */
36017             })),
36018             affectsEmit: true,
36019             affectsSemanticDiagnostics: true,
36020             category: ts.Diagnostics.Advanced_Options,
36021             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
36022         },
36023         {
36024             name: "downlevelIteration",
36025             type: "boolean",
36026             affectsEmit: true,
36027             category: ts.Diagnostics.Basic_Options,
36028             description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
36029         },
36030         {
36031             name: "isolatedModules",
36032             type: "boolean",
36033             category: ts.Diagnostics.Basic_Options,
36034             description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
36035             transpileOptionValue: true
36036         },
36037         // Strict Type Checks
36038         {
36039             name: "strict",
36040             type: "boolean",
36041             showInSimplifiedHelpView: true,
36042             category: ts.Diagnostics.Strict_Type_Checking_Options,
36043             description: ts.Diagnostics.Enable_all_strict_type_checking_options
36044         },
36045         {
36046             name: "noImplicitAny",
36047             type: "boolean",
36048             affectsSemanticDiagnostics: true,
36049             strictFlag: true,
36050             showInSimplifiedHelpView: true,
36051             category: ts.Diagnostics.Strict_Type_Checking_Options,
36052             description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
36053         },
36054         {
36055             name: "strictNullChecks",
36056             type: "boolean",
36057             affectsSemanticDiagnostics: true,
36058             strictFlag: true,
36059             showInSimplifiedHelpView: true,
36060             category: ts.Diagnostics.Strict_Type_Checking_Options,
36061             description: ts.Diagnostics.Enable_strict_null_checks
36062         },
36063         {
36064             name: "strictFunctionTypes",
36065             type: "boolean",
36066             affectsSemanticDiagnostics: true,
36067             strictFlag: true,
36068             showInSimplifiedHelpView: true,
36069             category: ts.Diagnostics.Strict_Type_Checking_Options,
36070             description: ts.Diagnostics.Enable_strict_checking_of_function_types
36071         },
36072         {
36073             name: "strictBindCallApply",
36074             type: "boolean",
36075             strictFlag: true,
36076             showInSimplifiedHelpView: true,
36077             category: ts.Diagnostics.Strict_Type_Checking_Options,
36078             description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
36079         },
36080         {
36081             name: "strictPropertyInitialization",
36082             type: "boolean",
36083             affectsSemanticDiagnostics: true,
36084             strictFlag: true,
36085             showInSimplifiedHelpView: true,
36086             category: ts.Diagnostics.Strict_Type_Checking_Options,
36087             description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
36088         },
36089         {
36090             name: "noImplicitThis",
36091             type: "boolean",
36092             affectsSemanticDiagnostics: true,
36093             strictFlag: true,
36094             showInSimplifiedHelpView: true,
36095             category: ts.Diagnostics.Strict_Type_Checking_Options,
36096             description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
36097         },
36098         {
36099             name: "alwaysStrict",
36100             type: "boolean",
36101             affectsSourceFile: true,
36102             strictFlag: true,
36103             showInSimplifiedHelpView: true,
36104             category: ts.Diagnostics.Strict_Type_Checking_Options,
36105             description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
36106         },
36107         // Additional Checks
36108         {
36109             name: "noUnusedLocals",
36110             type: "boolean",
36111             affectsSemanticDiagnostics: true,
36112             showInSimplifiedHelpView: true,
36113             category: ts.Diagnostics.Additional_Checks,
36114             description: ts.Diagnostics.Report_errors_on_unused_locals,
36115         },
36116         {
36117             name: "noUnusedParameters",
36118             type: "boolean",
36119             affectsSemanticDiagnostics: true,
36120             showInSimplifiedHelpView: true,
36121             category: ts.Diagnostics.Additional_Checks,
36122             description: ts.Diagnostics.Report_errors_on_unused_parameters,
36123         },
36124         {
36125             name: "noImplicitReturns",
36126             type: "boolean",
36127             affectsSemanticDiagnostics: true,
36128             showInSimplifiedHelpView: true,
36129             category: ts.Diagnostics.Additional_Checks,
36130             description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
36131         },
36132         {
36133             name: "noFallthroughCasesInSwitch",
36134             type: "boolean",
36135             affectsBindDiagnostics: true,
36136             affectsSemanticDiagnostics: true,
36137             showInSimplifiedHelpView: true,
36138             category: ts.Diagnostics.Additional_Checks,
36139             description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
36140         },
36141         {
36142             name: "noUncheckedIndexedAccess",
36143             type: "boolean",
36144             affectsSemanticDiagnostics: true,
36145             showInSimplifiedHelpView: false,
36146             category: ts.Diagnostics.Additional_Checks,
36147             description: ts.Diagnostics.Include_undefined_in_index_signature_results
36148         },
36149         // Module Resolution
36150         {
36151             name: "moduleResolution",
36152             type: new ts.Map(ts.getEntries({
36153                 node: ts.ModuleResolutionKind.NodeJs,
36154                 classic: ts.ModuleResolutionKind.Classic,
36155             })),
36156             affectsModuleResolution: true,
36157             paramType: ts.Diagnostics.STRATEGY,
36158             category: ts.Diagnostics.Module_Resolution_Options,
36159             description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
36160         },
36161         {
36162             name: "baseUrl",
36163             type: "string",
36164             affectsModuleResolution: true,
36165             isFilePath: true,
36166             category: ts.Diagnostics.Module_Resolution_Options,
36167             description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
36168         },
36169         {
36170             // this option can only be specified in tsconfig.json
36171             // use type = object to copy the value as-is
36172             name: "paths",
36173             type: "object",
36174             affectsModuleResolution: true,
36175             isTSConfigOnly: true,
36176             category: ts.Diagnostics.Module_Resolution_Options,
36177             description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
36178             transpileOptionValue: undefined
36179         },
36180         {
36181             // this option can only be specified in tsconfig.json
36182             // use type = object to copy the value as-is
36183             name: "rootDirs",
36184             type: "list",
36185             isTSConfigOnly: true,
36186             element: {
36187                 name: "rootDirs",
36188                 type: "string",
36189                 isFilePath: true
36190             },
36191             affectsModuleResolution: true,
36192             category: ts.Diagnostics.Module_Resolution_Options,
36193             description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
36194             transpileOptionValue: undefined
36195         },
36196         {
36197             name: "typeRoots",
36198             type: "list",
36199             element: {
36200                 name: "typeRoots",
36201                 type: "string",
36202                 isFilePath: true
36203             },
36204             affectsModuleResolution: true,
36205             category: ts.Diagnostics.Module_Resolution_Options,
36206             description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
36207         },
36208         {
36209             name: "types",
36210             type: "list",
36211             element: {
36212                 name: "types",
36213                 type: "string"
36214             },
36215             affectsModuleResolution: true,
36216             showInSimplifiedHelpView: true,
36217             category: ts.Diagnostics.Module_Resolution_Options,
36218             description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
36219             transpileOptionValue: undefined
36220         },
36221         {
36222             name: "allowSyntheticDefaultImports",
36223             type: "boolean",
36224             affectsSemanticDiagnostics: true,
36225             category: ts.Diagnostics.Module_Resolution_Options,
36226             description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
36227         },
36228         {
36229             name: "esModuleInterop",
36230             type: "boolean",
36231             affectsSemanticDiagnostics: true,
36232             affectsEmit: true,
36233             showInSimplifiedHelpView: true,
36234             category: ts.Diagnostics.Module_Resolution_Options,
36235             description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
36236         },
36237         {
36238             name: "preserveSymlinks",
36239             type: "boolean",
36240             category: ts.Diagnostics.Module_Resolution_Options,
36241             description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
36242         },
36243         {
36244             name: "allowUmdGlobalAccess",
36245             type: "boolean",
36246             affectsSemanticDiagnostics: true,
36247             category: ts.Diagnostics.Module_Resolution_Options,
36248             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
36249         },
36250         // Source Maps
36251         {
36252             name: "sourceRoot",
36253             type: "string",
36254             affectsEmit: true,
36255             paramType: ts.Diagnostics.LOCATION,
36256             category: ts.Diagnostics.Source_Map_Options,
36257             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
36258         },
36259         {
36260             name: "mapRoot",
36261             type: "string",
36262             affectsEmit: true,
36263             paramType: ts.Diagnostics.LOCATION,
36264             category: ts.Diagnostics.Source_Map_Options,
36265             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
36266         },
36267         {
36268             name: "inlineSourceMap",
36269             type: "boolean",
36270             affectsEmit: true,
36271             category: ts.Diagnostics.Source_Map_Options,
36272             description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
36273         },
36274         {
36275             name: "inlineSources",
36276             type: "boolean",
36277             affectsEmit: true,
36278             category: ts.Diagnostics.Source_Map_Options,
36279             description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
36280         },
36281         // Experimental
36282         {
36283             name: "experimentalDecorators",
36284             type: "boolean",
36285             affectsSemanticDiagnostics: true,
36286             category: ts.Diagnostics.Experimental_Options,
36287             description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
36288         },
36289         {
36290             name: "emitDecoratorMetadata",
36291             type: "boolean",
36292             affectsSemanticDiagnostics: true,
36293             affectsEmit: true,
36294             category: ts.Diagnostics.Experimental_Options,
36295             description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
36296         },
36297         // Advanced
36298         {
36299             name: "jsxFactory",
36300             type: "string",
36301             category: ts.Diagnostics.Advanced_Options,
36302             description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
36303         },
36304         {
36305             name: "jsxFragmentFactory",
36306             type: "string",
36307             category: ts.Diagnostics.Advanced_Options,
36308             description: ts.Diagnostics.Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment
36309         },
36310         {
36311             name: "jsxImportSource",
36312             type: "string",
36313             affectsSemanticDiagnostics: true,
36314             affectsEmit: true,
36315             affectsModuleResolution: true,
36316             category: ts.Diagnostics.Advanced_Options,
36317             description: ts.Diagnostics.Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react
36318         },
36319         {
36320             name: "resolveJsonModule",
36321             type: "boolean",
36322             affectsModuleResolution: true,
36323             category: ts.Diagnostics.Advanced_Options,
36324             description: ts.Diagnostics.Include_modules_imported_with_json_extension
36325         },
36326         {
36327             name: "out",
36328             type: "string",
36329             affectsEmit: true,
36330             isFilePath: false,
36331             // for correct behaviour, please use outFile
36332             category: ts.Diagnostics.Advanced_Options,
36333             paramType: ts.Diagnostics.FILE,
36334             description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
36335             transpileOptionValue: undefined
36336         },
36337         {
36338             name: "reactNamespace",
36339             type: "string",
36340             affectsEmit: true,
36341             category: ts.Diagnostics.Advanced_Options,
36342             description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
36343         },
36344         {
36345             name: "skipDefaultLibCheck",
36346             type: "boolean",
36347             category: ts.Diagnostics.Advanced_Options,
36348             description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
36349         },
36350         {
36351             name: "charset",
36352             type: "string",
36353             category: ts.Diagnostics.Advanced_Options,
36354             description: ts.Diagnostics.The_character_set_of_the_input_files
36355         },
36356         {
36357             name: "emitBOM",
36358             type: "boolean",
36359             affectsEmit: true,
36360             category: ts.Diagnostics.Advanced_Options,
36361             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
36362         },
36363         {
36364             name: "newLine",
36365             type: new ts.Map(ts.getEntries({
36366                 crlf: 0 /* CarriageReturnLineFeed */,
36367                 lf: 1 /* LineFeed */
36368             })),
36369             affectsEmit: true,
36370             paramType: ts.Diagnostics.NEWLINE,
36371             category: ts.Diagnostics.Advanced_Options,
36372             description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
36373         },
36374         {
36375             name: "noErrorTruncation",
36376             type: "boolean",
36377             affectsSemanticDiagnostics: true,
36378             category: ts.Diagnostics.Advanced_Options,
36379             description: ts.Diagnostics.Do_not_truncate_error_messages
36380         },
36381         {
36382             name: "noLib",
36383             type: "boolean",
36384             affectsModuleResolution: true,
36385             category: ts.Diagnostics.Advanced_Options,
36386             description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
36387             // We are not returning a sourceFile for lib file when asked by the program,
36388             // so pass --noLib to avoid reporting a file not found error.
36389             transpileOptionValue: true
36390         },
36391         {
36392             name: "noResolve",
36393             type: "boolean",
36394             affectsModuleResolution: true,
36395             category: ts.Diagnostics.Advanced_Options,
36396             description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
36397             // We are not doing a full typecheck, we are not resolving the whole context,
36398             // so pass --noResolve to avoid reporting missing file errors.
36399             transpileOptionValue: true
36400         },
36401         {
36402             name: "stripInternal",
36403             type: "boolean",
36404             affectsEmit: true,
36405             category: ts.Diagnostics.Advanced_Options,
36406             description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
36407         },
36408         {
36409             name: "disableSizeLimit",
36410             type: "boolean",
36411             affectsSourceFile: true,
36412             category: ts.Diagnostics.Advanced_Options,
36413             description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
36414         },
36415         {
36416             name: "disableSourceOfProjectReferenceRedirect",
36417             type: "boolean",
36418             isTSConfigOnly: true,
36419             category: ts.Diagnostics.Advanced_Options,
36420             description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
36421         },
36422         {
36423             name: "disableSolutionSearching",
36424             type: "boolean",
36425             isTSConfigOnly: true,
36426             category: ts.Diagnostics.Advanced_Options,
36427             description: ts.Diagnostics.Disable_solution_searching_for_this_project
36428         },
36429         {
36430             name: "disableReferencedProjectLoad",
36431             type: "boolean",
36432             isTSConfigOnly: true,
36433             category: ts.Diagnostics.Advanced_Options,
36434             description: ts.Diagnostics.Disable_loading_referenced_projects
36435         },
36436         {
36437             name: "noImplicitUseStrict",
36438             type: "boolean",
36439             affectsSemanticDiagnostics: true,
36440             category: ts.Diagnostics.Advanced_Options,
36441             description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
36442         },
36443         {
36444             name: "noEmitHelpers",
36445             type: "boolean",
36446             affectsEmit: true,
36447             category: ts.Diagnostics.Advanced_Options,
36448             description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
36449         },
36450         {
36451             name: "noEmitOnError",
36452             type: "boolean",
36453             affectsEmit: true,
36454             category: ts.Diagnostics.Advanced_Options,
36455             description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
36456             transpileOptionValue: undefined
36457         },
36458         {
36459             name: "preserveConstEnums",
36460             type: "boolean",
36461             affectsEmit: true,
36462             category: ts.Diagnostics.Advanced_Options,
36463             description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
36464         },
36465         {
36466             name: "declarationDir",
36467             type: "string",
36468             affectsEmit: true,
36469             isFilePath: true,
36470             paramType: ts.Diagnostics.DIRECTORY,
36471             category: ts.Diagnostics.Advanced_Options,
36472             description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
36473             transpileOptionValue: undefined
36474         },
36475         {
36476             name: "skipLibCheck",
36477             type: "boolean",
36478             category: ts.Diagnostics.Advanced_Options,
36479             description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
36480         },
36481         {
36482             name: "allowUnusedLabels",
36483             type: "boolean",
36484             affectsBindDiagnostics: true,
36485             affectsSemanticDiagnostics: true,
36486             category: ts.Diagnostics.Advanced_Options,
36487             description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
36488         },
36489         {
36490             name: "allowUnreachableCode",
36491             type: "boolean",
36492             affectsBindDiagnostics: true,
36493             affectsSemanticDiagnostics: true,
36494             category: ts.Diagnostics.Advanced_Options,
36495             description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
36496         },
36497         {
36498             name: "suppressExcessPropertyErrors",
36499             type: "boolean",
36500             affectsSemanticDiagnostics: true,
36501             category: ts.Diagnostics.Advanced_Options,
36502             description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
36503         },
36504         {
36505             name: "suppressImplicitAnyIndexErrors",
36506             type: "boolean",
36507             affectsSemanticDiagnostics: true,
36508             category: ts.Diagnostics.Advanced_Options,
36509             description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
36510         },
36511         {
36512             name: "forceConsistentCasingInFileNames",
36513             type: "boolean",
36514             affectsModuleResolution: true,
36515             category: ts.Diagnostics.Advanced_Options,
36516             description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
36517         },
36518         {
36519             name: "maxNodeModuleJsDepth",
36520             type: "number",
36521             affectsModuleResolution: true,
36522             category: ts.Diagnostics.Advanced_Options,
36523             description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
36524         },
36525         {
36526             name: "noStrictGenericChecks",
36527             type: "boolean",
36528             affectsSemanticDiagnostics: true,
36529             category: ts.Diagnostics.Advanced_Options,
36530             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
36531         },
36532         {
36533             name: "useDefineForClassFields",
36534             type: "boolean",
36535             affectsSemanticDiagnostics: true,
36536             affectsEmit: true,
36537             category: ts.Diagnostics.Advanced_Options,
36538             description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
36539         },
36540         {
36541             name: "keyofStringsOnly",
36542             type: "boolean",
36543             category: ts.Diagnostics.Advanced_Options,
36544             description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
36545         },
36546         {
36547             // A list of plugins to load in the language service
36548             name: "plugins",
36549             type: "list",
36550             isTSConfigOnly: true,
36551             element: {
36552                 name: "plugin",
36553                 type: "object"
36554             },
36555             description: ts.Diagnostics.List_of_language_service_plugins
36556         },
36557     ]);
36558     /* @internal */
36559     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
36560     /* @internal */
36561     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
36562     /* @internal */
36563     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
36564     /* @internal */
36565     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
36566         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
36567     });
36568     /* @internal */
36569     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
36570         return ts.hasProperty(option, "transpileOptionValue");
36571     });
36572     /* @internal */
36573     ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
36574         {
36575             name: "verbose",
36576             shortName: "v",
36577             category: ts.Diagnostics.Command_line_Options,
36578             description: ts.Diagnostics.Enable_verbose_logging,
36579             type: "boolean"
36580         },
36581         {
36582             name: "dry",
36583             shortName: "d",
36584             category: ts.Diagnostics.Command_line_Options,
36585             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
36586             type: "boolean"
36587         },
36588         {
36589             name: "force",
36590             shortName: "f",
36591             category: ts.Diagnostics.Command_line_Options,
36592             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
36593             type: "boolean"
36594         },
36595         {
36596             name: "clean",
36597             category: ts.Diagnostics.Command_line_Options,
36598             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
36599             type: "boolean"
36600         }
36601     ]);
36602     /* @internal */
36603     ts.typeAcquisitionDeclarations = [
36604         {
36605             /* @deprecated typingOptions.enableAutoDiscovery
36606              * Use typeAcquisition.enable instead.
36607              */
36608             name: "enableAutoDiscovery",
36609             type: "boolean",
36610         },
36611         {
36612             name: "enable",
36613             type: "boolean",
36614         },
36615         {
36616             name: "include",
36617             type: "list",
36618             element: {
36619                 name: "include",
36620                 type: "string"
36621             }
36622         },
36623         {
36624             name: "exclude",
36625             type: "list",
36626             element: {
36627                 name: "exclude",
36628                 type: "string"
36629             }
36630         },
36631         {
36632             name: "disableFilenameBasedTypeAcquisition",
36633             type: "boolean",
36634         },
36635     ];
36636     /*@internal*/
36637     function createOptionNameMap(optionDeclarations) {
36638         var optionsNameMap = new ts.Map();
36639         var shortOptionNames = new ts.Map();
36640         ts.forEach(optionDeclarations, function (option) {
36641             optionsNameMap.set(option.name.toLowerCase(), option);
36642             if (option.shortName) {
36643                 shortOptionNames.set(option.shortName, option.name);
36644             }
36645         });
36646         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
36647     }
36648     ts.createOptionNameMap = createOptionNameMap;
36649     var optionsNameMapCache;
36650     /* @internal */
36651     function getOptionsNameMap() {
36652         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
36653     }
36654     ts.getOptionsNameMap = getOptionsNameMap;
36655     /* @internal */
36656     ts.defaultInitCompilerOptions = {
36657         module: ts.ModuleKind.CommonJS,
36658         target: 1 /* ES5 */,
36659         strict: true,
36660         esModuleInterop: true,
36661         forceConsistentCasingInFileNames: true,
36662         skipLibCheck: true
36663     };
36664     /* @internal */
36665     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
36666         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
36667         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
36668             return {
36669                 enable: typeAcquisition.enableAutoDiscovery,
36670                 include: typeAcquisition.include || [],
36671                 exclude: typeAcquisition.exclude || []
36672             };
36673         }
36674         return typeAcquisition;
36675     }
36676     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
36677     /* @internal */
36678     function createCompilerDiagnosticForInvalidCustomType(opt) {
36679         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
36680     }
36681     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
36682     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
36683         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
36684         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
36685     }
36686     /* @internal */
36687     function parseCustomTypeOption(opt, value, errors) {
36688         return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
36689     }
36690     ts.parseCustomTypeOption = parseCustomTypeOption;
36691     /* @internal */
36692     function parseListTypeOption(opt, value, errors) {
36693         if (value === void 0) { value = ""; }
36694         value = trimString(value);
36695         if (ts.startsWith(value, "-")) {
36696             return undefined;
36697         }
36698         if (value === "") {
36699             return [];
36700         }
36701         var values = value.split(",");
36702         switch (opt.element.type) {
36703             case "number":
36704                 return ts.map(values, parseInt);
36705             case "string":
36706                 return ts.map(values, function (v) { return v || ""; });
36707             default:
36708                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
36709         }
36710     }
36711     ts.parseListTypeOption = parseListTypeOption;
36712     function getOptionName(option) {
36713         return option.name;
36714     }
36715     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
36716         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
36717         return possibleOption ?
36718             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
36719             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
36720     }
36721     /*@internal*/
36722     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
36723         var options = {};
36724         var watchOptions;
36725         var fileNames = [];
36726         var errors = [];
36727         parseStrings(commandLine);
36728         return {
36729             options: options,
36730             watchOptions: watchOptions,
36731             fileNames: fileNames,
36732             errors: errors
36733         };
36734         function parseStrings(args) {
36735             var i = 0;
36736             while (i < args.length) {
36737                 var s = args[i];
36738                 i++;
36739                 if (s.charCodeAt(0) === 64 /* at */) {
36740                     parseResponseFile(s.slice(1));
36741                 }
36742                 else if (s.charCodeAt(0) === 45 /* minus */) {
36743                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
36744                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
36745                     if (opt) {
36746                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
36747                     }
36748                     else {
36749                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
36750                         if (watchOpt) {
36751                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
36752                         }
36753                         else {
36754                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
36755                         }
36756                     }
36757                 }
36758                 else {
36759                     fileNames.push(s);
36760                 }
36761             }
36762         }
36763         function parseResponseFile(fileName) {
36764             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
36765             if (!ts.isString(text)) {
36766                 errors.push(text);
36767                 return;
36768             }
36769             var args = [];
36770             var pos = 0;
36771             while (true) {
36772                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
36773                     pos++;
36774                 if (pos >= text.length)
36775                     break;
36776                 var start = pos;
36777                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
36778                     pos++;
36779                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
36780                         pos++;
36781                     if (pos < text.length) {
36782                         args.push(text.substring(start + 1, pos));
36783                         pos++;
36784                     }
36785                     else {
36786                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
36787                     }
36788                 }
36789                 else {
36790                     while (text.charCodeAt(pos) > 32 /* space */)
36791                         pos++;
36792                     args.push(text.substring(start, pos));
36793                 }
36794             }
36795             parseStrings(args);
36796         }
36797     }
36798     ts.parseCommandLineWorker = parseCommandLineWorker;
36799     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
36800         if (opt.isTSConfigOnly) {
36801             var optValue = args[i];
36802             if (optValue === "null") {
36803                 options[opt.name] = undefined;
36804                 i++;
36805             }
36806             else if (opt.type === "boolean") {
36807                 if (optValue === "false") {
36808                     options[opt.name] = false;
36809                     i++;
36810                 }
36811                 else {
36812                     if (optValue === "true")
36813                         i++;
36814                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name));
36815                 }
36816             }
36817             else {
36818                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name));
36819                 if (optValue && !ts.startsWith(optValue, "-"))
36820                     i++;
36821             }
36822         }
36823         else {
36824             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
36825             if (!args[i] && opt.type !== "boolean") {
36826                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
36827             }
36828             if (args[i] !== "null") {
36829                 switch (opt.type) {
36830                     case "number":
36831                         options[opt.name] = parseInt(args[i]);
36832                         i++;
36833                         break;
36834                     case "boolean":
36835                         // boolean flag has optional value true, false, others
36836                         var optValue = args[i];
36837                         options[opt.name] = optValue !== "false";
36838                         // consume next argument as boolean flag value
36839                         if (optValue === "false" || optValue === "true") {
36840                             i++;
36841                         }
36842                         break;
36843                     case "string":
36844                         options[opt.name] = args[i] || "";
36845                         i++;
36846                         break;
36847                     case "list":
36848                         var result = parseListTypeOption(opt, args[i], errors);
36849                         options[opt.name] = result || [];
36850                         if (result) {
36851                             i++;
36852                         }
36853                         break;
36854                     // If not a primitive, the possible types are specified in what is effectively a map of options.
36855                     default:
36856                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
36857                         i++;
36858                         break;
36859                 }
36860             }
36861             else {
36862                 options[opt.name] = undefined;
36863                 i++;
36864             }
36865         }
36866         return i;
36867     }
36868     /*@internal*/
36869     ts.compilerOptionsDidYouMeanDiagnostics = {
36870         getOptionsNameMap: getOptionsNameMap,
36871         optionDeclarations: ts.optionDeclarations,
36872         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
36873         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
36874         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
36875     };
36876     function parseCommandLine(commandLine, readFile) {
36877         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
36878     }
36879     ts.parseCommandLine = parseCommandLine;
36880     /** @internal */
36881     function getOptionFromName(optionName, allowShort) {
36882         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
36883     }
36884     ts.getOptionFromName = getOptionFromName;
36885     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
36886         if (allowShort === void 0) { allowShort = false; }
36887         optionName = optionName.toLowerCase();
36888         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
36889         // Try to translate short option names to their full equivalents.
36890         if (allowShort) {
36891             var short = shortOptionNames.get(optionName);
36892             if (short !== undefined) {
36893                 optionName = short;
36894             }
36895         }
36896         return optionsNameMap.get(optionName);
36897     }
36898     var buildOptionsNameMapCache;
36899     function getBuildOptionsNameMap() {
36900         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
36901     }
36902     var buildOptionsDidYouMeanDiagnostics = {
36903         getOptionsNameMap: getBuildOptionsNameMap,
36904         optionDeclarations: ts.buildOpts,
36905         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
36906         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
36907         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
36908     };
36909     /*@internal*/
36910     function parseBuildCommand(args) {
36911         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
36912         var buildOptions = options;
36913         if (projects.length === 0) {
36914             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
36915             projects.push(".");
36916         }
36917         // Nonsensical combinations
36918         if (buildOptions.clean && buildOptions.force) {
36919             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
36920         }
36921         if (buildOptions.clean && buildOptions.verbose) {
36922             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
36923         }
36924         if (buildOptions.clean && buildOptions.watch) {
36925             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
36926         }
36927         if (buildOptions.watch && buildOptions.dry) {
36928             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
36929         }
36930         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
36931     }
36932     ts.parseBuildCommand = parseBuildCommand;
36933     /* @internal */
36934     function getDiagnosticText(_message) {
36935         var _args = [];
36936         for (var _i = 1; _i < arguments.length; _i++) {
36937             _args[_i - 1] = arguments[_i];
36938         }
36939         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
36940         return diagnostic.messageText;
36941     }
36942     ts.getDiagnosticText = getDiagnosticText;
36943     /**
36944      * Reads the config file, reports errors if any and exits if the config file cannot be found
36945      */
36946     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
36947         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
36948         if (!ts.isString(configFileText)) {
36949             host.onUnRecoverableConfigFileDiagnostic(configFileText);
36950             return undefined;
36951         }
36952         var result = ts.parseJsonText(configFileName, configFileText);
36953         var cwd = host.getCurrentDirectory();
36954         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
36955         result.resolvedPath = result.path;
36956         result.originalFileName = result.fileName;
36957         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
36958         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
36959     }
36960     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
36961     /**
36962      * Read tsconfig.json file
36963      * @param fileName The path to the config file
36964      */
36965     function readConfigFile(fileName, readFile) {
36966         var textOrDiagnostic = tryReadFile(fileName, readFile);
36967         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
36968     }
36969     ts.readConfigFile = readConfigFile;
36970     /**
36971      * Parse the text of the tsconfig.json file
36972      * @param fileName The path to the config file
36973      * @param jsonText The text of the config file
36974      */
36975     function parseConfigFileTextToJson(fileName, jsonText) {
36976         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
36977         return {
36978             config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
36979             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
36980         };
36981     }
36982     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
36983     /**
36984      * Read tsconfig.json file
36985      * @param fileName The path to the config file
36986      */
36987     function readJsonConfigFile(fileName, readFile) {
36988         var textOrDiagnostic = tryReadFile(fileName, readFile);
36989         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { fileName: fileName, parseDiagnostics: [textOrDiagnostic] };
36990     }
36991     ts.readJsonConfigFile = readJsonConfigFile;
36992     /*@internal*/
36993     function tryReadFile(fileName, readFile) {
36994         var text;
36995         try {
36996             text = readFile(fileName);
36997         }
36998         catch (e) {
36999             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
37000         }
37001         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
37002     }
37003     ts.tryReadFile = tryReadFile;
37004     function commandLineOptionsToMap(options) {
37005         return ts.arrayToMap(options, getOptionName);
37006     }
37007     var typeAcquisitionDidYouMeanDiagnostics = {
37008         optionDeclarations: ts.typeAcquisitionDeclarations,
37009         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
37010         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
37011     };
37012     var watchOptionsNameMapCache;
37013     function getWatchOptionsNameMap() {
37014         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
37015     }
37016     var watchOptionsDidYouMeanDiagnostics = {
37017         getOptionsNameMap: getWatchOptionsNameMap,
37018         optionDeclarations: ts.optionsForWatch,
37019         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
37020         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
37021         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
37022     };
37023     var commandLineCompilerOptionsMapCache;
37024     function getCommandLineCompilerOptionsMap() {
37025         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
37026     }
37027     var commandLineWatchOptionsMapCache;
37028     function getCommandLineWatchOptionsMap() {
37029         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
37030     }
37031     var commandLineTypeAcquisitionMapCache;
37032     function getCommandLineTypeAcquisitionMap() {
37033         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
37034     }
37035     var _tsconfigRootOptions;
37036     function getTsconfigRootOptionsMap() {
37037         if (_tsconfigRootOptions === undefined) {
37038             _tsconfigRootOptions = {
37039                 name: undefined,
37040                 type: "object",
37041                 elementOptions: commandLineOptionsToMap([
37042                     {
37043                         name: "compilerOptions",
37044                         type: "object",
37045                         elementOptions: getCommandLineCompilerOptionsMap(),
37046                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
37047                     },
37048                     {
37049                         name: "watchOptions",
37050                         type: "object",
37051                         elementOptions: getCommandLineWatchOptionsMap(),
37052                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
37053                     },
37054                     {
37055                         name: "typingOptions",
37056                         type: "object",
37057                         elementOptions: getCommandLineTypeAcquisitionMap(),
37058                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
37059                     },
37060                     {
37061                         name: "typeAcquisition",
37062                         type: "object",
37063                         elementOptions: getCommandLineTypeAcquisitionMap(),
37064                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
37065                     },
37066                     {
37067                         name: "extends",
37068                         type: "string"
37069                     },
37070                     {
37071                         name: "references",
37072                         type: "list",
37073                         element: {
37074                             name: "references",
37075                             type: "object"
37076                         }
37077                     },
37078                     {
37079                         name: "files",
37080                         type: "list",
37081                         element: {
37082                             name: "files",
37083                             type: "string"
37084                         }
37085                     },
37086                     {
37087                         name: "include",
37088                         type: "list",
37089                         element: {
37090                             name: "include",
37091                             type: "string"
37092                         }
37093                     },
37094                     {
37095                         name: "exclude",
37096                         type: "list",
37097                         element: {
37098                             name: "exclude",
37099                             type: "string"
37100                         }
37101                     },
37102                     ts.compileOnSaveCommandLineOption
37103                 ])
37104             };
37105         }
37106         return _tsconfigRootOptions;
37107     }
37108     /**
37109      * Convert the json syntax tree into the json value
37110      */
37111     function convertToObject(sourceFile, errors) {
37112         return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
37113     }
37114     ts.convertToObject = convertToObject;
37115     /**
37116      * Convert the json syntax tree into the json value and report errors
37117      * This returns the json value (apart from checking errors) only if returnValue provided is true.
37118      * Otherwise it just checks the errors and returns undefined
37119      */
37120     /*@internal*/
37121     function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
37122         if (!sourceFile.statements.length) {
37123             return returnValue ? {} : undefined;
37124         }
37125         return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
37126         function isRootOptionMap(knownOptions) {
37127             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
37128         }
37129         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
37130             var result = returnValue ? {} : undefined;
37131             var _loop_4 = function (element) {
37132                 if (element.kind !== 288 /* PropertyAssignment */) {
37133                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
37134                     return "continue";
37135                 }
37136                 if (element.questionToken) {
37137                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
37138                 }
37139                 if (!isDoubleQuotedString(element.name)) {
37140                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
37141                 }
37142                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
37143                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
37144                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
37145                 if (keyText && extraKeyDiagnostics && !option) {
37146                     if (knownOptions) {
37147                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
37148                     }
37149                     else {
37150                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
37151                     }
37152                 }
37153                 var value = convertPropertyValueToJson(element.initializer, option);
37154                 if (typeof keyText !== "undefined") {
37155                     if (returnValue) {
37156                         result[keyText] = value;
37157                     }
37158                     // Notify key value set, if user asked for it
37159                     if (jsonConversionNotifier &&
37160                         // Current callbacks are only on known parent option or if we are setting values in the root
37161                         (parentOption || isRootOptionMap(knownOptions))) {
37162                         var isValidOptionValue = isCompilerOptionsValue(option, value);
37163                         if (parentOption) {
37164                             if (isValidOptionValue) {
37165                                 // Notify option set in the parent if its a valid option value
37166                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
37167                             }
37168                         }
37169                         else if (isRootOptionMap(knownOptions)) {
37170                             if (isValidOptionValue) {
37171                                 // Notify about the valid root key value being set
37172                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
37173                             }
37174                             else if (!option) {
37175                                 // Notify about the unknown root key value being set
37176                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
37177                             }
37178                         }
37179                     }
37180                 }
37181             };
37182             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
37183                 var element = _a[_i];
37184                 _loop_4(element);
37185             }
37186             return result;
37187         }
37188         function convertArrayLiteralExpressionToJson(elements, elementOption) {
37189             if (!returnValue) {
37190                 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
37191             }
37192             // Filter out invalid values
37193             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
37194         }
37195         function convertPropertyValueToJson(valueExpression, option) {
37196             switch (valueExpression.kind) {
37197                 case 109 /* TrueKeyword */:
37198                     reportInvalidOptionValue(option && option.type !== "boolean");
37199                     return true;
37200                 case 94 /* FalseKeyword */:
37201                     reportInvalidOptionValue(option && option.type !== "boolean");
37202                     return false;
37203                 case 103 /* NullKeyword */:
37204                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
37205                     return null; // eslint-disable-line no-null/no-null
37206                 case 10 /* StringLiteral */:
37207                     if (!isDoubleQuotedString(valueExpression)) {
37208                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
37209                     }
37210                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
37211                     var text = valueExpression.text;
37212                     if (option && !ts.isString(option.type)) {
37213                         var customOption = option;
37214                         // Validate custom option type
37215                         if (!customOption.type.has(text.toLowerCase())) {
37216                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
37217                         }
37218                     }
37219                     return text;
37220                 case 8 /* NumericLiteral */:
37221                     reportInvalidOptionValue(option && option.type !== "number");
37222                     return Number(valueExpression.text);
37223                 case 214 /* PrefixUnaryExpression */:
37224                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
37225                         break; // not valid JSON syntax
37226                     }
37227                     reportInvalidOptionValue(option && option.type !== "number");
37228                     return -Number(valueExpression.operand.text);
37229                 case 200 /* ObjectLiteralExpression */:
37230                     reportInvalidOptionValue(option && option.type !== "object");
37231                     var objectLiteralExpression = valueExpression;
37232                     // Currently having element option declaration in the tsconfig with type "object"
37233                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
37234                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
37235                     // that satifies it and need it to modify options set in them (for normalizing file paths)
37236                     // vs what we set in the json
37237                     // If need arises, we can modify this interface and callbacks as needed
37238                     if (option) {
37239                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
37240                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
37241                     }
37242                     else {
37243                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
37244                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
37245                     }
37246                 case 199 /* ArrayLiteralExpression */:
37247                     reportInvalidOptionValue(option && option.type !== "list");
37248                     return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
37249             }
37250             // Not in expected format
37251             if (option) {
37252                 reportInvalidOptionValue(/*isError*/ true);
37253             }
37254             else {
37255                 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));
37256             }
37257             return undefined;
37258             function reportInvalidOptionValue(isError) {
37259                 if (isError) {
37260                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
37261                 }
37262             }
37263         }
37264         function isDoubleQuotedString(node) {
37265             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
37266         }
37267     }
37268     ts.convertToObjectWorker = convertToObjectWorker;
37269     function getCompilerOptionValueTypeString(option) {
37270         return option.type === "list" ?
37271             "Array" :
37272             ts.isString(option.type) ? option.type : "string";
37273     }
37274     function isCompilerOptionsValue(option, value) {
37275         if (option) {
37276             if (isNullOrUndefined(value))
37277                 return true; // All options are undefinable/nullable
37278             if (option.type === "list") {
37279                 return ts.isArray(value);
37280             }
37281             var expectedType = ts.isString(option.type) ? option.type : "string";
37282             return typeof value === expectedType;
37283         }
37284         return false;
37285     }
37286     /**
37287      * Generate an uncommented, complete tsconfig for use with "--showConfig"
37288      * @param configParseResult options to be generated into tsconfig.json
37289      * @param configFileName name of the parsed config file - output paths will be generated relative to this
37290      * @param host provides current directory and case sensitivity services
37291      */
37292     /** @internal */
37293     function convertToTSConfig(configParseResult, configFileName, host) {
37294         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
37295         var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); });
37296         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
37297         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
37298         var config = __assign(__assign({ compilerOptions: __assign(__assign({}, optionMapToObject(optionMap)), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign(__assign({}, r), { path: r.originalPath ? r.originalPath : "", originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? {
37299             include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
37300             exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
37301         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
37302         return config;
37303     }
37304     ts.convertToTSConfig = convertToTSConfig;
37305     function optionMapToObject(optionMap) {
37306         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
37307             var _a;
37308             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
37309         }, {}));
37310     }
37311     function filterSameAsDefaultInclude(specs) {
37312         if (!ts.length(specs))
37313             return undefined;
37314         if (ts.length(specs) !== 1)
37315             return specs;
37316         if (specs[0] === "**/*")
37317             return undefined;
37318         return specs;
37319     }
37320     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
37321         if (!includeSpecs)
37322             return function (_) { return true; };
37323         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
37324         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
37325         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
37326         if (includeRe) {
37327             if (excludeRe) {
37328                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
37329             }
37330             return function (path) { return !includeRe.test(path); };
37331         }
37332         if (excludeRe) {
37333             return function (path) { return excludeRe.test(path); };
37334         }
37335         return function (_) { return true; };
37336     }
37337     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
37338         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
37339             // this is of a type CommandLineOptionOfPrimitiveType
37340             return undefined;
37341         }
37342         else if (optionDefinition.type === "list") {
37343             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
37344         }
37345         else {
37346             return optionDefinition.type;
37347         }
37348     }
37349     function getNameOfCompilerOptionValue(value, customTypeMap) {
37350         // There is a typeMap associated with this command-line option so use it to map value back to its name
37351         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
37352             if (mapValue === value) {
37353                 return key;
37354             }
37355         });
37356     }
37357     function serializeCompilerOptions(options, pathOptions) {
37358         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
37359     }
37360     function serializeWatchOptions(options) {
37361         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
37362     }
37363     function serializeOptionBaseObject(options, _a, pathOptions) {
37364         var optionsNameMap = _a.optionsNameMap;
37365         var result = new ts.Map();
37366         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
37367         var _loop_5 = function (name) {
37368             if (ts.hasProperty(options, name)) {
37369                 // tsconfig only options cannot be specified via command line,
37370                 // so we can assume that only types that can appear here string | number | boolean
37371                 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
37372                     return "continue";
37373                 }
37374                 var value = options[name];
37375                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
37376                 if (optionDefinition) {
37377                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
37378                     if (!customTypeMap_1) {
37379                         // There is no map associated with this compiler option then use the value as-is
37380                         // This is the case if the value is expect to be string, number, boolean or list of string
37381                         if (pathOptions && optionDefinition.isFilePath) {
37382                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
37383                         }
37384                         else {
37385                             result.set(name, value);
37386                         }
37387                     }
37388                     else {
37389                         if (optionDefinition.type === "list") {
37390                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
37391                         }
37392                         else {
37393                             // There is a typeMap associated with this command-line option so use it to map value back to its name
37394                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
37395                         }
37396                     }
37397                 }
37398             }
37399         };
37400         for (var name in options) {
37401             _loop_5(name);
37402         }
37403         return result;
37404     }
37405     /**
37406      * Generate tsconfig configuration when running command line "--init"
37407      * @param options commandlineOptions to be generated into tsconfig.json
37408      * @param fileNames array of filenames to be generated into tsconfig.json
37409      */
37410     /* @internal */
37411     function generateTSConfig(options, fileNames, newLine) {
37412         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
37413         var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
37414         return writeConfigurations();
37415         function getDefaultValueForOption(option) {
37416             switch (option.type) {
37417                 case "number":
37418                     return 1;
37419                 case "boolean":
37420                     return true;
37421                 case "string":
37422                     return option.isFilePath ? "./" : "";
37423                 case "list":
37424                     return [];
37425                 case "object":
37426                     return {};
37427                 default:
37428                     var iterResult = option.type.keys().next();
37429                     if (!iterResult.done)
37430                         return iterResult.value;
37431                     return ts.Debug.fail("Expected 'option.type' to have entries.");
37432             }
37433         }
37434         function makePadding(paddingLength) {
37435             return Array(paddingLength + 1).join(" ");
37436         }
37437         function isAllowedOption(_a) {
37438             var category = _a.category, name = _a.name;
37439             // Skip options which do not have a category or have category `Command_line_Options`
37440             // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
37441             return category !== undefined
37442                 && category !== ts.Diagnostics.Command_line_Options
37443                 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
37444         }
37445         function writeConfigurations() {
37446             // Filter applicable options to place in the file
37447             var categorizedOptions = ts.createMultiMap();
37448             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
37449                 var option = optionDeclarations_1[_i];
37450                 var category = option.category;
37451                 if (isAllowedOption(option)) {
37452                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
37453                 }
37454             }
37455             // Serialize all options and their descriptions
37456             var marginLength = 0;
37457             var seenKnownKeys = 0;
37458             var entries = [];
37459             categorizedOptions.forEach(function (options, category) {
37460                 if (entries.length !== 0) {
37461                     entries.push({ value: "" });
37462                 }
37463                 entries.push({ value: "/* " + category + " */" });
37464                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
37465                     var option = options_1[_i];
37466                     var optionName = void 0;
37467                     if (compilerOptionsMap.has(option.name)) {
37468                         optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
37469                     }
37470                     else {
37471                         optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
37472                     }
37473                     entries.push({
37474                         value: optionName,
37475                         description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
37476                     });
37477                     marginLength = Math.max(optionName.length, marginLength);
37478                 }
37479             });
37480             // Write the output
37481             var tab = makePadding(2);
37482             var result = [];
37483             result.push("{");
37484             result.push(tab + "\"compilerOptions\": {");
37485             result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
37486             result.push("");
37487             // Print out each row, aligning all the descriptions on the same column.
37488             for (var _a = 0, entries_2 = entries; _a < entries_2.length; _a++) {
37489                 var entry = entries_2[_a];
37490                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
37491                 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
37492             }
37493             if (fileNames.length) {
37494                 result.push(tab + "},");
37495                 result.push(tab + "\"files\": [");
37496                 for (var i = 0; i < fileNames.length; i++) {
37497                     result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
37498                 }
37499                 result.push(tab + "]");
37500             }
37501             else {
37502                 result.push(tab + "}");
37503             }
37504             result.push("}");
37505             return result.join(newLine) + newLine;
37506         }
37507     }
37508     ts.generateTSConfig = generateTSConfig;
37509     /* @internal */
37510     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
37511         var result = {};
37512         var optionsNameMap = getOptionsNameMap().optionsNameMap;
37513         for (var name in options) {
37514             if (ts.hasProperty(options, name)) {
37515                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
37516             }
37517         }
37518         if (result.configFilePath) {
37519             result.configFilePath = toAbsolutePath(result.configFilePath);
37520         }
37521         return result;
37522     }
37523     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
37524     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
37525         if (option && !isNullOrUndefined(value)) {
37526             if (option.type === "list") {
37527                 var values = value;
37528                 if (option.element.isFilePath && values.length) {
37529                     return values.map(toAbsolutePath);
37530                 }
37531             }
37532             else if (option.isFilePath) {
37533                 return toAbsolutePath(value);
37534             }
37535         }
37536         return value;
37537     }
37538     /**
37539      * Parse the contents of a config file (tsconfig.json).
37540      * @param json The contents of the config file to parse
37541      * @param host Instance of ParseConfigHost used to enumerate files in folder.
37542      * @param basePath A root directory to resolve relative path entries in the config
37543      *    file to. e.g. outDir
37544      */
37545     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
37546         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
37547     }
37548     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
37549     /**
37550      * Parse the contents of a config file (tsconfig.json).
37551      * @param jsonNode The contents of the config file to parse
37552      * @param host Instance of ParseConfigHost used to enumerate files in folder.
37553      * @param basePath A root directory to resolve relative path entries in the config
37554      *    file to. e.g. outDir
37555      */
37556     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
37557         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
37558     }
37559     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
37560     /*@internal*/
37561     function setConfigFileInOptions(options, configFile) {
37562         if (configFile) {
37563             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
37564         }
37565     }
37566     ts.setConfigFileInOptions = setConfigFileInOptions;
37567     function isNullOrUndefined(x) {
37568         return x === undefined || x === null; // eslint-disable-line no-null/no-null
37569     }
37570     function directoryOfCombinedPath(fileName, basePath) {
37571         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
37572         // until consistent casing errors are reported
37573         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
37574     }
37575     /**
37576      * Parse the contents of a config file from json or json source file (tsconfig.json).
37577      * @param json The contents of the config file to parse
37578      * @param sourceFile sourceFile corresponding to the Json
37579      * @param host Instance of ParseConfigHost used to enumerate files in folder.
37580      * @param basePath A root directory to resolve relative path entries in the config
37581      *    file to. e.g. outDir
37582      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
37583      */
37584     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
37585         if (existingOptions === void 0) { existingOptions = {}; }
37586         if (resolutionStack === void 0) { resolutionStack = []; }
37587         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
37588         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
37589         var errors = [];
37590         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
37591         var raw = parsedConfig.raw;
37592         var options = ts.extend(existingOptions, parsedConfig.options || {});
37593         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
37594             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
37595             parsedConfig.watchOptions || existingWatchOptions;
37596         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
37597         setConfigFileInOptions(options, sourceFile);
37598         var projectReferences;
37599         var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
37600         return {
37601             options: options,
37602             watchOptions: watchOptions,
37603             fileNames: fileNames,
37604             projectReferences: projectReferences,
37605             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
37606             raw: raw,
37607             errors: errors,
37608             wildcardDirectories: wildcardDirectories,
37609             compileOnSave: !!raw.compileOnSave,
37610             configFileSpecs: spec
37611         };
37612         function getFileNames() {
37613             var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
37614             if (ts.isArray(referencesOfRaw)) {
37615                 for (var _i = 0, referencesOfRaw_1 = referencesOfRaw; _i < referencesOfRaw_1.length; _i++) {
37616                     var ref = referencesOfRaw_1[_i];
37617                     if (typeof ref.path !== "string") {
37618                         createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
37619                     }
37620                     else {
37621                         (projectReferences || (projectReferences = [])).push({
37622                             path: ts.getNormalizedAbsolutePath(ref.path, basePath),
37623                             originalPath: ref.path,
37624                             prepend: ref.prepend,
37625                             circular: ref.circular
37626                         });
37627                     }
37628                 }
37629             }
37630             var filesSpecs = toPropValue(getSpecsFromRaw("files"));
37631             if (filesSpecs) {
37632                 var hasZeroOrNoReferences = referencesOfRaw === "no-prop" || ts.isArray(referencesOfRaw) && referencesOfRaw.length === 0;
37633                 var hasExtends = ts.hasProperty(raw, "extends");
37634                 if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
37635                     if (sourceFile) {
37636                         var fileName = configFileName || "tsconfig.json";
37637                         var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
37638                         var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
37639                         var error = nodeValue
37640                             ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
37641                             : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
37642                         errors.push(error);
37643                     }
37644                     else {
37645                         createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
37646                     }
37647                 }
37648             }
37649             var includeSpecs = toPropValue(getSpecsFromRaw("include"));
37650             var excludeOfRaw = getSpecsFromRaw("exclude");
37651             var excludeSpecs = toPropValue(excludeOfRaw);
37652             if (excludeOfRaw === "no-prop" && raw.compilerOptions) {
37653                 var outDir = raw.compilerOptions.outDir;
37654                 var declarationDir = raw.compilerOptions.declarationDir;
37655                 if (outDir || declarationDir) {
37656                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
37657                 }
37658             }
37659             if (filesSpecs === undefined && includeSpecs === undefined) {
37660                 includeSpecs = ["**/*"];
37661             }
37662             var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
37663             if (shouldReportNoInputFiles(result, canJsonReportNoInputFiles(raw), resolutionStack)) {
37664                 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
37665             }
37666             return result;
37667         }
37668         function toPropValue(specResult) {
37669             return ts.isArray(specResult) ? specResult : undefined;
37670         }
37671         function getSpecsFromRaw(prop) {
37672             return getPropFromRaw(prop, ts.isString, "string");
37673         }
37674         function getPropFromRaw(prop, validateElement, elementTypeName) {
37675             if (ts.hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) {
37676                 if (ts.isArray(raw[prop])) {
37677                     var result = raw[prop];
37678                     if (!sourceFile && !ts.every(result, validateElement)) {
37679                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName));
37680                     }
37681                     return result;
37682                 }
37683                 else {
37684                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, "Array");
37685                     return "not-array";
37686                 }
37687             }
37688             return "no-prop";
37689         }
37690         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
37691             if (!sourceFile) {
37692                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
37693             }
37694         }
37695     }
37696     function isErrorNoInputFiles(error) {
37697         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
37698     }
37699     function getErrorForNoInputFiles(_a, configFileName) {
37700         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
37701         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 || []));
37702     }
37703     function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
37704         return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
37705     }
37706     /*@internal*/
37707     function canJsonReportNoInputFiles(raw) {
37708         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
37709     }
37710     ts.canJsonReportNoInputFiles = canJsonReportNoInputFiles;
37711     /*@internal*/
37712     function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
37713         var existingErrors = configParseDiagnostics.length;
37714         if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
37715             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
37716         }
37717         else {
37718             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
37719         }
37720         return existingErrors !== configParseDiagnostics.length;
37721     }
37722     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
37723     function isSuccessfulParsedTsconfig(value) {
37724         return !!value.options;
37725     }
37726     /**
37727      * This *just* extracts options/include/exclude/files out of a config file.
37728      * It does *not* resolve the included files.
37729      */
37730     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
37731         var _a;
37732         basePath = ts.normalizeSlashes(basePath);
37733         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
37734         if (resolutionStack.indexOf(resolvedPath) >= 0) {
37735             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
37736             return { raw: json || convertToObject(sourceFile, errors) };
37737         }
37738         var ownConfig = json ?
37739             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
37740             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
37741         if ((_a = ownConfig.options) === null || _a === void 0 ? void 0 : _a.paths) {
37742             // If we end up needing to resolve relative paths from 'paths' relative to
37743             // the config file location, we'll need to know where that config file was.
37744             // Since 'paths' can be inherited from an extended config in another directory,
37745             // we wouldn't know which directory to use unless we store it here.
37746             ownConfig.options.pathsBasePath = basePath;
37747         }
37748         if (ownConfig.extendedConfigPath) {
37749             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
37750             resolutionStack = resolutionStack.concat([resolvedPath]);
37751             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
37752             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
37753                 var baseRaw_1 = extendedConfig.raw;
37754                 var raw_1 = ownConfig.raw;
37755                 var setPropertyInRawIfNotUndefined = function (propertyName) {
37756                     var value = raw_1[propertyName] || baseRaw_1[propertyName];
37757                     if (value) {
37758                         raw_1[propertyName] = value;
37759                     }
37760                 };
37761                 setPropertyInRawIfNotUndefined("include");
37762                 setPropertyInRawIfNotUndefined("exclude");
37763                 setPropertyInRawIfNotUndefined("files");
37764                 if (raw_1.compileOnSave === undefined) {
37765                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
37766                 }
37767                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
37768                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
37769                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
37770                     ownConfig.watchOptions || extendedConfig.watchOptions;
37771                 // TODO extend type typeAcquisition
37772             }
37773         }
37774         return ownConfig;
37775     }
37776     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
37777         if (ts.hasProperty(json, "excludes")) {
37778             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
37779         }
37780         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
37781         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
37782         // It should be removed in future releases - use typeAcquisition instead.
37783         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
37784         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
37785         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
37786         var extendedConfigPath;
37787         if (json.extends) {
37788             if (!ts.isString(json.extends)) {
37789                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
37790             }
37791             else {
37792                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
37793                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
37794             }
37795         }
37796         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
37797     }
37798     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
37799         var options = getDefaultCompilerOptions(configFileName);
37800         var typeAcquisition, typingOptionstypeAcquisition;
37801         var watchOptions;
37802         var extendedConfigPath;
37803         var optionsIterator = {
37804             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
37805                 var currentOption;
37806                 switch (parentOption) {
37807                     case "compilerOptions":
37808                         currentOption = options;
37809                         break;
37810                     case "watchOptions":
37811                         currentOption = (watchOptions || (watchOptions = {}));
37812                         break;
37813                     case "typeAcquisition":
37814                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
37815                         break;
37816                     case "typingOptions":
37817                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
37818                         break;
37819                     default:
37820                         ts.Debug.fail("Unknown option");
37821                 }
37822                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
37823             },
37824             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
37825                 switch (key) {
37826                     case "extends":
37827                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
37828                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
37829                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
37830                         });
37831                         return;
37832                 }
37833             },
37834             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
37835                 if (key === "excludes") {
37836                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
37837                 }
37838             }
37839         };
37840         var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
37841         if (!typeAcquisition) {
37842             if (typingOptionstypeAcquisition) {
37843                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
37844                     {
37845                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
37846                         include: typingOptionstypeAcquisition.include,
37847                         exclude: typingOptionstypeAcquisition.exclude
37848                     } :
37849                     typingOptionstypeAcquisition;
37850             }
37851             else {
37852                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
37853             }
37854         }
37855         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
37856     }
37857     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
37858         extendedConfig = ts.normalizeSlashes(extendedConfig);
37859         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
37860             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
37861             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
37862                 extendedConfigPath = extendedConfigPath + ".json";
37863                 if (!host.fileExists(extendedConfigPath)) {
37864                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
37865                     return undefined;
37866                 }
37867             }
37868             return extendedConfigPath;
37869         }
37870         // If the path isn't a rooted or relative path, resolve like a module
37871         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
37872         if (resolved.resolvedModule) {
37873             return resolved.resolvedModule.resolvedFileName;
37874         }
37875         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
37876         return undefined;
37877     }
37878     function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
37879         var _a;
37880         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
37881         var value;
37882         var extendedResult;
37883         var extendedConfig;
37884         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
37885             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
37886         }
37887         else {
37888             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
37889             if (!extendedResult.parseDiagnostics.length) {
37890                 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
37891                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
37892                 if (isSuccessfulParsedTsconfig(extendedConfig)) {
37893                     // Update the paths to reflect base path
37894                     var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
37895                     var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
37896                     var mapPropertiesInRawIfNotUndefined = function (propertyName) {
37897                         if (raw_2[propertyName]) {
37898                             raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
37899                         }
37900                     };
37901                     var raw_2 = extendedConfig.raw;
37902                     mapPropertiesInRawIfNotUndefined("include");
37903                     mapPropertiesInRawIfNotUndefined("exclude");
37904                     mapPropertiesInRawIfNotUndefined("files");
37905                 }
37906             }
37907             if (extendedConfigCache) {
37908                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
37909             }
37910         }
37911         if (sourceFile) {
37912             sourceFile.extendedSourceFiles = [extendedResult.fileName];
37913             if (extendedResult.extendedSourceFiles) {
37914                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
37915             }
37916         }
37917         if (extendedResult.parseDiagnostics.length) {
37918             errors.push.apply(errors, extendedResult.parseDiagnostics);
37919             return undefined;
37920         }
37921         return extendedConfig;
37922     }
37923     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
37924         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
37925             return false;
37926         }
37927         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
37928         return typeof result === "boolean" && result;
37929     }
37930     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
37931         var errors = [];
37932         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
37933         return { options: options, errors: errors };
37934     }
37935     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
37936     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
37937         var errors = [];
37938         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
37939         return { options: options, errors: errors };
37940     }
37941     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
37942     function getDefaultCompilerOptions(configFileName) {
37943         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
37944             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
37945             : {};
37946         return options;
37947     }
37948     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
37949         var options = getDefaultCompilerOptions(configFileName);
37950         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
37951         if (configFileName) {
37952             options.configFilePath = ts.normalizeSlashes(configFileName);
37953         }
37954         return options;
37955     }
37956     function getDefaultTypeAcquisition(configFileName) {
37957         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
37958     }
37959     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
37960         var options = getDefaultTypeAcquisition(configFileName);
37961         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
37962         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
37963         return options;
37964     }
37965     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
37966         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
37967     }
37968     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
37969         if (!jsonOptions) {
37970             return;
37971         }
37972         for (var id in jsonOptions) {
37973             var opt = optionsNameMap.get(id);
37974             if (opt) {
37975                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
37976             }
37977             else {
37978                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
37979             }
37980         }
37981         return defaultOptions;
37982     }
37983     function convertJsonOption(opt, value, basePath, errors) {
37984         if (isCompilerOptionsValue(opt, value)) {
37985             var optType = opt.type;
37986             if (optType === "list" && ts.isArray(value)) {
37987                 return convertJsonOptionOfListType(opt, value, basePath, errors);
37988             }
37989             else if (!ts.isString(optType)) {
37990                 return convertJsonOptionOfCustomType(opt, value, errors);
37991             }
37992             return normalizeNonListOptionValue(opt, basePath, value);
37993         }
37994         else {
37995             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
37996         }
37997     }
37998     function normalizeOptionValue(option, basePath, value) {
37999         if (isNullOrUndefined(value))
38000             return undefined;
38001         if (option.type === "list") {
38002             var listOption_1 = option;
38003             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
38004                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
38005             }
38006             return value;
38007         }
38008         else if (!ts.isString(option.type)) {
38009             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
38010         }
38011         return normalizeNonListOptionValue(option, basePath, value);
38012     }
38013     function normalizeNonListOptionValue(option, basePath, value) {
38014         if (option.isFilePath) {
38015             value = ts.getNormalizedAbsolutePath(value, basePath);
38016             if (value === "") {
38017                 value = ".";
38018             }
38019         }
38020         return value;
38021     }
38022     function convertJsonOptionOfCustomType(opt, value, errors) {
38023         if (isNullOrUndefined(value))
38024             return undefined;
38025         var key = value.toLowerCase();
38026         var val = opt.type.get(key);
38027         if (val !== undefined) {
38028             return val;
38029         }
38030         else {
38031             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
38032         }
38033     }
38034     function convertJsonOptionOfListType(option, values, basePath, errors) {
38035         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
38036     }
38037     function trimString(s) {
38038         return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
38039     }
38040     /**
38041      * Tests for a path that ends in a recursive directory wildcard.
38042      * Matches **, \**, **\, and \**\, but not a**b.
38043      *
38044      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38045      *
38046      * Breakdown:
38047      *  (^|\/)      # matches either the beginning of the string or a directory separator.
38048      *  \*\*        # matches the recursive directory wildcard "**".
38049      *  \/?$        # matches an optional trailing directory separator at the end of the string.
38050      */
38051     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
38052     /**
38053      * Tests for a path where .. appears after a recursive directory wildcard.
38054      * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
38055      *
38056      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38057      *
38058      * Breakdown:
38059      *  (^|\/)      # matches either the beginning of the string or a directory separator.
38060      *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
38061      *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
38062      *  \.\.        # matches a parent directory path component ".."
38063      *  ($|\/)      # matches either the end of the string or a directory separator.
38064      */
38065     var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
38066     /**
38067      * Tests for a path containing a wildcard character in a directory component of the path.
38068      * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
38069      *
38070      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38071      *
38072      * Breakdown:
38073      *  \/          # matches a directory separator.
38074      *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
38075      *  [*?]        # matches either a wildcard character (* or ?)
38076      *  [^/]*       # matches any number of characters excluding directory separators (greedy).
38077      *  \/          # matches a directory separator.
38078      */
38079     var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
38080     /**
38081      * Matches the portion of a wildcard path that does not contain wildcards.
38082      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
38083      *
38084      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38085      *
38086      * Breakdown:
38087      *  ^                   # matches the beginning of the string
38088      *  [^*?]*              # matches any number of non-wildcard characters
38089      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
38090      *                      # a path component that contains at least one wildcard character (* or ?).
38091      */
38092     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
38093     /**
38094      * Expands an array of file specifications.
38095      *
38096      * @param filesSpecs The literal file names to include.
38097      * @param includeSpecs The wildcard file specifications to include.
38098      * @param excludeSpecs The wildcard file specifications to exclude.
38099      * @param basePath The base path for any relative file specifications.
38100      * @param options Compiler options.
38101      * @param host The host used to resolve files and directories.
38102      * @param errors An array for diagnostic reporting.
38103      */
38104     function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
38105         basePath = ts.normalizePath(basePath);
38106         var validatedIncludeSpecs, validatedExcludeSpecs;
38107         // The exclude spec list is converted into a regular expression, which allows us to quickly
38108         // test whether a file or directory should be excluded before recursively traversing the
38109         // file system.
38110         if (includeSpecs) {
38111             validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
38112         }
38113         if (excludeSpecs) {
38114             validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
38115         }
38116         // Wildcard directories (provided as part of a wildcard path) are stored in a
38117         // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
38118         // or a recursive directory. This information is used by filesystem watchers to monitor for
38119         // new entries in these paths.
38120         var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
38121         var spec = {
38122             filesSpecs: filesSpecs,
38123             includeSpecs: includeSpecs,
38124             excludeSpecs: excludeSpecs,
38125             validatedFilesSpec: ts.filter(filesSpecs, ts.isString),
38126             validatedIncludeSpecs: validatedIncludeSpecs,
38127             validatedExcludeSpecs: validatedExcludeSpecs,
38128             wildcardDirectories: wildcardDirectories
38129         };
38130         return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
38131     }
38132     /**
38133      * Gets the file names from the provided config file specs that contain, files, include, exclude and
38134      * other properties needed to resolve the file names
38135      * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
38136      * @param basePath The base path for any relative file specifications.
38137      * @param options Compiler options.
38138      * @param host The host used to resolve files and directories.
38139      * @param extraFileExtensions optionaly file extra file extension information from host
38140      */
38141     /* @internal */
38142     function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
38143         if (extraFileExtensions === void 0) { extraFileExtensions = ts.emptyArray; }
38144         basePath = ts.normalizePath(basePath);
38145         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
38146         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
38147         // file map with a possibly case insensitive key. We use this map later when when including
38148         // wildcard paths.
38149         var literalFileMap = new ts.Map();
38150         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
38151         // file map with a possibly case insensitive key. We use this map to store paths matched
38152         // via wildcard, and to handle extension priority.
38153         var wildcardFileMap = new ts.Map();
38154         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
38155         // file map with a possibly case insensitive key. We use this map to store paths matched
38156         // via wildcard of *.json kind
38157         var wildCardJsonFileMap = new ts.Map();
38158         var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
38159         // Rather than requery this for each file and filespec, we query the supported extensions
38160         // once and store it on the expansion context.
38161         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
38162         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
38163         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
38164         // remove a literal file.
38165         if (validatedFilesSpec) {
38166             for (var _i = 0, validatedFilesSpec_1 = validatedFilesSpec; _i < validatedFilesSpec_1.length; _i++) {
38167                 var fileName = validatedFilesSpec_1[_i];
38168                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
38169                 literalFileMap.set(keyMapper(file), file);
38170             }
38171         }
38172         var jsonOnlyIncludeRegexes;
38173         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
38174             var _loop_6 = function (file) {
38175                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
38176                     // Valid only if *.json specified
38177                     if (!jsonOnlyIncludeRegexes) {
38178                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
38179                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
38180                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
38181                     }
38182                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
38183                     if (includeIndex !== -1) {
38184                         var key_1 = keyMapper(file);
38185                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
38186                             wildCardJsonFileMap.set(key_1, file);
38187                         }
38188                     }
38189                     return "continue";
38190                 }
38191                 // If we have already included a literal or wildcard path with a
38192                 // higher priority extension, we should skip this file.
38193                 //
38194                 // This handles cases where we may encounter both <file>.ts and
38195                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
38196                 // directory when they are compilation outputs.
38197                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
38198                     return "continue";
38199                 }
38200                 // We may have included a wildcard path with a lower priority
38201                 // extension due to the user-defined order of entries in the
38202                 // "include" array. If there is a lower priority extension in the
38203                 // same directory, we should remove it.
38204                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
38205                 var key = keyMapper(file);
38206                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
38207                     wildcardFileMap.set(key, file);
38208                 }
38209             };
38210             for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
38211                 var file = _b[_a];
38212                 _loop_6(file);
38213             }
38214         }
38215         var literalFiles = ts.arrayFrom(literalFileMap.values());
38216         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
38217         return {
38218             fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
38219             wildcardDirectories: wildcardDirectories,
38220             spec: spec
38221         };
38222     }
38223     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
38224     /* @internal */
38225     function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) {
38226         var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs;
38227         if (!ts.length(validatedIncludeSpecs) || !ts.length(validatedExcludeSpecs))
38228             return false;
38229         basePath = ts.normalizePath(basePath);
38230         var keyMapper = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
38231         if (validatedFilesSpec) {
38232             for (var _i = 0, validatedFilesSpec_2 = validatedFilesSpec; _i < validatedFilesSpec_2.length; _i++) {
38233                 var fileName = validatedFilesSpec_2[_i];
38234                 if (keyMapper(ts.getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck)
38235                     return false;
38236             }
38237         }
38238         var excludePattern = ts.getRegularExpressionForWildcard(validatedExcludeSpecs, ts.combinePaths(ts.normalizePath(currentDirectory), basePath), "exclude");
38239         var excludeRegex = excludePattern && ts.getRegexFromPattern(excludePattern, useCaseSensitiveFileNames);
38240         if (!excludeRegex)
38241             return false;
38242         if (excludeRegex.test(pathToCheck))
38243             return true;
38244         return !ts.hasExtension(pathToCheck) && excludeRegex.test(ts.ensureTrailingDirectorySeparator(pathToCheck));
38245     }
38246     ts.isExcludedFile = isExcludedFile;
38247     function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
38248         return specs.filter(function (spec) {
38249             if (!ts.isString(spec))
38250                 return false;
38251             var diag = specToDiagnostic(spec, allowTrailingRecursion);
38252             if (diag !== undefined) {
38253                 errors.push(createDiagnostic(diag, spec));
38254             }
38255             return diag === undefined;
38256         });
38257         function createDiagnostic(message, spec) {
38258             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
38259             return element ?
38260                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
38261                 ts.createCompilerDiagnostic(message, spec);
38262         }
38263     }
38264     function specToDiagnostic(spec, allowTrailingRecursion) {
38265         if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
38266             return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
38267         }
38268         else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
38269             return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
38270         }
38271     }
38272     /**
38273      * Gets directories in a set of include patterns that should be watched for changes.
38274      */
38275     function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
38276         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
38277         // of the pattern:
38278         //
38279         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
38280         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
38281         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
38282         //
38283         // We watch a directory without recursion if it contains a wildcard in the file segment of
38284         // the pattern:
38285         //
38286         //  /a/b/*      - Watch /a/b directly to catch any new file
38287         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
38288         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
38289         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
38290         var wildcardDirectories = {};
38291         if (include !== undefined) {
38292             var recursiveKeys = [];
38293             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
38294                 var file = include_1[_i];
38295                 var spec = ts.normalizePath(ts.combinePaths(path, file));
38296                 if (excludeRegex && excludeRegex.test(spec)) {
38297                     continue;
38298                 }
38299                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
38300                 if (match) {
38301                     var key = match.key, flags = match.flags;
38302                     var existingFlags = wildcardDirectories[key];
38303                     if (existingFlags === undefined || existingFlags < flags) {
38304                         wildcardDirectories[key] = flags;
38305                         if (flags === 1 /* Recursive */) {
38306                             recursiveKeys.push(key);
38307                         }
38308                     }
38309                 }
38310             }
38311             // Remove any subpaths under an existing recursively watched directory.
38312             for (var key in wildcardDirectories) {
38313                 if (ts.hasProperty(wildcardDirectories, key)) {
38314                     for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
38315                         var recursiveKey = recursiveKeys_1[_a];
38316                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
38317                             delete wildcardDirectories[key];
38318                         }
38319                     }
38320                 }
38321             }
38322         }
38323         return wildcardDirectories;
38324     }
38325     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
38326         var match = wildcardDirectoryPattern.exec(spec);
38327         if (match) {
38328             return {
38329                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
38330                 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
38331             };
38332         }
38333         if (ts.isImplicitGlob(spec)) {
38334             return {
38335                 key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec),
38336                 flags: 1 /* Recursive */
38337             };
38338         }
38339         return undefined;
38340     }
38341     /**
38342      * Determines whether a literal or wildcard file has already been included that has a higher
38343      * extension priority.
38344      *
38345      * @param file The path to the file.
38346      * @param extensionPriority The priority of the extension.
38347      * @param context The expansion context.
38348      */
38349     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
38350         var extensionPriority = ts.getExtensionPriority(file, extensions);
38351         var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
38352         for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
38353             var higherPriorityExtension = extensions[i];
38354             var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
38355             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
38356                 return true;
38357             }
38358         }
38359         return false;
38360     }
38361     /**
38362      * Removes files included via wildcard expansion with a lower extension priority that have
38363      * already been included.
38364      *
38365      * @param file The path to the file.
38366      * @param extensionPriority The priority of the extension.
38367      * @param context The expansion context.
38368      */
38369     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
38370         var extensionPriority = ts.getExtensionPriority(file, extensions);
38371         var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
38372         for (var i = nextExtensionPriority; i < extensions.length; i++) {
38373             var lowerPriorityExtension = extensions[i];
38374             var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
38375             wildcardFiles.delete(lowerPriorityPath);
38376         }
38377     }
38378     /**
38379      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
38380      * Also converts enum values back to strings.
38381      */
38382     /* @internal */
38383     function convertCompilerOptionsForTelemetry(opts) {
38384         var out = {};
38385         for (var key in opts) {
38386             if (opts.hasOwnProperty(key)) {
38387                 var type = getOptionFromName(key);
38388                 if (type !== undefined) { // Ignore unknown options
38389                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
38390                 }
38391             }
38392         }
38393         return out;
38394     }
38395     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
38396     function getOptionValueWithEmptyStrings(value, option) {
38397         switch (option.type) {
38398             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
38399                 return "";
38400             case "string": // Could be any arbitrary string -- use empty string instead.
38401                 return "";
38402             case "number": // Allow numbers, but be sure to check it's actually a number.
38403                 return typeof value === "number" ? value : "";
38404             case "boolean":
38405                 return typeof value === "boolean" ? value : "";
38406             case "list":
38407                 var elementType_1 = option.element;
38408                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
38409             default:
38410                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
38411                     if (optionEnumValue === value) {
38412                         return optionStringValue;
38413                     }
38414                 }); // TODO: GH#18217
38415         }
38416     }
38417 })(ts || (ts = {}));
38418 var ts;
38419 (function (ts) {
38420     function trace(host) {
38421         host.trace(ts.formatMessage.apply(undefined, arguments));
38422     }
38423     ts.trace = trace;
38424     /* @internal */
38425     function isTraceEnabled(compilerOptions, host) {
38426         return !!compilerOptions.traceResolution && host.trace !== undefined;
38427     }
38428     ts.isTraceEnabled = isTraceEnabled;
38429     function withPackageId(packageInfo, r) {
38430         var packageId;
38431         if (r && packageInfo) {
38432             var packageJsonContent = packageInfo.packageJsonContent;
38433             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
38434                 packageId = {
38435                     name: packageJsonContent.name,
38436                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
38437                     version: packageJsonContent.version
38438                 };
38439             }
38440         }
38441         return r && { path: r.path, extension: r.ext, packageId: packageId };
38442     }
38443     function noPackageId(r) {
38444         return withPackageId(/*packageInfo*/ undefined, r);
38445     }
38446     function removeIgnoredPackageId(r) {
38447         if (r) {
38448             ts.Debug.assert(r.packageId === undefined);
38449             return { path: r.path, ext: r.extension };
38450         }
38451     }
38452     /**
38453      * Kinds of file that we are currently looking for.
38454      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
38455      */
38456     var Extensions;
38457     (function (Extensions) {
38458         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
38459         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
38460         Extensions[Extensions["Json"] = 2] = "Json";
38461         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
38462         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
38463     })(Extensions || (Extensions = {}));
38464     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
38465     function resolvedTypeScriptOnly(resolved) {
38466         if (!resolved) {
38467             return undefined;
38468         }
38469         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
38470         return { fileName: resolved.path, packageId: resolved.packageId };
38471     }
38472     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
38473         var _a;
38474         if (resultFromCache) {
38475             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
38476             return resultFromCache;
38477         }
38478         return {
38479             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
38480             failedLookupLocations: failedLookupLocations
38481         };
38482     }
38483     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
38484         if (!ts.hasProperty(jsonContent, fieldName)) {
38485             if (state.traceEnabled) {
38486                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
38487             }
38488             return;
38489         }
38490         var value = jsonContent[fieldName];
38491         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
38492             if (state.traceEnabled) {
38493                 // eslint-disable-next-line no-null/no-null
38494                 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);
38495             }
38496             return;
38497         }
38498         return value;
38499     }
38500     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
38501         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
38502         if (fileName === undefined) {
38503             return;
38504         }
38505         if (!fileName) {
38506             if (state.traceEnabled) {
38507                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
38508             }
38509             return;
38510         }
38511         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
38512         if (state.traceEnabled) {
38513             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
38514         }
38515         return path;
38516     }
38517     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
38518         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
38519             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
38520     }
38521     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
38522         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
38523     }
38524     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
38525         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
38526     }
38527     function readPackageJsonTypesVersionsField(jsonContent, state) {
38528         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
38529         if (typesVersions === undefined)
38530             return;
38531         if (state.traceEnabled) {
38532             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
38533         }
38534         return typesVersions;
38535     }
38536     function readPackageJsonTypesVersionPaths(jsonContent, state) {
38537         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
38538         if (typesVersions === undefined)
38539             return;
38540         if (state.traceEnabled) {
38541             for (var key in typesVersions) {
38542                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
38543                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
38544                 }
38545             }
38546         }
38547         var result = getPackageJsonTypesVersionsPaths(typesVersions);
38548         if (!result) {
38549             if (state.traceEnabled) {
38550                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
38551             }
38552             return;
38553         }
38554         var bestVersionKey = result.version, bestVersionPaths = result.paths;
38555         if (typeof bestVersionPaths !== "object") {
38556             if (state.traceEnabled) {
38557                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
38558             }
38559             return;
38560         }
38561         return result;
38562     }
38563     var typeScriptVersion;
38564     /* @internal */
38565     function getPackageJsonTypesVersionsPaths(typesVersions) {
38566         if (!typeScriptVersion)
38567             typeScriptVersion = new ts.Version(ts.version);
38568         for (var key in typesVersions) {
38569             if (!ts.hasProperty(typesVersions, key))
38570                 continue;
38571             var keyRange = ts.VersionRange.tryParse(key);
38572             if (keyRange === undefined) {
38573                 continue;
38574             }
38575             // return the first entry whose range matches the current compiler version.
38576             if (keyRange.test(typeScriptVersion)) {
38577                 return { version: key, paths: typesVersions[key] };
38578             }
38579         }
38580     }
38581     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
38582     function getEffectiveTypeRoots(options, host) {
38583         if (options.typeRoots) {
38584             return options.typeRoots;
38585         }
38586         var currentDirectory;
38587         if (options.configFilePath) {
38588             currentDirectory = ts.getDirectoryPath(options.configFilePath);
38589         }
38590         else if (host.getCurrentDirectory) {
38591             currentDirectory = host.getCurrentDirectory();
38592         }
38593         if (currentDirectory !== undefined) {
38594             return getDefaultTypeRoots(currentDirectory, host);
38595         }
38596     }
38597     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
38598     /**
38599      * Returns the path to every node_modules/@types directory from some ancestor directory.
38600      * Returns undefined if there are none.
38601      */
38602     function getDefaultTypeRoots(currentDirectory, host) {
38603         if (!host.directoryExists) {
38604             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
38605             // And if it doesn't exist, tough.
38606         }
38607         var typeRoots;
38608         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
38609             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
38610             if (host.directoryExists(atTypes)) {
38611                 (typeRoots || (typeRoots = [])).push(atTypes);
38612             }
38613             return undefined;
38614         });
38615         return typeRoots;
38616     }
38617     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
38618     /**
38619      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
38620      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
38621      * is assumed to be the same as root directory of the project.
38622      */
38623     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
38624         var traceEnabled = isTraceEnabled(options, host);
38625         if (redirectedReference) {
38626             options = redirectedReference.commandLine.options;
38627         }
38628         var failedLookupLocations = [];
38629         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
38630         var typeRoots = getEffectiveTypeRoots(options, host);
38631         if (traceEnabled) {
38632             if (containingFile === undefined) {
38633                 if (typeRoots === undefined) {
38634                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
38635                 }
38636                 else {
38637                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
38638                 }
38639             }
38640             else {
38641                 if (typeRoots === undefined) {
38642                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
38643                 }
38644                 else {
38645                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
38646                 }
38647             }
38648             if (redirectedReference) {
38649                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
38650             }
38651         }
38652         var resolved = primaryLookup();
38653         var primary = true;
38654         if (!resolved) {
38655             resolved = secondaryLookup();
38656             primary = false;
38657         }
38658         var resolvedTypeReferenceDirective;
38659         if (resolved) {
38660             var fileName = resolved.fileName, packageId = resolved.packageId;
38661             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
38662             if (traceEnabled) {
38663                 if (packageId) {
38664                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary);
38665                 }
38666                 else {
38667                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
38668                 }
38669             }
38670             resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
38671         }
38672         return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
38673         function primaryLookup() {
38674             // Check primary library paths
38675             if (typeRoots && typeRoots.length) {
38676                 if (traceEnabled) {
38677                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
38678                 }
38679                 return ts.firstDefined(typeRoots, function (typeRoot) {
38680                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
38681                     var candidateDirectory = ts.getDirectoryPath(candidate);
38682                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
38683                     if (!directoryExists && traceEnabled) {
38684                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
38685                     }
38686                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
38687                 });
38688             }
38689             else {
38690                 if (traceEnabled) {
38691                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
38692                 }
38693             }
38694         }
38695         function secondaryLookup() {
38696             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
38697             if (initialLocationForSecondaryLookup !== undefined) {
38698                 // check secondary locations
38699                 if (traceEnabled) {
38700                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
38701                 }
38702                 var result = void 0;
38703                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
38704                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
38705                     result = searchResult && searchResult.value;
38706                 }
38707                 else {
38708                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
38709                     result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
38710                 }
38711                 var resolvedFile = resolvedTypeScriptOnly(result);
38712                 if (!resolvedFile && traceEnabled) {
38713                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
38714                 }
38715                 return resolvedFile;
38716             }
38717             else {
38718                 if (traceEnabled) {
38719                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
38720                 }
38721             }
38722         }
38723     }
38724     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
38725     /**
38726      * Given a set of options, returns the set of type directive names
38727      *   that should be included for this program automatically.
38728      * This list could either come from the config file,
38729      *   or from enumerating the types root + initial secondary types lookup location.
38730      * More type directives might appear in the program later as a result of loading actual source files;
38731      *   this list is only the set of defaults that are implicitly included.
38732      */
38733     function getAutomaticTypeDirectiveNames(options, host) {
38734         // Use explicit type list from tsconfig.json
38735         if (options.types) {
38736             return options.types;
38737         }
38738         // Walk the primary type lookup locations
38739         var result = [];
38740         if (host.directoryExists && host.getDirectories) {
38741             var typeRoots = getEffectiveTypeRoots(options, host);
38742             if (typeRoots) {
38743                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
38744                     var root = typeRoots_1[_i];
38745                     if (host.directoryExists(root)) {
38746                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
38747                             var typeDirectivePath = _b[_a];
38748                             var normalized = ts.normalizePath(typeDirectivePath);
38749                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
38750                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
38751                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
38752                             // eslint-disable-next-line no-null/no-null
38753                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
38754                             if (!isNotNeededPackage) {
38755                                 var baseFileName = ts.getBaseFileName(normalized);
38756                                 // At this stage, skip results with leading dot.
38757                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
38758                                     // Return just the type directive names
38759                                     result.push(baseFileName);
38760                                 }
38761                             }
38762                         }
38763                     }
38764                 }
38765             }
38766         }
38767         return result;
38768     }
38769     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
38770     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
38771         return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
38772     }
38773     ts.createModuleResolutionCache = createModuleResolutionCache;
38774     /*@internal*/
38775     function createCacheWithRedirects(options) {
38776         var ownMap = new ts.Map();
38777         var redirectsMap = new ts.Map();
38778         return {
38779             ownMap: ownMap,
38780             redirectsMap: redirectsMap,
38781             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
38782             clear: clear,
38783             setOwnOptions: setOwnOptions,
38784             setOwnMap: setOwnMap
38785         };
38786         function setOwnOptions(newOptions) {
38787             options = newOptions;
38788         }
38789         function setOwnMap(newOwnMap) {
38790             ownMap = newOwnMap;
38791         }
38792         function getOrCreateMapOfCacheRedirects(redirectedReference) {
38793             if (!redirectedReference) {
38794                 return ownMap;
38795             }
38796             var path = redirectedReference.sourceFile.path;
38797             var redirects = redirectsMap.get(path);
38798             if (!redirects) {
38799                 // Reuse map if redirected reference map uses same resolution
38800                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? new ts.Map() : ownMap;
38801                 redirectsMap.set(path, redirects);
38802             }
38803             return redirects;
38804         }
38805         function clear() {
38806             ownMap.clear();
38807             redirectsMap.clear();
38808         }
38809     }
38810     ts.createCacheWithRedirects = createCacheWithRedirects;
38811     /*@internal*/
38812     function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
38813         return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
38814         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
38815             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
38816             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); });
38817         }
38818         function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
38819             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
38820             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
38821         }
38822         function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
38823             var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
38824             var result = cache.get(key);
38825             if (!result) {
38826                 result = create();
38827                 cache.set(key, result);
38828             }
38829             return result;
38830         }
38831         function createPerModuleNameCache() {
38832             var directoryPathMap = new ts.Map();
38833             return { get: get, set: set };
38834             function get(directory) {
38835                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
38836             }
38837             /**
38838              * At first this function add entry directory -> module resolution result to the table.
38839              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
38840              * and for every parent folder in set it adds entry: parent -> module resolution. .
38841              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
38842              * Set of parent folders that should have the same result will be:
38843              * [
38844              *     /a/b/c/d, /a/b/c, /a/b
38845              * ]
38846              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
38847              */
38848             function set(directory, result) {
38849                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
38850                 // if entry is already in cache do nothing
38851                 if (directoryPathMap.has(path)) {
38852                     return;
38853                 }
38854                 directoryPathMap.set(path, result);
38855                 var resolvedFileName = result.resolvedModule &&
38856                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
38857                 // find common prefix between directory and resolved file name
38858                 // this common prefix should be the shortest path that has the same resolution
38859                 // directory: /a/b/c/d/e
38860                 // resolvedFileName: /a/b/foo.d.ts
38861                 // commonPrefix: /a/b
38862                 // for failed lookups cache the result for every directory up to root
38863                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
38864                 var current = path;
38865                 while (current !== commonPrefix) {
38866                     var parent = ts.getDirectoryPath(current);
38867                     if (parent === current || directoryPathMap.has(parent)) {
38868                         break;
38869                     }
38870                     directoryPathMap.set(parent, result);
38871                     current = parent;
38872                 }
38873             }
38874             function getCommonPrefix(directory, resolution) {
38875                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
38876                 // find first position where directory and resolution differs
38877                 var i = 0;
38878                 var limit = Math.min(directory.length, resolutionDirectory.length);
38879                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
38880                     i++;
38881                 }
38882                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
38883                     return directory;
38884                 }
38885                 var rootLength = ts.getRootLength(directory);
38886                 if (i < rootLength) {
38887                     return undefined;
38888                 }
38889                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
38890                 if (sep === -1) {
38891                     return undefined;
38892                 }
38893                 return directory.substr(0, Math.max(sep, rootLength));
38894             }
38895         }
38896     }
38897     ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
38898     function resolveModuleNameFromCache(moduleName, containingFile, cache) {
38899         var containingDirectory = ts.getDirectoryPath(containingFile);
38900         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
38901         return perFolderCache && perFolderCache.get(moduleName);
38902     }
38903     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
38904     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
38905         var traceEnabled = isTraceEnabled(compilerOptions, host);
38906         if (redirectedReference) {
38907             compilerOptions = redirectedReference.commandLine.options;
38908         }
38909         if (traceEnabled) {
38910             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
38911             if (redirectedReference) {
38912                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
38913             }
38914         }
38915         var containingDirectory = ts.getDirectoryPath(containingFile);
38916         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
38917         var result = perFolderCache && perFolderCache.get(moduleName);
38918         if (result) {
38919             if (traceEnabled) {
38920                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
38921             }
38922         }
38923         else {
38924             var moduleResolution = compilerOptions.moduleResolution;
38925             if (moduleResolution === undefined) {
38926                 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
38927                 if (traceEnabled) {
38928                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
38929                 }
38930             }
38931             else {
38932                 if (traceEnabled) {
38933                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
38934                 }
38935             }
38936             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
38937             switch (moduleResolution) {
38938                 case ts.ModuleResolutionKind.NodeJs:
38939                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
38940                     break;
38941                 case ts.ModuleResolutionKind.Classic:
38942                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
38943                     break;
38944                 default:
38945                     return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
38946             }
38947             if (result && result.resolvedModule)
38948                 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
38949             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
38950             if (perFolderCache) {
38951                 perFolderCache.set(moduleName, result);
38952                 if (!ts.isExternalModuleNameRelative(moduleName)) {
38953                     // put result in per-module name cache
38954                     cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
38955                 }
38956             }
38957         }
38958         if (traceEnabled) {
38959             if (result.resolvedModule) {
38960                 if (result.resolvedModule.packageId) {
38961                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, ts.packageIdToString(result.resolvedModule.packageId));
38962                 }
38963                 else {
38964                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
38965                 }
38966             }
38967             else {
38968                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
38969             }
38970         }
38971         return result;
38972     }
38973     ts.resolveModuleName = resolveModuleName;
38974     /**
38975      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
38976      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
38977      * can be resolved successfully by TypeScript compiler and runtime module loader.
38978      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
38979      * fallback to standard resolution routine.
38980      *
38981      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
38982      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
38983      * be '/a/b/c/d'
38984      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
38985      * will be resolved based on the content of the module name.
38986      * Structure of 'paths' compiler options
38987      * 'paths': {
38988      *    pattern-1: [...substitutions],
38989      *    pattern-2: [...substitutions],
38990      *    ...
38991      *    pattern-n: [...substitutions]
38992      * }
38993      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
38994      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
38995      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
38996      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
38997      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
38998      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
38999      * from the candidate location.
39000      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
39001      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
39002      * will be converted to absolute using baseUrl.
39003      * For example:
39004      * baseUrl: /a/b/c
39005      * "paths": {
39006      *     // match all module names
39007      *     "*": [
39008      *         "*",        // use matched name as is,
39009      *                     // <matched name> will be looked as /a/b/c/<matched name>
39010      *
39011      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
39012      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
39013      *     ],
39014      *     // match module names that start with 'components/'
39015      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
39016      *                                              // it is rooted so it will be final candidate location
39017      * }
39018      *
39019      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
39020      * they were in the same location. For example lets say there are two files
39021      * '/local/src/content/file1.ts'
39022      * '/shared/components/contracts/src/content/protocols/file2.ts'
39023      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
39024      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
39025      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
39026      * root dirs were merged together.
39027      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
39028      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
39029      * '/local/src/content/protocols/file2' and try to load it - failure.
39030      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
39031      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
39032      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
39033      */
39034     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
39035         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
39036         if (resolved)
39037             return resolved.value;
39038         if (!ts.isExternalModuleNameRelative(moduleName)) {
39039             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
39040         }
39041         else {
39042             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
39043         }
39044     }
39045     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
39046         var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
39047         if (paths && !ts.pathIsRelative(moduleName)) {
39048             if (state.traceEnabled) {
39049                 if (baseUrl) {
39050                     trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
39051                 }
39052                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
39053             }
39054             var baseDirectory = ts.getPathsBasePath(state.compilerOptions, state.host); // Always defined when 'paths' is defined
39055             return tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, /*onlyRecordFailures*/ false, state);
39056         }
39057     }
39058     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
39059         if (!state.compilerOptions.rootDirs) {
39060             return undefined;
39061         }
39062         if (state.traceEnabled) {
39063             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
39064         }
39065         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
39066         var matchedRootDir;
39067         var matchedNormalizedPrefix;
39068         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
39069             var rootDir = _a[_i];
39070             // rootDirs are expected to be absolute
39071             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
39072             // using location of tsconfig.json as base location
39073             var normalizedRoot = ts.normalizePath(rootDir);
39074             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
39075                 normalizedRoot += ts.directorySeparator;
39076             }
39077             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
39078                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
39079             if (state.traceEnabled) {
39080                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
39081             }
39082             if (isLongestMatchingPrefix) {
39083                 matchedNormalizedPrefix = normalizedRoot;
39084                 matchedRootDir = rootDir;
39085             }
39086         }
39087         if (matchedNormalizedPrefix) {
39088             if (state.traceEnabled) {
39089                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
39090             }
39091             var suffix = candidate.substr(matchedNormalizedPrefix.length);
39092             // first - try to load from a initial location
39093             if (state.traceEnabled) {
39094                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
39095             }
39096             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
39097             if (resolvedFileName) {
39098                 return resolvedFileName;
39099             }
39100             if (state.traceEnabled) {
39101                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
39102             }
39103             // then try to resolve using remaining entries in rootDirs
39104             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
39105                 var rootDir = _c[_b];
39106                 if (rootDir === matchedRootDir) {
39107                     // skip the initially matched entry
39108                     continue;
39109                 }
39110                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
39111                 if (state.traceEnabled) {
39112                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
39113                 }
39114                 var baseDirectory = ts.getDirectoryPath(candidate_1);
39115                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
39116                 if (resolvedFileName_1) {
39117                     return resolvedFileName_1;
39118                 }
39119             }
39120             if (state.traceEnabled) {
39121                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
39122             }
39123         }
39124         return undefined;
39125     }
39126     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
39127         var baseUrl = state.compilerOptions.baseUrl;
39128         if (!baseUrl) {
39129             return undefined;
39130         }
39131         if (state.traceEnabled) {
39132             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
39133         }
39134         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
39135         if (state.traceEnabled) {
39136             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
39137         }
39138         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
39139     }
39140     /**
39141      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
39142      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
39143      * Throws an error if the module can't be resolved.
39144      */
39145     /* @internal */
39146     function resolveJSModule(moduleName, initialDir, host) {
39147         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
39148         if (!resolvedModule) {
39149             throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
39150         }
39151         return resolvedModule.resolvedFileName;
39152     }
39153     ts.resolveJSModule = resolveJSModule;
39154     /* @internal */
39155     function tryResolveJSModule(moduleName, initialDir, host) {
39156         var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
39157         return resolvedModule && resolvedModule.resolvedFileName;
39158     }
39159     ts.tryResolveJSModule = tryResolveJSModule;
39160     var jsOnlyExtensions = [Extensions.JavaScript];
39161     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
39162     var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
39163     var tsconfigExtensions = [Extensions.TSConfig];
39164     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
39165         return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
39166     }
39167     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
39168         return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
39169     }
39170     ts.nodeModuleNameResolver = nodeModuleNameResolver;
39171     function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
39172         var _a, _b;
39173         var traceEnabled = isTraceEnabled(compilerOptions, host);
39174         var failedLookupLocations = [];
39175         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
39176         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
39177         return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache);
39178         function tryResolve(extensions) {
39179             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
39180             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
39181             if (resolved) {
39182                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
39183             }
39184             if (!ts.isExternalModuleNameRelative(moduleName)) {
39185                 if (traceEnabled) {
39186                     trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
39187                 }
39188                 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
39189                 if (!resolved_1)
39190                     return undefined;
39191                 var resolvedValue = resolved_1.value;
39192                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
39193                     var path = realPath(resolvedValue.path, host, traceEnabled);
39194                     var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
39195                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
39196                 }
39197                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
39198                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
39199             }
39200             else {
39201                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
39202                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
39203                 // Treat explicit "node_modules" import as an external library import.
39204                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
39205             }
39206         }
39207     }
39208     function realPath(path, host, traceEnabled) {
39209         if (!host.realpath) {
39210             return path;
39211         }
39212         var real = ts.normalizePath(host.realpath(path));
39213         if (traceEnabled) {
39214             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
39215         }
39216         ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
39217         return real;
39218     }
39219     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
39220         if (state.traceEnabled) {
39221             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
39222         }
39223         if (!ts.hasTrailingDirectorySeparator(candidate)) {
39224             if (!onlyRecordFailures) {
39225                 var parentOfCandidate = ts.getDirectoryPath(candidate);
39226                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
39227                     if (state.traceEnabled) {
39228                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
39229                     }
39230                     onlyRecordFailures = true;
39231                 }
39232             }
39233             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
39234             if (resolvedFromFile) {
39235                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
39236                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
39237                 return withPackageId(packageInfo, resolvedFromFile);
39238             }
39239         }
39240         if (!onlyRecordFailures) {
39241             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
39242             if (!candidateExists) {
39243                 if (state.traceEnabled) {
39244                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
39245                 }
39246                 onlyRecordFailures = true;
39247             }
39248         }
39249         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
39250     }
39251     /*@internal*/
39252     ts.nodeModulesPathPart = "/node_modules/";
39253     /*@internal*/
39254     function pathContainsNodeModules(path) {
39255         return ts.stringContains(path, ts.nodeModulesPathPart);
39256     }
39257     ts.pathContainsNodeModules = pathContainsNodeModules;
39258     /**
39259      * This will be called on the successfully resolved path from `loadModuleFromFile`.
39260      * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
39261      *
39262      * packageDirectory is the directory of the package itself.
39263      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
39264      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
39265      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
39266      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
39267      */
39268     function parseNodeModuleFromPath(resolved) {
39269         var path = ts.normalizePath(resolved.path);
39270         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
39271         if (idx === -1) {
39272             return undefined;
39273         }
39274         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
39275         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
39276         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
39277             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
39278         }
39279         return path.slice(0, indexAfterPackageName);
39280     }
39281     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
39282         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
39283         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
39284     }
39285     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
39286         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
39287     }
39288     /**
39289      * @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
39290      * 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.
39291      */
39292     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
39293         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
39294             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
39295             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
39296         }
39297         // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
39298         var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
39299         if (resolvedByAddingExtension) {
39300             return resolvedByAddingExtension;
39301         }
39302         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
39303         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
39304         if (ts.hasJSFileExtension(candidate)) {
39305             var extensionless = ts.removeFileExtension(candidate);
39306             if (state.traceEnabled) {
39307                 var extension = candidate.substring(extensionless.length);
39308                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
39309             }
39310             return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
39311         }
39312     }
39313     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
39314     function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
39315         if (!onlyRecordFailures) {
39316             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
39317             var directory = ts.getDirectoryPath(candidate);
39318             if (directory) {
39319                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
39320             }
39321         }
39322         switch (extensions) {
39323             case Extensions.DtsOnly:
39324                 return tryExtension(".d.ts" /* Dts */);
39325             case Extensions.TypeScript:
39326                 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
39327             case Extensions.JavaScript:
39328                 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
39329             case Extensions.TSConfig:
39330             case Extensions.Json:
39331                 return tryExtension(".json" /* Json */);
39332         }
39333         function tryExtension(ext) {
39334             var path = tryFile(candidate + ext, onlyRecordFailures, state);
39335             return path === undefined ? undefined : { path: path, ext: ext };
39336         }
39337     }
39338     /** Return the file if it exists. */
39339     function tryFile(fileName, onlyRecordFailures, state) {
39340         if (!onlyRecordFailures) {
39341             if (state.host.fileExists(fileName)) {
39342                 if (state.traceEnabled) {
39343                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
39344                 }
39345                 return fileName;
39346             }
39347             else {
39348                 if (state.traceEnabled) {
39349                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
39350                 }
39351             }
39352         }
39353         state.failedLookupLocations.push(fileName);
39354         return undefined;
39355     }
39356     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
39357         if (considerPackageJson === void 0) { considerPackageJson = true; }
39358         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
39359         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
39360         var versionPaths = packageInfo && packageInfo.versionPaths;
39361         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
39362     }
39363     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
39364         var host = state.host, traceEnabled = state.traceEnabled;
39365         var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
39366         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
39367         if (directoryExists && host.fileExists(packageJsonPath)) {
39368             var packageJsonContent = ts.readJson(packageJsonPath, host);
39369             if (traceEnabled) {
39370                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
39371             }
39372             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
39373             return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
39374         }
39375         else {
39376             if (directoryExists && traceEnabled) {
39377                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
39378             }
39379             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
39380             state.failedLookupLocations.push(packageJsonPath);
39381         }
39382     }
39383     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
39384         var packageFile;
39385         if (jsonContent) {
39386             switch (extensions) {
39387                 case Extensions.JavaScript:
39388                 case Extensions.Json:
39389                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
39390                     break;
39391                 case Extensions.TypeScript:
39392                     // When resolving typescript modules, try resolving using main field as well
39393                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
39394                     break;
39395                 case Extensions.DtsOnly:
39396                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
39397                     break;
39398                 case Extensions.TSConfig:
39399                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
39400                     break;
39401                 default:
39402                     return ts.Debug.assertNever(extensions);
39403             }
39404         }
39405         var loader = function (extensions, candidate, onlyRecordFailures, state) {
39406             var fromFile = tryFile(candidate, onlyRecordFailures, state);
39407             if (fromFile) {
39408                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
39409                 if (resolved) {
39410                     return noPackageId(resolved);
39411                 }
39412                 if (state.traceEnabled) {
39413                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
39414                 }
39415             }
39416             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
39417             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
39418             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
39419             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
39420         };
39421         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
39422         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
39423         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
39424         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
39425             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
39426             if (state.traceEnabled) {
39427                 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);
39428             }
39429             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
39430             if (result) {
39431                 return removeIgnoredPackageId(result.value);
39432             }
39433         }
39434         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
39435         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
39436         if (packageFileResult)
39437             return packageFileResult;
39438         return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
39439     }
39440     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
39441     function resolvedIfExtensionMatches(extensions, path) {
39442         var ext = ts.tryGetExtensionFromPath(path);
39443         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
39444     }
39445     /** True if `extension` is one of the supported `extensions`. */
39446     function extensionIsOk(extensions, extension) {
39447         switch (extensions) {
39448             case Extensions.JavaScript:
39449                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
39450             case Extensions.TSConfig:
39451             case Extensions.Json:
39452                 return extension === ".json" /* Json */;
39453             case Extensions.TypeScript:
39454                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
39455             case Extensions.DtsOnly:
39456                 return extension === ".d.ts" /* Dts */;
39457         }
39458     }
39459     /* @internal */
39460     function parsePackageName(moduleName) {
39461         var idx = moduleName.indexOf(ts.directorySeparator);
39462         if (moduleName[0] === "@") {
39463             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
39464         }
39465         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
39466     }
39467     ts.parsePackageName = parsePackageName;
39468     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
39469         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
39470     }
39471     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
39472         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
39473         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
39474     }
39475     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
39476         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
39477         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
39478             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
39479                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
39480                 if (resolutionFromCache) {
39481                     return resolutionFromCache;
39482                 }
39483                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
39484             }
39485         });
39486     }
39487     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
39488         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
39489         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
39490         if (!nodeModulesFolderExists && state.traceEnabled) {
39491             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
39492         }
39493         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
39494         if (packageResult) {
39495             return packageResult;
39496         }
39497         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
39498             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
39499             var nodeModulesAtTypesExists = nodeModulesFolderExists;
39500             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
39501                 if (state.traceEnabled) {
39502                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
39503                 }
39504                 nodeModulesAtTypesExists = false;
39505             }
39506             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
39507         }
39508     }
39509     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
39510         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
39511         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
39512         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
39513         if (packageInfo) {
39514             var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
39515             if (fromFile) {
39516                 return noPackageId(fromFile);
39517             }
39518             var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
39519             return withPackageId(packageInfo, fromDirectory);
39520         }
39521         var loader = function (extensions, candidate, onlyRecordFailures, state) {
39522             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
39523                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
39524             return withPackageId(packageInfo, pathAndExtension);
39525         };
39526         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
39527         if (rest !== "") { // If "rest" is empty, we just did this search above.
39528             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
39529             // 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.
39530             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
39531             if (packageInfo && packageInfo.versionPaths) {
39532                 if (state.traceEnabled) {
39533                     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, packageInfo.versionPaths.version, ts.version, rest);
39534                 }
39535                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
39536                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
39537                 if (fromPaths) {
39538                     return fromPaths.value;
39539                 }
39540             }
39541         }
39542         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
39543     }
39544     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
39545         var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
39546         if (matchedPattern) {
39547             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
39548             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
39549             if (state.traceEnabled) {
39550                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
39551             }
39552             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
39553                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
39554                 // When baseUrl is not specified, the command line parser resolves relative paths to the config file location.
39555                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
39556                 if (state.traceEnabled) {
39557                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
39558                 }
39559                 // A path mapping may have an extension, in contrast to an import, which should omit it.
39560                 var extension = ts.tryGetExtensionFromPath(candidate);
39561                 if (extension !== undefined) {
39562                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
39563                     if (path_1 !== undefined) {
39564                         return noPackageId({ path: path_1, ext: extension });
39565                     }
39566                 }
39567                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
39568             });
39569             return { value: resolved };
39570         }
39571     }
39572     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
39573     var mangledScopedPackageSeparator = "__";
39574     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
39575     function mangleScopedPackageNameWithTrace(packageName, state) {
39576         var mangled = mangleScopedPackageName(packageName);
39577         if (state.traceEnabled && mangled !== packageName) {
39578             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
39579         }
39580         return mangled;
39581     }
39582     /* @internal */
39583     function getTypesPackageName(packageName) {
39584         return "@types/" + mangleScopedPackageName(packageName);
39585     }
39586     ts.getTypesPackageName = getTypesPackageName;
39587     /* @internal */
39588     function mangleScopedPackageName(packageName) {
39589         if (ts.startsWith(packageName, "@")) {
39590             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
39591             if (replaceSlash !== packageName) {
39592                 return replaceSlash.slice(1); // Take off the "@"
39593             }
39594         }
39595         return packageName;
39596     }
39597     ts.mangleScopedPackageName = mangleScopedPackageName;
39598     /* @internal */
39599     function getPackageNameFromTypesPackageName(mangledName) {
39600         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
39601         if (withoutAtTypePrefix !== mangledName) {
39602             return unmangleScopedPackageName(withoutAtTypePrefix);
39603         }
39604         return mangledName;
39605     }
39606     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
39607     /* @internal */
39608     function unmangleScopedPackageName(typesPackageName) {
39609         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
39610             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
39611             typesPackageName;
39612     }
39613     ts.unmangleScopedPackageName = unmangleScopedPackageName;
39614     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
39615         var result = cache && cache.get(containingDirectory);
39616         if (result) {
39617             if (state.traceEnabled) {
39618                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
39619             }
39620             state.resultFromCache = result;
39621             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
39622         }
39623     }
39624     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
39625         var traceEnabled = isTraceEnabled(compilerOptions, host);
39626         var failedLookupLocations = [];
39627         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
39628         var containingDirectory = ts.getDirectoryPath(containingFile);
39629         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
39630         // No originalPath because classic resolution doesn't resolve realPath
39631         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
39632         function tryResolve(extensions) {
39633             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
39634             if (resolvedUsingSettings) {
39635                 return { value: resolvedUsingSettings };
39636             }
39637             if (!ts.isExternalModuleNameRelative(moduleName)) {
39638                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
39639                 // Climb up parent directories looking for a module.
39640                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
39641                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
39642                     if (resolutionFromCache) {
39643                         return resolutionFromCache;
39644                     }
39645                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
39646                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
39647                 });
39648                 if (resolved_3) {
39649                     return resolved_3;
39650                 }
39651                 if (extensions === Extensions.TypeScript) {
39652                     // If we didn't find the file normally, look it up in @types.
39653                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
39654                 }
39655             }
39656             else {
39657                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
39658                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
39659             }
39660         }
39661     }
39662     ts.classicNameResolver = classicNameResolver;
39663     /**
39664      * A host may load a module from a global cache of typings.
39665      * This is the minumum code needed to expose that functionality; the rest is in the host.
39666      */
39667     /* @internal */
39668     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
39669         var traceEnabled = isTraceEnabled(compilerOptions, host);
39670         if (traceEnabled) {
39671             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);
39672         }
39673         var failedLookupLocations = [];
39674         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
39675         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
39676         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
39677     }
39678     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
39679     /**
39680      * Wraps value to SearchResult.
39681      * @returns undefined if value is undefined or { value } otherwise
39682      */
39683     function toSearchResult(value) {
39684         return value !== undefined ? { value: value } : undefined;
39685     }
39686 })(ts || (ts = {}));
39687 /* @internal */
39688 var ts;
39689 (function (ts) {
39690     var ModuleInstanceState;
39691     (function (ModuleInstanceState) {
39692         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
39693         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
39694         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
39695     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
39696     function getModuleInstanceState(node, visited) {
39697         if (node.body && !node.body.parent) {
39698             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
39699             ts.setParent(node.body, node);
39700             ts.setParentRecursive(node.body, /*incremental*/ false);
39701         }
39702         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
39703     }
39704     ts.getModuleInstanceState = getModuleInstanceState;
39705     function getModuleInstanceStateCached(node, visited) {
39706         if (visited === void 0) { visited = new ts.Map(); }
39707         var nodeId = ts.getNodeId(node);
39708         if (visited.has(nodeId)) {
39709             return visited.get(nodeId) || 0 /* NonInstantiated */;
39710         }
39711         visited.set(nodeId, undefined);
39712         var result = getModuleInstanceStateWorker(node, visited);
39713         visited.set(nodeId, result);
39714         return result;
39715     }
39716     function getModuleInstanceStateWorker(node, visited) {
39717         // A module is uninstantiated if it contains only
39718         switch (node.kind) {
39719             // 1. interface declarations, type alias declarations
39720             case 253 /* InterfaceDeclaration */:
39721             case 254 /* TypeAliasDeclaration */:
39722                 return 0 /* NonInstantiated */;
39723             // 2. const enum declarations
39724             case 255 /* EnumDeclaration */:
39725                 if (ts.isEnumConst(node)) {
39726                     return 2 /* ConstEnumOnly */;
39727                 }
39728                 break;
39729             // 3. non-exported import declarations
39730             case 261 /* ImportDeclaration */:
39731             case 260 /* ImportEqualsDeclaration */:
39732                 if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) {
39733                     return 0 /* NonInstantiated */;
39734                 }
39735                 break;
39736             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
39737             case 267 /* ExportDeclaration */:
39738                 var exportDeclaration = node;
39739                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 268 /* NamedExports */) {
39740                     var state = 0 /* NonInstantiated */;
39741                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
39742                         var specifier = _a[_i];
39743                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
39744                         if (specifierState > state) {
39745                             state = specifierState;
39746                         }
39747                         if (state === 1 /* Instantiated */) {
39748                             return state;
39749                         }
39750                     }
39751                     return state;
39752                 }
39753                 break;
39754             // 5. other uninstantiated module declarations.
39755             case 257 /* ModuleBlock */: {
39756                 var state_1 = 0 /* NonInstantiated */;
39757                 ts.forEachChild(node, function (n) {
39758                     var childState = getModuleInstanceStateCached(n, visited);
39759                     switch (childState) {
39760                         case 0 /* NonInstantiated */:
39761                             // child is non-instantiated - continue searching
39762                             return;
39763                         case 2 /* ConstEnumOnly */:
39764                             // child is const enum only - record state and continue searching
39765                             state_1 = 2 /* ConstEnumOnly */;
39766                             return;
39767                         case 1 /* Instantiated */:
39768                             // child is instantiated - record state and stop
39769                             state_1 = 1 /* Instantiated */;
39770                             return true;
39771                         default:
39772                             ts.Debug.assertNever(childState);
39773                     }
39774                 });
39775                 return state_1;
39776             }
39777             case 256 /* ModuleDeclaration */:
39778                 return getModuleInstanceState(node, visited);
39779             case 78 /* Identifier */:
39780                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
39781                 // be considered the same as type alias
39782                 if (node.isInJSDocNamespace) {
39783                     return 0 /* NonInstantiated */;
39784                 }
39785         }
39786         return 1 /* Instantiated */;
39787     }
39788     function getModuleInstanceStateForAliasTarget(specifier, visited) {
39789         var name = specifier.propertyName || specifier.name;
39790         var p = specifier.parent;
39791         while (p) {
39792             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
39793                 var statements = p.statements;
39794                 var found = void 0;
39795                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
39796                     var statement = statements_2[_i];
39797                     if (ts.nodeHasName(statement, name)) {
39798                         if (!statement.parent) {
39799                             ts.setParent(statement, p);
39800                             ts.setParentRecursive(statement, /*incremental*/ false);
39801                         }
39802                         var state = getModuleInstanceStateCached(statement, visited);
39803                         if (found === undefined || state > found) {
39804                             found = state;
39805                         }
39806                         if (found === 1 /* Instantiated */) {
39807                             return found;
39808                         }
39809                     }
39810                 }
39811                 if (found !== undefined) {
39812                     return found;
39813                 }
39814             }
39815             p = p.parent;
39816         }
39817         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
39818     }
39819     var ContainerFlags;
39820     (function (ContainerFlags) {
39821         // The current node is not a container, and no container manipulation should happen before
39822         // recursing into it.
39823         ContainerFlags[ContainerFlags["None"] = 0] = "None";
39824         // The current node is a container.  It should be set as the current container (and block-
39825         // container) before recursing into it.  The current node does not have locals.  Examples:
39826         //
39827         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
39828         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
39829         // The current node is a block-scoped-container.  It should be set as the current block-
39830         // container before recursing into it.  Examples:
39831         //
39832         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
39833         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
39834         // The current node is the container of a control flow path. The current control flow should
39835         // be saved and restored, and a new control flow initialized within the container.
39836         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
39837         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
39838         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
39839         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
39840         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
39841         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
39842     })(ContainerFlags || (ContainerFlags = {}));
39843     function initFlowNode(node) {
39844         ts.Debug.attachFlowNodeDebugInfo(node);
39845         return node;
39846     }
39847     var binder = createBinder();
39848     function bindSourceFile(file, options) {
39849         var tracingData = ["bind" /* Bind */, "bindSourceFile", { path: file.path }];
39850         ts.tracing.begin.apply(ts.tracing, tracingData);
39851         ts.performance.mark("beforeBind");
39852         ts.perfLogger.logStartBindFile("" + file.fileName);
39853         binder(file, options);
39854         ts.perfLogger.logStopBindFile();
39855         ts.performance.mark("afterBind");
39856         ts.performance.measure("Bind", "beforeBind", "afterBind");
39857         ts.tracing.end.apply(ts.tracing, tracingData);
39858     }
39859     ts.bindSourceFile = bindSourceFile;
39860     function createBinder() {
39861         var file;
39862         var options;
39863         var languageVersion;
39864         var parent;
39865         var container;
39866         var thisParentContainer; // Container one level up
39867         var blockScopeContainer;
39868         var lastContainer;
39869         var delayedTypeAliases;
39870         var seenThisKeyword;
39871         // state used by control flow analysis
39872         var currentFlow;
39873         var currentBreakTarget;
39874         var currentContinueTarget;
39875         var currentReturnTarget;
39876         var currentTrueTarget;
39877         var currentFalseTarget;
39878         var currentExceptionTarget;
39879         var preSwitchCaseFlow;
39880         var activeLabelList;
39881         var hasExplicitReturn;
39882         // state used for emit helpers
39883         var emitFlags;
39884         // If this file is an external module, then it is automatically in strict-mode according to
39885         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
39886         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
39887         // or if compiler options contain alwaysStrict.
39888         var inStrictMode;
39889         // If we are binding an assignment pattern, we will bind certain expressions differently.
39890         var inAssignmentPattern = false;
39891         var symbolCount = 0;
39892         var Symbol;
39893         var classifiableNames;
39894         var unreachableFlow = { flags: 1 /* Unreachable */ };
39895         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
39896         /**
39897          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
39898          * 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)
39899          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
39900          */
39901         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
39902             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
39903         }
39904         function bindSourceFile(f, opts) {
39905             file = f;
39906             options = opts;
39907             languageVersion = ts.getEmitScriptTarget(options);
39908             inStrictMode = bindInStrictMode(file, opts);
39909             classifiableNames = new ts.Set();
39910             symbolCount = 0;
39911             Symbol = ts.objectAllocator.getSymbolConstructor();
39912             // Attach debugging information if necessary
39913             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
39914             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
39915             if (!file.locals) {
39916                 bind(file);
39917                 file.symbolCount = symbolCount;
39918                 file.classifiableNames = classifiableNames;
39919                 delayedBindJSDocTypedefTag();
39920             }
39921             file = undefined;
39922             options = undefined;
39923             languageVersion = undefined;
39924             parent = undefined;
39925             container = undefined;
39926             thisParentContainer = undefined;
39927             blockScopeContainer = undefined;
39928             lastContainer = undefined;
39929             delayedTypeAliases = undefined;
39930             seenThisKeyword = false;
39931             currentFlow = undefined;
39932             currentBreakTarget = undefined;
39933             currentContinueTarget = undefined;
39934             currentReturnTarget = undefined;
39935             currentTrueTarget = undefined;
39936             currentFalseTarget = undefined;
39937             currentExceptionTarget = undefined;
39938             activeLabelList = undefined;
39939             hasExplicitReturn = false;
39940             inAssignmentPattern = false;
39941             emitFlags = 0 /* None */;
39942         }
39943         return bindSourceFile;
39944         function bindInStrictMode(file, opts) {
39945             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
39946                 // bind in strict mode source files with alwaysStrict option
39947                 return true;
39948             }
39949             else {
39950                 return !!file.externalModuleIndicator;
39951             }
39952         }
39953         function createSymbol(flags, name) {
39954             symbolCount++;
39955             return new Symbol(flags, name);
39956         }
39957         function addDeclarationToSymbol(symbol, node, symbolFlags) {
39958             symbol.flags |= symbolFlags;
39959             node.symbol = symbol;
39960             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
39961             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
39962                 symbol.exports = ts.createSymbolTable();
39963             }
39964             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
39965                 symbol.members = ts.createSymbolTable();
39966             }
39967             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
39968             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
39969                 symbol.constEnumOnlyModule = false;
39970             }
39971             if (symbolFlags & 111551 /* Value */) {
39972                 ts.setValueDeclaration(symbol, node);
39973             }
39974         }
39975         // Should not be called on a declaration with a computed property name,
39976         // unless it is a well known Symbol.
39977         function getDeclarationName(node) {
39978             if (node.kind === 266 /* ExportAssignment */) {
39979                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
39980             }
39981             var name = ts.getNameOfDeclaration(node);
39982             if (name) {
39983                 if (ts.isAmbientModule(node)) {
39984                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
39985                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
39986                 }
39987                 if (name.kind === 158 /* ComputedPropertyName */) {
39988                     var nameExpression = name.expression;
39989                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
39990                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
39991                         return ts.escapeLeadingUnderscores(nameExpression.text);
39992                     }
39993                     if (ts.isSignedNumericLiteral(nameExpression)) {
39994                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
39995                     }
39996                     ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
39997                     return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
39998                 }
39999                 if (ts.isWellKnownSymbolSyntactically(name)) {
40000                     return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
40001                 }
40002                 if (ts.isPrivateIdentifier(name)) {
40003                     // containingClass exists because private names only allowed inside classes
40004                     var containingClass = ts.getContainingClass(node);
40005                     if (!containingClass) {
40006                         // we can get here in cases where there is already a parse error.
40007                         return undefined;
40008                     }
40009                     var containingClassSymbol = containingClass.symbol;
40010                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
40011                 }
40012                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
40013             }
40014             switch (node.kind) {
40015                 case 166 /* Constructor */:
40016                     return "__constructor" /* Constructor */;
40017                 case 174 /* FunctionType */:
40018                 case 169 /* CallSignature */:
40019                 case 313 /* JSDocSignature */:
40020                     return "__call" /* Call */;
40021                 case 175 /* ConstructorType */:
40022                 case 170 /* ConstructSignature */:
40023                     return "__new" /* New */;
40024                 case 171 /* IndexSignature */:
40025                     return "__index" /* Index */;
40026                 case 267 /* ExportDeclaration */:
40027                     return "__export" /* ExportStar */;
40028                 case 297 /* SourceFile */:
40029                     // json file should behave as
40030                     // module.exports = ...
40031                     return "export=" /* ExportEquals */;
40032                 case 216 /* BinaryExpression */:
40033                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
40034                         // module.exports = ...
40035                         return "export=" /* ExportEquals */;
40036                     }
40037                     ts.Debug.fail("Unknown binary declaration kind");
40038                     break;
40039                 case 308 /* JSDocFunctionType */:
40040                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
40041                 case 160 /* Parameter */:
40042                     // Parameters with names are handled at the top of this function.  Parameters
40043                     // without names can only come from JSDocFunctionTypes.
40044                     ts.Debug.assert(node.parent.kind === 308 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
40045                     var functionType = node.parent;
40046                     var index = functionType.parameters.indexOf(node);
40047                     return "arg" + index;
40048             }
40049         }
40050         function getDisplayName(node) {
40051             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
40052         }
40053         /**
40054          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
40055          * @param symbolTable - The symbol table which node will be added to.
40056          * @param parent - node's parent declaration.
40057          * @param node - The declaration to be added to the symbol table
40058          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
40059          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
40060          */
40061         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
40062             ts.Debug.assert(!ts.hasDynamicName(node));
40063             var isDefaultExport = ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
40064             // The exported symbol for an export default function/class node is always named "default"
40065             var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
40066             var symbol;
40067             if (name === undefined) {
40068                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
40069             }
40070             else {
40071                 // Check and see if the symbol table already has a symbol with this name.  If not,
40072                 // create a new symbol with this name and add it to the table.  Note that we don't
40073                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
40074                 // with the 'excludes' flags we pass in.
40075                 //
40076                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
40077                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
40078                 // the same symbol table.  If we have a conflict, report the issue on each
40079                 // declaration we have for this symbol, and then create a new symbol for this
40080                 // declaration.
40081                 //
40082                 // Note that when properties declared in Javascript constructors
40083                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
40084                 // Always. This allows the common Javascript pattern of overwriting a prototype method
40085                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
40086                 //
40087                 // If we created a new symbol, either because we didn't have a symbol with this name
40088                 // in the symbol table, or we conflicted with an existing symbol, then just add this
40089                 // node as the sole declaration of the new symbol.
40090                 //
40091                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
40092                 // you have multiple 'vars' with the same name in the same container).  In this case
40093                 // just add this node into the declarations list of the symbol.
40094                 symbol = symbolTable.get(name);
40095                 if (includes & 2885600 /* Classifiable */) {
40096                     classifiableNames.add(name);
40097                 }
40098                 if (!symbol) {
40099                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
40100                     if (isReplaceableByMethod)
40101                         symbol.isReplaceableByMethod = true;
40102                 }
40103                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
40104                     // A symbol already exists, so don't add this as a declaration.
40105                     return symbol;
40106                 }
40107                 else if (symbol.flags & excludes) {
40108                     if (symbol.isReplaceableByMethod) {
40109                         // Javascript constructor-declared symbols can be discarded in favor of
40110                         // prototype symbols like methods.
40111                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
40112                     }
40113                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
40114                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
40115                         if (ts.isNamedDeclaration(node)) {
40116                             ts.setParent(node.name, node);
40117                         }
40118                         // Report errors every position with duplicate declaration
40119                         // Report errors on previous encountered declarations
40120                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
40121                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
40122                             : ts.Diagnostics.Duplicate_identifier_0;
40123                         var messageNeedsName_1 = true;
40124                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
40125                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
40126                             messageNeedsName_1 = false;
40127                         }
40128                         var multipleDefaultExports_1 = false;
40129                         if (ts.length(symbol.declarations)) {
40130                             // If the current node is a default export of some sort, then check if
40131                             // there are any other default exports that we need to error on.
40132                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
40133                             if (isDefaultExport) {
40134                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
40135                                 messageNeedsName_1 = false;
40136                                 multipleDefaultExports_1 = true;
40137                             }
40138                             else {
40139                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
40140                                 // Error on multiple export default in the following case:
40141                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
40142                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
40143                                 if (symbol.declarations && symbol.declarations.length &&
40144                                     (node.kind === 266 /* ExportAssignment */ && !node.isExportEquals)) {
40145                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
40146                                     messageNeedsName_1 = false;
40147                                     multipleDefaultExports_1 = true;
40148                                 }
40149                             }
40150                         }
40151                         var relatedInformation_1 = [];
40152                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasSyntacticModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
40153                             // export type T; - may have meant export type { T }?
40154                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
40155                         }
40156                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
40157                         ts.forEach(symbol.declarations, function (declaration, index) {
40158                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
40159                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
40160                             file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
40161                             if (multipleDefaultExports_1) {
40162                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
40163                             }
40164                         });
40165                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
40166                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
40167                         symbol = createSymbol(0 /* None */, name);
40168                     }
40169                 }
40170             }
40171             addDeclarationToSymbol(symbol, node, includes);
40172             if (symbol.parent) {
40173                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
40174             }
40175             else {
40176                 symbol.parent = parent;
40177             }
40178             return symbol;
40179         }
40180         function declareModuleMember(node, symbolFlags, symbolExcludes) {
40181             var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node);
40182             if (symbolFlags & 2097152 /* Alias */) {
40183                 if (node.kind === 270 /* ExportSpecifier */ || (node.kind === 260 /* ImportEqualsDeclaration */ && hasExportModifier)) {
40184                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
40185                 }
40186                 else {
40187                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
40188                 }
40189             }
40190             else {
40191                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
40192                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
40193                 //
40194                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
40195                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
40196                 //      with the same name in the same container.
40197                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
40198                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
40199                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
40200                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
40201                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
40202                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
40203                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
40204                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
40205                 if (ts.isJSDocTypeAlias(node))
40206                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
40207                 if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) {
40208                     if (!container.locals || (ts.hasSyntacticModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
40209                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
40210                     }
40211                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
40212                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
40213                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
40214                     node.localSymbol = local;
40215                     return local;
40216                 }
40217                 else {
40218                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
40219                 }
40220             }
40221         }
40222         function jsdocTreatAsExported(node) {
40223             if (node.parent && ts.isModuleDeclaration(node)) {
40224                 node = node.parent;
40225             }
40226             if (!ts.isJSDocTypeAlias(node))
40227                 return false;
40228             // jsdoc typedef handling is a bit of a doozy, but to summarize, treat the typedef as exported if:
40229             // 1. It has an explicit name (since by default typedefs are always directly exported, either at the top level or in a container), or
40230             if (!ts.isJSDocEnumTag(node) && !!node.fullName)
40231                 return true;
40232             // 2. The thing a nameless typedef pulls its name from is implicitly a direct export (either by assignment or actual export flag).
40233             var declName = ts.getNameOfDeclaration(node);
40234             if (!declName)
40235                 return false;
40236             if (ts.isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent))
40237                 return true;
40238             if (ts.isDeclaration(declName.parent) && ts.getCombinedModifierFlags(declName.parent) & 1 /* Export */)
40239                 return true;
40240             // This could potentially be simplified by having `delayedBindJSDocTypedefTag` pass in an override for `hasExportModifier`, since it should
40241             // already have calculated and branched on most of this.
40242             return false;
40243         }
40244         // All container nodes are kept on a linked list in declaration order. This list is used by
40245         // the getLocalNameOfContainer function in the type checker to validate that the local name
40246         // used for a container is unique.
40247         function bindContainer(node, containerFlags) {
40248             // Before we recurse into a node's children, we first save the existing parent, container
40249             // and block-container.  Then after we pop out of processing the children, we restore
40250             // these saved values.
40251             var saveContainer = container;
40252             var saveThisParentContainer = thisParentContainer;
40253             var savedBlockScopeContainer = blockScopeContainer;
40254             // Depending on what kind of node this is, we may have to adjust the current container
40255             // and block-container.   If the current node is a container, then it is automatically
40256             // considered the current block-container as well.  Also, for containers that we know
40257             // may contain locals, we eagerly initialize the .locals field. We do this because
40258             // it's highly likely that the .locals will be needed to place some child in (for example,
40259             // a parameter, or variable declaration).
40260             //
40261             // However, we do not proactively create the .locals for block-containers because it's
40262             // totally normal and common for block-containers to never actually have a block-scoped
40263             // variable in them.  We don't want to end up allocating an object for every 'block' we
40264             // run into when most of them won't be necessary.
40265             //
40266             // Finally, if this is a block-container, then we clear out any existing .locals object
40267             // it may contain within it.  This happens in incremental scenarios.  Because we can be
40268             // reusing a node from a previous compilation, that node may have had 'locals' created
40269             // for it.  We must clear this so we don't accidentally move any stale data forward from
40270             // a previous compilation.
40271             if (containerFlags & 1 /* IsContainer */) {
40272                 if (node.kind !== 209 /* ArrowFunction */) {
40273                     thisParentContainer = container;
40274                 }
40275                 container = blockScopeContainer = node;
40276                 if (containerFlags & 32 /* HasLocals */) {
40277                     container.locals = ts.createSymbolTable();
40278                 }
40279                 addToContainerChain(container);
40280             }
40281             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
40282                 blockScopeContainer = node;
40283                 blockScopeContainer.locals = undefined;
40284             }
40285             if (containerFlags & 4 /* IsControlFlowContainer */) {
40286                 var saveCurrentFlow = currentFlow;
40287                 var saveBreakTarget = currentBreakTarget;
40288                 var saveContinueTarget = currentContinueTarget;
40289                 var saveReturnTarget = currentReturnTarget;
40290                 var saveExceptionTarget = currentExceptionTarget;
40291                 var saveActiveLabelList = activeLabelList;
40292                 var saveHasExplicitReturn = hasExplicitReturn;
40293                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasSyntacticModifier(node, 256 /* Async */) &&
40294                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
40295                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
40296                 // similarly to break statements that exit to a label just past the statement body.
40297                 if (!isIIFE) {
40298                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
40299                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
40300                         currentFlow.node = node;
40301                     }
40302                 }
40303                 // We create a return control flow graph for IIFEs and constructors. For constructors
40304                 // we use the return control flow graph in strict property initialization checks.
40305                 currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined;
40306                 currentExceptionTarget = undefined;
40307                 currentBreakTarget = undefined;
40308                 currentContinueTarget = undefined;
40309                 activeLabelList = undefined;
40310                 hasExplicitReturn = false;
40311                 bindChildren(node);
40312                 // Reset all reachability check related flags on node (for incremental scenarios)
40313                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
40314                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
40315                     node.flags |= 256 /* HasImplicitReturn */;
40316                     if (hasExplicitReturn)
40317                         node.flags |= 512 /* HasExplicitReturn */;
40318                     node.endFlowNode = currentFlow;
40319                 }
40320                 if (node.kind === 297 /* SourceFile */) {
40321                     node.flags |= emitFlags;
40322                 }
40323                 if (currentReturnTarget) {
40324                     addAntecedent(currentReturnTarget, currentFlow);
40325                     currentFlow = finishFlowLabel(currentReturnTarget);
40326                     if (node.kind === 166 /* Constructor */ || (ts.isInJSFile && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) {
40327                         node.returnFlowNode = currentFlow;
40328                     }
40329                 }
40330                 if (!isIIFE) {
40331                     currentFlow = saveCurrentFlow;
40332                 }
40333                 currentBreakTarget = saveBreakTarget;
40334                 currentContinueTarget = saveContinueTarget;
40335                 currentReturnTarget = saveReturnTarget;
40336                 currentExceptionTarget = saveExceptionTarget;
40337                 activeLabelList = saveActiveLabelList;
40338                 hasExplicitReturn = saveHasExplicitReturn;
40339             }
40340             else if (containerFlags & 64 /* IsInterface */) {
40341                 seenThisKeyword = false;
40342                 bindChildren(node);
40343                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
40344             }
40345             else {
40346                 bindChildren(node);
40347             }
40348             container = saveContainer;
40349             thisParentContainer = saveThisParentContainer;
40350             blockScopeContainer = savedBlockScopeContainer;
40351         }
40352         function bindEachFunctionsFirst(nodes) {
40353             bindEach(nodes, function (n) { return n.kind === 251 /* FunctionDeclaration */ ? bind(n) : undefined; });
40354             bindEach(nodes, function (n) { return n.kind !== 251 /* FunctionDeclaration */ ? bind(n) : undefined; });
40355         }
40356         function bindEach(nodes, bindFunction) {
40357             if (bindFunction === void 0) { bindFunction = bind; }
40358             if (nodes === undefined) {
40359                 return;
40360             }
40361             ts.forEach(nodes, bindFunction);
40362         }
40363         function bindEachChild(node) {
40364             ts.forEachChild(node, bind, bindEach);
40365         }
40366         function bindChildren(node) {
40367             var saveInAssignmentPattern = inAssignmentPattern;
40368             // Most nodes aren't valid in an assignment pattern, so we clear the value here
40369             // and set it before we descend into nodes that could actually be part of an assignment pattern.
40370             inAssignmentPattern = false;
40371             if (checkUnreachable(node)) {
40372                 bindEachChild(node);
40373                 bindJSDoc(node);
40374                 inAssignmentPattern = saveInAssignmentPattern;
40375                 return;
40376             }
40377             if (node.kind >= 232 /* FirstStatement */ && node.kind <= 248 /* LastStatement */ && !options.allowUnreachableCode) {
40378                 node.flowNode = currentFlow;
40379             }
40380             switch (node.kind) {
40381                 case 236 /* WhileStatement */:
40382                     bindWhileStatement(node);
40383                     break;
40384                 case 235 /* DoStatement */:
40385                     bindDoStatement(node);
40386                     break;
40387                 case 237 /* ForStatement */:
40388                     bindForStatement(node);
40389                     break;
40390                 case 238 /* ForInStatement */:
40391                 case 239 /* ForOfStatement */:
40392                     bindForInOrForOfStatement(node);
40393                     break;
40394                 case 234 /* IfStatement */:
40395                     bindIfStatement(node);
40396                     break;
40397                 case 242 /* ReturnStatement */:
40398                 case 246 /* ThrowStatement */:
40399                     bindReturnOrThrow(node);
40400                     break;
40401                 case 241 /* BreakStatement */:
40402                 case 240 /* ContinueStatement */:
40403                     bindBreakOrContinueStatement(node);
40404                     break;
40405                 case 247 /* TryStatement */:
40406                     bindTryStatement(node);
40407                     break;
40408                 case 244 /* SwitchStatement */:
40409                     bindSwitchStatement(node);
40410                     break;
40411                 case 258 /* CaseBlock */:
40412                     bindCaseBlock(node);
40413                     break;
40414                 case 284 /* CaseClause */:
40415                     bindCaseClause(node);
40416                     break;
40417                 case 233 /* ExpressionStatement */:
40418                     bindExpressionStatement(node);
40419                     break;
40420                 case 245 /* LabeledStatement */:
40421                     bindLabeledStatement(node);
40422                     break;
40423                 case 214 /* PrefixUnaryExpression */:
40424                     bindPrefixUnaryExpressionFlow(node);
40425                     break;
40426                 case 215 /* PostfixUnaryExpression */:
40427                     bindPostfixUnaryExpressionFlow(node);
40428                     break;
40429                 case 216 /* BinaryExpression */:
40430                     if (ts.isDestructuringAssignment(node)) {
40431                         // Carry over whether we are in an assignment pattern to
40432                         // binary expressions that could actually be an initializer
40433                         inAssignmentPattern = saveInAssignmentPattern;
40434                         bindDestructuringAssignmentFlow(node);
40435                         return;
40436                     }
40437                     bindBinaryExpressionFlow(node);
40438                     break;
40439                 case 210 /* DeleteExpression */:
40440                     bindDeleteExpressionFlow(node);
40441                     break;
40442                 case 217 /* ConditionalExpression */:
40443                     bindConditionalExpressionFlow(node);
40444                     break;
40445                 case 249 /* VariableDeclaration */:
40446                     bindVariableDeclarationFlow(node);
40447                     break;
40448                 case 201 /* PropertyAccessExpression */:
40449                 case 202 /* ElementAccessExpression */:
40450                     bindAccessExpressionFlow(node);
40451                     break;
40452                 case 203 /* CallExpression */:
40453                     bindCallExpressionFlow(node);
40454                     break;
40455                 case 225 /* NonNullExpression */:
40456                     bindNonNullExpressionFlow(node);
40457                     break;
40458                 case 331 /* JSDocTypedefTag */:
40459                 case 324 /* JSDocCallbackTag */:
40460                 case 325 /* JSDocEnumTag */:
40461                     bindJSDocTypeAlias(node);
40462                     break;
40463                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
40464                 case 297 /* SourceFile */: {
40465                     bindEachFunctionsFirst(node.statements);
40466                     bind(node.endOfFileToken);
40467                     break;
40468                 }
40469                 case 230 /* Block */:
40470                 case 257 /* ModuleBlock */:
40471                     bindEachFunctionsFirst(node.statements);
40472                     break;
40473                 case 198 /* BindingElement */:
40474                     bindBindingElementFlow(node);
40475                     break;
40476                 case 200 /* ObjectLiteralExpression */:
40477                 case 199 /* ArrayLiteralExpression */:
40478                 case 288 /* PropertyAssignment */:
40479                 case 220 /* SpreadElement */:
40480                     // Carry over whether we are in an assignment pattern of Object and Array literals
40481                     // as well as their children that are valid assignment targets.
40482                     inAssignmentPattern = saveInAssignmentPattern;
40483                 // falls through
40484                 default:
40485                     bindEachChild(node);
40486                     break;
40487             }
40488             bindJSDoc(node);
40489             inAssignmentPattern = saveInAssignmentPattern;
40490         }
40491         function isNarrowingExpression(expr) {
40492             switch (expr.kind) {
40493                 case 78 /* Identifier */:
40494                 case 79 /* PrivateIdentifier */:
40495                 case 107 /* ThisKeyword */:
40496                 case 201 /* PropertyAccessExpression */:
40497                 case 202 /* ElementAccessExpression */:
40498                     return containsNarrowableReference(expr);
40499                 case 203 /* CallExpression */:
40500                     return hasNarrowableArgument(expr);
40501                 case 207 /* ParenthesizedExpression */:
40502                 case 225 /* NonNullExpression */:
40503                     return isNarrowingExpression(expr.expression);
40504                 case 216 /* BinaryExpression */:
40505                     return isNarrowingBinaryExpression(expr);
40506                 case 214 /* PrefixUnaryExpression */:
40507                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
40508                 case 211 /* TypeOfExpression */:
40509                     return isNarrowingExpression(expr.expression);
40510             }
40511             return false;
40512         }
40513         function isNarrowableReference(expr) {
40514             return expr.kind === 78 /* Identifier */ || expr.kind === 79 /* PrivateIdentifier */ || expr.kind === 107 /* ThisKeyword */ || expr.kind === 105 /* SuperKeyword */ ||
40515                 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
40516                 ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) ||
40517                 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) ||
40518                 ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left);
40519         }
40520         function containsNarrowableReference(expr) {
40521             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
40522         }
40523         function hasNarrowableArgument(expr) {
40524             if (expr.arguments) {
40525                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
40526                     var argument = _a[_i];
40527                     if (containsNarrowableReference(argument)) {
40528                         return true;
40529                     }
40530                 }
40531             }
40532             if (expr.expression.kind === 201 /* PropertyAccessExpression */ &&
40533                 containsNarrowableReference(expr.expression.expression)) {
40534                 return true;
40535             }
40536             return false;
40537         }
40538         function isNarrowingTypeofOperands(expr1, expr2) {
40539             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
40540         }
40541         function isNarrowableInOperands(left, right) {
40542             return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
40543         }
40544         function isNarrowingBinaryExpression(expr) {
40545             switch (expr.operatorToken.kind) {
40546                 case 62 /* EqualsToken */:
40547                 case 74 /* BarBarEqualsToken */:
40548                 case 75 /* AmpersandAmpersandEqualsToken */:
40549                 case 76 /* QuestionQuestionEqualsToken */:
40550                     return containsNarrowableReference(expr.left);
40551                 case 34 /* EqualsEqualsToken */:
40552                 case 35 /* ExclamationEqualsToken */:
40553                 case 36 /* EqualsEqualsEqualsToken */:
40554                 case 37 /* ExclamationEqualsEqualsToken */:
40555                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
40556                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
40557                 case 101 /* InstanceOfKeyword */:
40558                     return isNarrowableOperand(expr.left);
40559                 case 100 /* InKeyword */:
40560                     return isNarrowableInOperands(expr.left, expr.right);
40561                 case 27 /* CommaToken */:
40562                     return isNarrowingExpression(expr.right);
40563             }
40564             return false;
40565         }
40566         function isNarrowableOperand(expr) {
40567             switch (expr.kind) {
40568                 case 207 /* ParenthesizedExpression */:
40569                     return isNarrowableOperand(expr.expression);
40570                 case 216 /* BinaryExpression */:
40571                     switch (expr.operatorToken.kind) {
40572                         case 62 /* EqualsToken */:
40573                             return isNarrowableOperand(expr.left);
40574                         case 27 /* CommaToken */:
40575                             return isNarrowableOperand(expr.right);
40576                     }
40577             }
40578             return containsNarrowableReference(expr);
40579         }
40580         function createBranchLabel() {
40581             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
40582         }
40583         function createLoopLabel() {
40584             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
40585         }
40586         function createReduceLabel(target, antecedents, antecedent) {
40587             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
40588         }
40589         function setFlowNodeReferenced(flow) {
40590             // On first reference we set the Referenced flag, thereafter we set the Shared flag
40591             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
40592         }
40593         function addAntecedent(label, antecedent) {
40594             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
40595                 (label.antecedents || (label.antecedents = [])).push(antecedent);
40596                 setFlowNodeReferenced(antecedent);
40597             }
40598         }
40599         function createFlowCondition(flags, antecedent, expression) {
40600             if (antecedent.flags & 1 /* Unreachable */) {
40601                 return antecedent;
40602             }
40603             if (!expression) {
40604                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
40605             }
40606             if ((expression.kind === 109 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
40607                 expression.kind === 94 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
40608                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
40609                 return unreachableFlow;
40610             }
40611             if (!isNarrowingExpression(expression)) {
40612                 return antecedent;
40613             }
40614             setFlowNodeReferenced(antecedent);
40615             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
40616         }
40617         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
40618             setFlowNodeReferenced(antecedent);
40619             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
40620         }
40621         function createFlowMutation(flags, antecedent, node) {
40622             setFlowNodeReferenced(antecedent);
40623             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
40624             if (currentExceptionTarget) {
40625                 addAntecedent(currentExceptionTarget, result);
40626             }
40627             return result;
40628         }
40629         function createFlowCall(antecedent, node) {
40630             setFlowNodeReferenced(antecedent);
40631             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
40632         }
40633         function finishFlowLabel(flow) {
40634             var antecedents = flow.antecedents;
40635             if (!antecedents) {
40636                 return unreachableFlow;
40637             }
40638             if (antecedents.length === 1) {
40639                 return antecedents[0];
40640             }
40641             return flow;
40642         }
40643         function isStatementCondition(node) {
40644             var parent = node.parent;
40645             switch (parent.kind) {
40646                 case 234 /* IfStatement */:
40647                 case 236 /* WhileStatement */:
40648                 case 235 /* DoStatement */:
40649                     return parent.expression === node;
40650                 case 237 /* ForStatement */:
40651                 case 217 /* ConditionalExpression */:
40652                     return parent.condition === node;
40653             }
40654             return false;
40655         }
40656         function isLogicalExpression(node) {
40657             while (true) {
40658                 if (node.kind === 207 /* ParenthesizedExpression */) {
40659                     node = node.expression;
40660                 }
40661                 else if (node.kind === 214 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
40662                     node = node.operand;
40663                 }
40664                 else {
40665                     return node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
40666                         node.operatorToken.kind === 56 /* BarBarToken */ ||
40667                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
40668                 }
40669             }
40670         }
40671         function isLogicalAssignmentExpression(node) {
40672             node = ts.skipParentheses(node);
40673             return ts.isBinaryExpression(node) && ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind);
40674         }
40675         function isTopLevelLogicalExpression(node) {
40676             while (ts.isParenthesizedExpression(node.parent) ||
40677                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
40678                 node = node.parent;
40679             }
40680             return !isStatementCondition(node) &&
40681                 !isLogicalAssignmentExpression(node.parent) &&
40682                 !isLogicalExpression(node.parent) &&
40683                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
40684         }
40685         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
40686             var savedTrueTarget = currentTrueTarget;
40687             var savedFalseTarget = currentFalseTarget;
40688             currentTrueTarget = trueTarget;
40689             currentFalseTarget = falseTarget;
40690             action(value);
40691             currentTrueTarget = savedTrueTarget;
40692             currentFalseTarget = savedFalseTarget;
40693         }
40694         function bindCondition(node, trueTarget, falseTarget) {
40695             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
40696             if (!node || !isLogicalAssignmentExpression(node) && !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
40697                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
40698                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
40699             }
40700         }
40701         function bindIterativeStatement(node, breakTarget, continueTarget) {
40702             var saveBreakTarget = currentBreakTarget;
40703             var saveContinueTarget = currentContinueTarget;
40704             currentBreakTarget = breakTarget;
40705             currentContinueTarget = continueTarget;
40706             bind(node);
40707             currentBreakTarget = saveBreakTarget;
40708             currentContinueTarget = saveContinueTarget;
40709         }
40710         function setContinueTarget(node, target) {
40711             var label = activeLabelList;
40712             while (label && node.parent.kind === 245 /* LabeledStatement */) {
40713                 label.continueTarget = target;
40714                 label = label.next;
40715                 node = node.parent;
40716             }
40717             return target;
40718         }
40719         function bindWhileStatement(node) {
40720             var preWhileLabel = setContinueTarget(node, createLoopLabel());
40721             var preBodyLabel = createBranchLabel();
40722             var postWhileLabel = createBranchLabel();
40723             addAntecedent(preWhileLabel, currentFlow);
40724             currentFlow = preWhileLabel;
40725             bindCondition(node.expression, preBodyLabel, postWhileLabel);
40726             currentFlow = finishFlowLabel(preBodyLabel);
40727             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
40728             addAntecedent(preWhileLabel, currentFlow);
40729             currentFlow = finishFlowLabel(postWhileLabel);
40730         }
40731         function bindDoStatement(node) {
40732             var preDoLabel = createLoopLabel();
40733             var preConditionLabel = setContinueTarget(node, createBranchLabel());
40734             var postDoLabel = createBranchLabel();
40735             addAntecedent(preDoLabel, currentFlow);
40736             currentFlow = preDoLabel;
40737             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
40738             addAntecedent(preConditionLabel, currentFlow);
40739             currentFlow = finishFlowLabel(preConditionLabel);
40740             bindCondition(node.expression, preDoLabel, postDoLabel);
40741             currentFlow = finishFlowLabel(postDoLabel);
40742         }
40743         function bindForStatement(node) {
40744             var preLoopLabel = setContinueTarget(node, createLoopLabel());
40745             var preBodyLabel = createBranchLabel();
40746             var postLoopLabel = createBranchLabel();
40747             bind(node.initializer);
40748             addAntecedent(preLoopLabel, currentFlow);
40749             currentFlow = preLoopLabel;
40750             bindCondition(node.condition, preBodyLabel, postLoopLabel);
40751             currentFlow = finishFlowLabel(preBodyLabel);
40752             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
40753             bind(node.incrementor);
40754             addAntecedent(preLoopLabel, currentFlow);
40755             currentFlow = finishFlowLabel(postLoopLabel);
40756         }
40757         function bindForInOrForOfStatement(node) {
40758             var preLoopLabel = setContinueTarget(node, createLoopLabel());
40759             var postLoopLabel = createBranchLabel();
40760             bind(node.expression);
40761             addAntecedent(preLoopLabel, currentFlow);
40762             currentFlow = preLoopLabel;
40763             if (node.kind === 239 /* ForOfStatement */) {
40764                 bind(node.awaitModifier);
40765             }
40766             addAntecedent(postLoopLabel, currentFlow);
40767             bind(node.initializer);
40768             if (node.initializer.kind !== 250 /* VariableDeclarationList */) {
40769                 bindAssignmentTargetFlow(node.initializer);
40770             }
40771             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
40772             addAntecedent(preLoopLabel, currentFlow);
40773             currentFlow = finishFlowLabel(postLoopLabel);
40774         }
40775         function bindIfStatement(node) {
40776             var thenLabel = createBranchLabel();
40777             var elseLabel = createBranchLabel();
40778             var postIfLabel = createBranchLabel();
40779             bindCondition(node.expression, thenLabel, elseLabel);
40780             currentFlow = finishFlowLabel(thenLabel);
40781             bind(node.thenStatement);
40782             addAntecedent(postIfLabel, currentFlow);
40783             currentFlow = finishFlowLabel(elseLabel);
40784             bind(node.elseStatement);
40785             addAntecedent(postIfLabel, currentFlow);
40786             currentFlow = finishFlowLabel(postIfLabel);
40787         }
40788         function bindReturnOrThrow(node) {
40789             bind(node.expression);
40790             if (node.kind === 242 /* ReturnStatement */) {
40791                 hasExplicitReturn = true;
40792                 if (currentReturnTarget) {
40793                     addAntecedent(currentReturnTarget, currentFlow);
40794                 }
40795             }
40796             currentFlow = unreachableFlow;
40797         }
40798         function findActiveLabel(name) {
40799             for (var label = activeLabelList; label; label = label.next) {
40800                 if (label.name === name) {
40801                     return label;
40802                 }
40803             }
40804             return undefined;
40805         }
40806         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
40807             var flowLabel = node.kind === 241 /* BreakStatement */ ? breakTarget : continueTarget;
40808             if (flowLabel) {
40809                 addAntecedent(flowLabel, currentFlow);
40810                 currentFlow = unreachableFlow;
40811             }
40812         }
40813         function bindBreakOrContinueStatement(node) {
40814             bind(node.label);
40815             if (node.label) {
40816                 var activeLabel = findActiveLabel(node.label.escapedText);
40817                 if (activeLabel) {
40818                     activeLabel.referenced = true;
40819                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
40820                 }
40821             }
40822             else {
40823                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
40824             }
40825         }
40826         function bindTryStatement(node) {
40827             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
40828             // to track code that causes mutations (because only mutations widen the possible control flow type of
40829             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
40830             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
40831             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
40832             // represent exceptions that occur before any mutations.
40833             var saveReturnTarget = currentReturnTarget;
40834             var saveExceptionTarget = currentExceptionTarget;
40835             var normalExitLabel = createBranchLabel();
40836             var returnLabel = createBranchLabel();
40837             var exceptionLabel = createBranchLabel();
40838             if (node.finallyBlock) {
40839                 currentReturnTarget = returnLabel;
40840             }
40841             addAntecedent(exceptionLabel, currentFlow);
40842             currentExceptionTarget = exceptionLabel;
40843             bind(node.tryBlock);
40844             addAntecedent(normalExitLabel, currentFlow);
40845             if (node.catchClause) {
40846                 // Start of catch clause is the target of exceptions from try block.
40847                 currentFlow = finishFlowLabel(exceptionLabel);
40848                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
40849                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
40850                 // acts like a second try block.
40851                 exceptionLabel = createBranchLabel();
40852                 addAntecedent(exceptionLabel, currentFlow);
40853                 currentExceptionTarget = exceptionLabel;
40854                 bind(node.catchClause);
40855                 addAntecedent(normalExitLabel, currentFlow);
40856             }
40857             currentReturnTarget = saveReturnTarget;
40858             currentExceptionTarget = saveExceptionTarget;
40859             if (node.finallyBlock) {
40860                 // Possible ways control can reach the finally block:
40861                 // 1) Normal completion of try block of a try-finally or try-catch-finally
40862                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
40863                 // 3) Return in try or catch block of a try-finally or try-catch-finally
40864                 // 4) Exception in try block of a try-finally
40865                 // 5) Exception in catch block of a try-catch-finally
40866                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
40867                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
40868                 // the finally block, we only want to consider the first two (if we're past a finally block then it
40869                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
40870                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
40871                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
40872                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
40873                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
40874                 var finallyLabel = createBranchLabel();
40875                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
40876                 currentFlow = finallyLabel;
40877                 bind(node.finallyBlock);
40878                 if (currentFlow.flags & 1 /* Unreachable */) {
40879                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
40880                     currentFlow = unreachableFlow;
40881                 }
40882                 else {
40883                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
40884                     // flow that goes back through the finally block and back through only the return statements.
40885                     if (currentReturnTarget && returnLabel.antecedents) {
40886                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
40887                     }
40888                     // If we have an outer exception target (i.e. a containing try-finally or try-catch-finally), add a
40889                     // control flow that goes back through the finally blok and back through each possible exception source.
40890                     if (currentExceptionTarget && exceptionLabel.antecedents) {
40891                         addAntecedent(currentExceptionTarget, createReduceLabel(finallyLabel, exceptionLabel.antecedents, currentFlow));
40892                     }
40893                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
40894                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
40895                     // result in an unreachable current control flow.
40896                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
40897                 }
40898             }
40899             else {
40900                 currentFlow = finishFlowLabel(normalExitLabel);
40901             }
40902         }
40903         function bindSwitchStatement(node) {
40904             var postSwitchLabel = createBranchLabel();
40905             bind(node.expression);
40906             var saveBreakTarget = currentBreakTarget;
40907             var savePreSwitchCaseFlow = preSwitchCaseFlow;
40908             currentBreakTarget = postSwitchLabel;
40909             preSwitchCaseFlow = currentFlow;
40910             bind(node.caseBlock);
40911             addAntecedent(postSwitchLabel, currentFlow);
40912             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 285 /* DefaultClause */; });
40913             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
40914             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
40915             // this property in control flow analysis, it's there only for backwards compatibility.
40916             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
40917             if (!hasDefault) {
40918                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
40919             }
40920             currentBreakTarget = saveBreakTarget;
40921             preSwitchCaseFlow = savePreSwitchCaseFlow;
40922             currentFlow = finishFlowLabel(postSwitchLabel);
40923         }
40924         function bindCaseBlock(node) {
40925             var clauses = node.clauses;
40926             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
40927             var fallthroughFlow = unreachableFlow;
40928             for (var i = 0; i < clauses.length; i++) {
40929                 var clauseStart = i;
40930                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
40931                     bind(clauses[i]);
40932                     i++;
40933                 }
40934                 var preCaseLabel = createBranchLabel();
40935                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
40936                 addAntecedent(preCaseLabel, fallthroughFlow);
40937                 currentFlow = finishFlowLabel(preCaseLabel);
40938                 var clause = clauses[i];
40939                 bind(clause);
40940                 fallthroughFlow = currentFlow;
40941                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
40942                     clause.fallthroughFlowNode = currentFlow;
40943                 }
40944             }
40945         }
40946         function bindCaseClause(node) {
40947             var saveCurrentFlow = currentFlow;
40948             currentFlow = preSwitchCaseFlow;
40949             bind(node.expression);
40950             currentFlow = saveCurrentFlow;
40951             bindEach(node.statements);
40952         }
40953         function bindExpressionStatement(node) {
40954             bind(node.expression);
40955             maybeBindExpressionFlowIfCall(node.expression);
40956         }
40957         function maybeBindExpressionFlowIfCall(node) {
40958             // A top level or LHS of comma expression call expression with a dotted function name and at least one argument
40959             // is potentially an assertion and is therefore included in the control flow.
40960             if (node.kind === 203 /* CallExpression */) {
40961                 var call = node;
40962                 if (ts.isDottedName(call.expression) && call.expression.kind !== 105 /* SuperKeyword */) {
40963                     currentFlow = createFlowCall(currentFlow, call);
40964                 }
40965             }
40966         }
40967         function bindLabeledStatement(node) {
40968             var postStatementLabel = createBranchLabel();
40969             activeLabelList = {
40970                 next: activeLabelList,
40971                 name: node.label.escapedText,
40972                 breakTarget: postStatementLabel,
40973                 continueTarget: undefined,
40974                 referenced: false
40975             };
40976             bind(node.label);
40977             bind(node.statement);
40978             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
40979                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
40980             }
40981             activeLabelList = activeLabelList.next;
40982             addAntecedent(postStatementLabel, currentFlow);
40983             currentFlow = finishFlowLabel(postStatementLabel);
40984         }
40985         function bindDestructuringTargetFlow(node) {
40986             if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
40987                 bindAssignmentTargetFlow(node.left);
40988             }
40989             else {
40990                 bindAssignmentTargetFlow(node);
40991             }
40992         }
40993         function bindAssignmentTargetFlow(node) {
40994             if (isNarrowableReference(node)) {
40995                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
40996             }
40997             else if (node.kind === 199 /* ArrayLiteralExpression */) {
40998                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
40999                     var e = _a[_i];
41000                     if (e.kind === 220 /* SpreadElement */) {
41001                         bindAssignmentTargetFlow(e.expression);
41002                     }
41003                     else {
41004                         bindDestructuringTargetFlow(e);
41005                     }
41006                 }
41007             }
41008             else if (node.kind === 200 /* ObjectLiteralExpression */) {
41009                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
41010                     var p = _c[_b];
41011                     if (p.kind === 288 /* PropertyAssignment */) {
41012                         bindDestructuringTargetFlow(p.initializer);
41013                     }
41014                     else if (p.kind === 289 /* ShorthandPropertyAssignment */) {
41015                         bindAssignmentTargetFlow(p.name);
41016                     }
41017                     else if (p.kind === 290 /* SpreadAssignment */) {
41018                         bindAssignmentTargetFlow(p.expression);
41019                     }
41020                 }
41021             }
41022         }
41023         function bindLogicalLikeExpression(node, trueTarget, falseTarget) {
41024             var preRightLabel = createBranchLabel();
41025             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 75 /* AmpersandAmpersandEqualsToken */) {
41026                 bindCondition(node.left, preRightLabel, falseTarget);
41027             }
41028             else {
41029                 bindCondition(node.left, trueTarget, preRightLabel);
41030             }
41031             currentFlow = finishFlowLabel(preRightLabel);
41032             bind(node.operatorToken);
41033             if (ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind)) {
41034                 doWithConditionalBranches(bind, node.right, trueTarget, falseTarget);
41035                 bindAssignmentTargetFlow(node.left);
41036                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41037                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41038             }
41039             else {
41040                 bindCondition(node.right, trueTarget, falseTarget);
41041             }
41042         }
41043         function bindPrefixUnaryExpressionFlow(node) {
41044             if (node.operator === 53 /* ExclamationToken */) {
41045                 var saveTrueTarget = currentTrueTarget;
41046                 currentTrueTarget = currentFalseTarget;
41047                 currentFalseTarget = saveTrueTarget;
41048                 bindEachChild(node);
41049                 currentFalseTarget = currentTrueTarget;
41050                 currentTrueTarget = saveTrueTarget;
41051             }
41052             else {
41053                 bindEachChild(node);
41054                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
41055                     bindAssignmentTargetFlow(node.operand);
41056                 }
41057             }
41058         }
41059         function bindPostfixUnaryExpressionFlow(node) {
41060             bindEachChild(node);
41061             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
41062                 bindAssignmentTargetFlow(node.operand);
41063             }
41064         }
41065         function bindDestructuringAssignmentFlow(node) {
41066             if (inAssignmentPattern) {
41067                 inAssignmentPattern = false;
41068                 bind(node.operatorToken);
41069                 bind(node.right);
41070                 inAssignmentPattern = true;
41071                 bind(node.left);
41072             }
41073             else {
41074                 inAssignmentPattern = true;
41075                 bind(node.left);
41076                 inAssignmentPattern = false;
41077                 bind(node.operatorToken);
41078                 bind(node.right);
41079             }
41080             bindAssignmentTargetFlow(node.left);
41081         }
41082         var BindBinaryExpressionFlowState;
41083         (function (BindBinaryExpressionFlowState) {
41084             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
41085             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
41086             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
41087             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
41088             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
41089         })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
41090         function bindBinaryExpressionFlow(node) {
41091             var workStacks = {
41092                 expr: [node],
41093                 state: [1 /* MaybeBindLeft */],
41094                 inStrictMode: [undefined],
41095                 parent: [undefined],
41096             };
41097             var stackIndex = 0;
41098             while (stackIndex >= 0) {
41099                 node = workStacks.expr[stackIndex];
41100                 switch (workStacks.state[stackIndex]) {
41101                     case 0 /* BindThenBindChildren */: {
41102                         // This state is used only when recuring, to emulate the work that `bind` does before
41103                         // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
41104                         ts.setParent(node, parent);
41105                         var saveInStrictMode = inStrictMode;
41106                         bindWorker(node);
41107                         var saveParent = parent;
41108                         parent = node;
41109                         advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent);
41110                         break;
41111                     }
41112                     case 1 /* MaybeBindLeft */: {
41113                         var operator = node.operatorToken.kind;
41114                         // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
41115                         // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
41116                         // For now, though, since the common cases are chained `+`, leaving it recursive is fine
41117                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */ ||
41118                             ts.isLogicalOrCoalescingAssignmentOperator(operator)) {
41119                             if (isTopLevelLogicalExpression(node)) {
41120                                 var postExpressionLabel = createBranchLabel();
41121                                 bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel);
41122                                 currentFlow = finishFlowLabel(postExpressionLabel);
41123                             }
41124                             else {
41125                                 bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget);
41126                             }
41127                             completeNode();
41128                         }
41129                         else {
41130                             advanceState(2 /* BindToken */);
41131                             maybeBind(node.left);
41132                         }
41133                         break;
41134                     }
41135                     case 2 /* BindToken */: {
41136                         if (node.operatorToken.kind === 27 /* CommaToken */) {
41137                             maybeBindExpressionFlowIfCall(node.left);
41138                         }
41139                         advanceState(3 /* BindRight */);
41140                         maybeBind(node.operatorToken);
41141                         break;
41142                     }
41143                     case 3 /* BindRight */: {
41144                         advanceState(4 /* FinishBind */);
41145                         maybeBind(node.right);
41146                         break;
41147                     }
41148                     case 4 /* FinishBind */: {
41149                         var operator = node.operatorToken.kind;
41150                         if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
41151                             bindAssignmentTargetFlow(node.left);
41152                             if (operator === 62 /* EqualsToken */ && node.left.kind === 202 /* ElementAccessExpression */) {
41153                                 var elementAccess = node.left;
41154                                 if (isNarrowableOperand(elementAccess.expression)) {
41155                                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
41156                                 }
41157                             }
41158                         }
41159                         completeNode();
41160                         break;
41161                     }
41162                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
41163                 }
41164             }
41165             /**
41166              * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
41167              * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
41168              */
41169             function advanceState(state, isInStrictMode, parent) {
41170                 workStacks.state[stackIndex] = state;
41171                 if (isInStrictMode !== undefined) {
41172                     workStacks.inStrictMode[stackIndex] = isInStrictMode;
41173                 }
41174                 if (parent !== undefined) {
41175                     workStacks.parent[stackIndex] = parent;
41176                 }
41177             }
41178             function completeNode() {
41179                 if (workStacks.inStrictMode[stackIndex] !== undefined) {
41180                     inStrictMode = workStacks.inStrictMode[stackIndex];
41181                     parent = workStacks.parent[stackIndex];
41182                 }
41183                 stackIndex--;
41184             }
41185             /**
41186              * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
41187              */
41188             function maybeBind(node) {
41189                 if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) {
41190                     stackIndex++;
41191                     workStacks.expr[stackIndex] = node;
41192                     workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
41193                     workStacks.inStrictMode[stackIndex] = undefined;
41194                     workStacks.parent[stackIndex] = undefined;
41195                 }
41196                 else {
41197                     bind(node);
41198                 }
41199             }
41200         }
41201         function bindDeleteExpressionFlow(node) {
41202             bindEachChild(node);
41203             if (node.expression.kind === 201 /* PropertyAccessExpression */) {
41204                 bindAssignmentTargetFlow(node.expression);
41205             }
41206         }
41207         function bindConditionalExpressionFlow(node) {
41208             var trueLabel = createBranchLabel();
41209             var falseLabel = createBranchLabel();
41210             var postExpressionLabel = createBranchLabel();
41211             bindCondition(node.condition, trueLabel, falseLabel);
41212             currentFlow = finishFlowLabel(trueLabel);
41213             bind(node.questionToken);
41214             bind(node.whenTrue);
41215             addAntecedent(postExpressionLabel, currentFlow);
41216             currentFlow = finishFlowLabel(falseLabel);
41217             bind(node.colonToken);
41218             bind(node.whenFalse);
41219             addAntecedent(postExpressionLabel, currentFlow);
41220             currentFlow = finishFlowLabel(postExpressionLabel);
41221         }
41222         function bindInitializedVariableFlow(node) {
41223             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
41224             if (ts.isBindingPattern(name)) {
41225                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
41226                     var child = _a[_i];
41227                     bindInitializedVariableFlow(child);
41228                 }
41229             }
41230             else {
41231                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
41232             }
41233         }
41234         function bindVariableDeclarationFlow(node) {
41235             bindEachChild(node);
41236             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
41237                 bindInitializedVariableFlow(node);
41238             }
41239         }
41240         function bindBindingElementFlow(node) {
41241             if (ts.isBindingPattern(node.name)) {
41242                 // When evaluating a binding pattern, the initializer is evaluated before the binding pattern, per:
41243                 // - https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization
41244                 //   - `BindingElement: BindingPattern Initializer?`
41245                 // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization
41246                 //   - `BindingElement: BindingPattern Initializer?`
41247                 bindEach(node.decorators);
41248                 bindEach(node.modifiers);
41249                 bind(node.dotDotDotToken);
41250                 bind(node.propertyName);
41251                 bind(node.initializer);
41252                 bind(node.name);
41253             }
41254             else {
41255                 bindEachChild(node);
41256             }
41257         }
41258         function bindJSDocTypeAlias(node) {
41259             ts.setParent(node.tagName, node);
41260             if (node.kind !== 325 /* JSDocEnumTag */ && node.fullName) {
41261                 ts.setParent(node.fullName, node);
41262                 ts.setParentRecursive(node.fullName, /*incremental*/ false);
41263             }
41264         }
41265         function bindJSDocClassTag(node) {
41266             bindEachChild(node);
41267             var host = ts.getHostSignatureFromJSDoc(node);
41268             if (host && host.kind !== 165 /* MethodDeclaration */) {
41269                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
41270             }
41271         }
41272         function bindOptionalExpression(node, trueTarget, falseTarget) {
41273             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
41274             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
41275                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41276                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41277             }
41278         }
41279         function bindOptionalChainRest(node) {
41280             switch (node.kind) {
41281                 case 201 /* PropertyAccessExpression */:
41282                     bind(node.questionDotToken);
41283                     bind(node.name);
41284                     break;
41285                 case 202 /* ElementAccessExpression */:
41286                     bind(node.questionDotToken);
41287                     bind(node.argumentExpression);
41288                     break;
41289                 case 203 /* CallExpression */:
41290                     bind(node.questionDotToken);
41291                     bindEach(node.typeArguments);
41292                     bindEach(node.arguments);
41293                     break;
41294             }
41295         }
41296         function bindOptionalChain(node, trueTarget, falseTarget) {
41297             // For an optional chain, we emulate the behavior of a logical expression:
41298             //
41299             // a?.b         -> a && a.b
41300             // a?.b.c       -> a && a.b.c
41301             // a?.b?.c      -> a && a.b && a.b.c
41302             // a?.[x = 1]   -> a && a[x = 1]
41303             //
41304             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
41305             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
41306             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
41307             // chain node. We then treat the entire node as the right side of the expression.
41308             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
41309             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
41310             if (preChainLabel) {
41311                 currentFlow = finishFlowLabel(preChainLabel);
41312             }
41313             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
41314             if (ts.isOutermostOptionalChain(node)) {
41315                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41316                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41317             }
41318         }
41319         function bindOptionalChainFlow(node) {
41320             if (isTopLevelLogicalExpression(node)) {
41321                 var postExpressionLabel = createBranchLabel();
41322                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
41323                 currentFlow = finishFlowLabel(postExpressionLabel);
41324             }
41325             else {
41326                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
41327             }
41328         }
41329         function bindNonNullExpressionFlow(node) {
41330             if (ts.isOptionalChain(node)) {
41331                 bindOptionalChainFlow(node);
41332             }
41333             else {
41334                 bindEachChild(node);
41335             }
41336         }
41337         function bindAccessExpressionFlow(node) {
41338             if (ts.isOptionalChain(node)) {
41339                 bindOptionalChainFlow(node);
41340             }
41341             else {
41342                 bindEachChild(node);
41343             }
41344         }
41345         function bindCallExpressionFlow(node) {
41346             if (ts.isOptionalChain(node)) {
41347                 bindOptionalChainFlow(node);
41348             }
41349             else {
41350                 // If the target of the call expression is a function expression or arrow function we have
41351                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
41352                 // the current control flow (which includes evaluation of the IIFE arguments).
41353                 var expr = ts.skipParentheses(node.expression);
41354                 if (expr.kind === 208 /* FunctionExpression */ || expr.kind === 209 /* ArrowFunction */) {
41355                     bindEach(node.typeArguments);
41356                     bindEach(node.arguments);
41357                     bind(node.expression);
41358                 }
41359                 else {
41360                     bindEachChild(node);
41361                     if (node.expression.kind === 105 /* SuperKeyword */) {
41362                         currentFlow = createFlowCall(currentFlow, node);
41363                     }
41364                 }
41365             }
41366             if (node.expression.kind === 201 /* PropertyAccessExpression */) {
41367                 var propertyAccess = node.expression;
41368                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
41369                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
41370                 }
41371             }
41372         }
41373         function getContainerFlags(node) {
41374             switch (node.kind) {
41375                 case 221 /* ClassExpression */:
41376                 case 252 /* ClassDeclaration */:
41377                 case 255 /* EnumDeclaration */:
41378                 case 200 /* ObjectLiteralExpression */:
41379                 case 177 /* TypeLiteral */:
41380                 case 312 /* JSDocTypeLiteral */:
41381                 case 281 /* JsxAttributes */:
41382                     return 1 /* IsContainer */;
41383                 case 253 /* InterfaceDeclaration */:
41384                     return 1 /* IsContainer */ | 64 /* IsInterface */;
41385                 case 256 /* ModuleDeclaration */:
41386                 case 254 /* TypeAliasDeclaration */:
41387                 case 190 /* MappedType */:
41388                     return 1 /* IsContainer */ | 32 /* HasLocals */;
41389                 case 297 /* SourceFile */:
41390                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
41391                 case 165 /* MethodDeclaration */:
41392                     if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
41393                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
41394                     }
41395                 // falls through
41396                 case 166 /* Constructor */:
41397                 case 251 /* FunctionDeclaration */:
41398                 case 164 /* MethodSignature */:
41399                 case 167 /* GetAccessor */:
41400                 case 168 /* SetAccessor */:
41401                 case 169 /* CallSignature */:
41402                 case 313 /* JSDocSignature */:
41403                 case 308 /* JSDocFunctionType */:
41404                 case 174 /* FunctionType */:
41405                 case 170 /* ConstructSignature */:
41406                 case 171 /* IndexSignature */:
41407                 case 175 /* ConstructorType */:
41408                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
41409                 case 208 /* FunctionExpression */:
41410                 case 209 /* ArrowFunction */:
41411                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
41412                 case 257 /* ModuleBlock */:
41413                     return 4 /* IsControlFlowContainer */;
41414                 case 163 /* PropertyDeclaration */:
41415                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
41416                 case 287 /* CatchClause */:
41417                 case 237 /* ForStatement */:
41418                 case 238 /* ForInStatement */:
41419                 case 239 /* ForOfStatement */:
41420                 case 258 /* CaseBlock */:
41421                     return 2 /* IsBlockScopedContainer */;
41422                 case 230 /* Block */:
41423                     // do not treat blocks directly inside a function as a block-scoped-container.
41424                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
41425                     // would not appear to be a redeclaration of a block scoped local in the following
41426                     // example:
41427                     //
41428                     //      function foo() {
41429                     //          var x;
41430                     //          let x;
41431                     //      }
41432                     //
41433                     // If we placed 'var x' into the function locals and 'let x' into the locals of
41434                     // the block, then there would be no collision.
41435                     //
41436                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
41437                     // and 'let x' go into the Function-container's locals, and we do get a collision
41438                     // conflict.
41439                     return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
41440             }
41441             return 0 /* None */;
41442         }
41443         function addToContainerChain(next) {
41444             if (lastContainer) {
41445                 lastContainer.nextContainer = next;
41446             }
41447             lastContainer = next;
41448         }
41449         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
41450             switch (container.kind) {
41451                 // Modules, source files, and classes need specialized handling for how their
41452                 // members are declared (for example, a member of a class will go into a specific
41453                 // symbol table depending on if it is static or not). We defer to specialized
41454                 // handlers to take care of declaring these child members.
41455                 case 256 /* ModuleDeclaration */:
41456                     return declareModuleMember(node, symbolFlags, symbolExcludes);
41457                 case 297 /* SourceFile */:
41458                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
41459                 case 221 /* ClassExpression */:
41460                 case 252 /* ClassDeclaration */:
41461                     return declareClassMember(node, symbolFlags, symbolExcludes);
41462                 case 255 /* EnumDeclaration */:
41463                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
41464                 case 177 /* TypeLiteral */:
41465                 case 312 /* JSDocTypeLiteral */:
41466                 case 200 /* ObjectLiteralExpression */:
41467                 case 253 /* InterfaceDeclaration */:
41468                 case 281 /* JsxAttributes */:
41469                     // Interface/Object-types always have their children added to the 'members' of
41470                     // their container. They are only accessible through an instance of their
41471                     // container, and are never in scope otherwise (even inside the body of the
41472                     // object / type / interface declaring them). An exception is type parameters,
41473                     // which are in scope without qualification (similar to 'locals').
41474                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
41475                 case 174 /* FunctionType */:
41476                 case 175 /* ConstructorType */:
41477                 case 169 /* CallSignature */:
41478                 case 170 /* ConstructSignature */:
41479                 case 313 /* JSDocSignature */:
41480                 case 171 /* IndexSignature */:
41481                 case 165 /* MethodDeclaration */:
41482                 case 164 /* MethodSignature */:
41483                 case 166 /* Constructor */:
41484                 case 167 /* GetAccessor */:
41485                 case 168 /* SetAccessor */:
41486                 case 251 /* FunctionDeclaration */:
41487                 case 208 /* FunctionExpression */:
41488                 case 209 /* ArrowFunction */:
41489                 case 308 /* JSDocFunctionType */:
41490                 case 331 /* JSDocTypedefTag */:
41491                 case 324 /* JSDocCallbackTag */:
41492                 case 254 /* TypeAliasDeclaration */:
41493                 case 190 /* MappedType */:
41494                     // All the children of these container types are never visible through another
41495                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
41496                     // they're only accessed 'lexically' (i.e. from code that exists underneath
41497                     // their container in the tree). To accomplish this, we simply add their declared
41498                     // symbol to the 'locals' of the container.  These symbols can then be found as
41499                     // the type checker walks up the containers, checking them for matching names.
41500                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
41501             }
41502         }
41503         function declareClassMember(node, symbolFlags, symbolExcludes) {
41504             return ts.hasSyntacticModifier(node, 32 /* Static */)
41505                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
41506                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
41507         }
41508         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
41509             return ts.isExternalModule(file)
41510                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
41511                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
41512         }
41513         function hasExportDeclarations(node) {
41514             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
41515             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
41516         }
41517         function setExportContextFlag(node) {
41518             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
41519             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
41520             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
41521                 node.flags |= 64 /* ExportContext */;
41522             }
41523             else {
41524                 node.flags &= ~64 /* ExportContext */;
41525             }
41526         }
41527         function bindModuleDeclaration(node) {
41528             setExportContextFlag(node);
41529             if (ts.isAmbientModule(node)) {
41530                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
41531                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
41532                 }
41533                 if (ts.isModuleAugmentationExternal(node)) {
41534                     declareModuleSymbol(node);
41535                 }
41536                 else {
41537                     var pattern = void 0;
41538                     if (node.name.kind === 10 /* StringLiteral */) {
41539                         var text = node.name.text;
41540                         if (ts.hasZeroOrOneAsteriskCharacter(text)) {
41541                             pattern = ts.tryParsePattern(text);
41542                         }
41543                         else {
41544                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
41545                         }
41546                     }
41547                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
41548                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
41549                 }
41550             }
41551             else {
41552                 var state = declareModuleSymbol(node);
41553                 if (state !== 0 /* NonInstantiated */) {
41554                     var symbol = node.symbol;
41555                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
41556                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
41557                         // Current must be `const enum` only
41558                         && state === 2 /* ConstEnumOnly */
41559                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
41560                         && symbol.constEnumOnlyModule !== false;
41561                 }
41562             }
41563         }
41564         function declareModuleSymbol(node) {
41565             var state = getModuleInstanceState(node);
41566             var instantiated = state !== 0 /* NonInstantiated */;
41567             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
41568             return state;
41569         }
41570         function bindFunctionOrConstructorType(node) {
41571             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
41572             // to the one we would get for: { <...>(...): T }
41573             //
41574             // We do that by making an anonymous type literal symbol, and then setting the function
41575             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
41576             // from an actual type literal symbol you would have gotten had you used the long form.
41577             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
41578             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
41579             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
41580             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
41581             typeLiteralSymbol.members = ts.createSymbolTable();
41582             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
41583         }
41584         function bindObjectLiteralExpression(node) {
41585             var ElementKind;
41586             (function (ElementKind) {
41587                 ElementKind[ElementKind["Property"] = 1] = "Property";
41588                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
41589             })(ElementKind || (ElementKind = {}));
41590             if (inStrictMode && !ts.isAssignmentTarget(node)) {
41591                 var seen = new ts.Map();
41592                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
41593                     var prop = _a[_i];
41594                     if (prop.kind === 290 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) {
41595                         continue;
41596                     }
41597                     var identifier = prop.name;
41598                     // ECMA-262 11.1.5 Object Initializer
41599                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
41600                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
41601                     // IsDataDescriptor(propId.descriptor) is true.
41602                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
41603                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
41604                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
41605                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
41606                     var currentKind = prop.kind === 288 /* PropertyAssignment */ || prop.kind === 289 /* ShorthandPropertyAssignment */ || prop.kind === 165 /* MethodDeclaration */
41607                         ? 1 /* Property */
41608                         : 2 /* Accessor */;
41609                     var existingKind = seen.get(identifier.escapedText);
41610                     if (!existingKind) {
41611                         seen.set(identifier.escapedText, currentKind);
41612                         continue;
41613                     }
41614                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
41615                         var span = ts.getErrorSpanForNode(file, identifier);
41616                         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));
41617                     }
41618                 }
41619             }
41620             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
41621         }
41622         function bindJsxAttributes(node) {
41623             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
41624         }
41625         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
41626             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
41627         }
41628         function bindAnonymousDeclaration(node, symbolFlags, name) {
41629             var symbol = createSymbol(symbolFlags, name);
41630             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
41631                 symbol.parent = container.symbol;
41632             }
41633             addDeclarationToSymbol(symbol, node, symbolFlags);
41634             return symbol;
41635         }
41636         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
41637             switch (blockScopeContainer.kind) {
41638                 case 256 /* ModuleDeclaration */:
41639                     declareModuleMember(node, symbolFlags, symbolExcludes);
41640                     break;
41641                 case 297 /* SourceFile */:
41642                     if (ts.isExternalOrCommonJsModule(container)) {
41643                         declareModuleMember(node, symbolFlags, symbolExcludes);
41644                         break;
41645                     }
41646                 // falls through
41647                 default:
41648                     if (!blockScopeContainer.locals) {
41649                         blockScopeContainer.locals = ts.createSymbolTable();
41650                         addToContainerChain(blockScopeContainer);
41651                     }
41652                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
41653             }
41654         }
41655         function delayedBindJSDocTypedefTag() {
41656             if (!delayedTypeAliases) {
41657                 return;
41658             }
41659             var saveContainer = container;
41660             var saveLastContainer = lastContainer;
41661             var saveBlockScopeContainer = blockScopeContainer;
41662             var saveParent = parent;
41663             var saveCurrentFlow = currentFlow;
41664             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
41665                 var typeAlias = delayedTypeAliases_1[_i];
41666                 var host = ts.getJSDocHost(typeAlias);
41667                 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
41668                 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
41669                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
41670                 parent = typeAlias;
41671                 bind(typeAlias.typeExpression);
41672                 var declName = ts.getNameOfDeclaration(typeAlias);
41673                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
41674                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
41675                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
41676                     if (isTopLevel) {
41677                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
41678                         var oldContainer = container;
41679                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
41680                             case 1 /* ExportsProperty */:
41681                             case 2 /* ModuleExports */:
41682                                 if (!ts.isExternalOrCommonJsModule(file)) {
41683                                     container = undefined;
41684                                 }
41685                                 else {
41686                                     container = file;
41687                                 }
41688                                 break;
41689                             case 4 /* ThisProperty */:
41690                                 container = declName.parent.expression;
41691                                 break;
41692                             case 3 /* PrototypeProperty */:
41693                                 container = declName.parent.expression.name;
41694                                 break;
41695                             case 5 /* Property */:
41696                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
41697                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
41698                                         : declName.parent.expression;
41699                                 break;
41700                             case 0 /* None */:
41701                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
41702                         }
41703                         if (container) {
41704                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
41705                         }
41706                         container = oldContainer;
41707                     }
41708                 }
41709                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 78 /* Identifier */) {
41710                     parent = typeAlias.parent;
41711                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
41712                 }
41713                 else {
41714                     bind(typeAlias.fullName);
41715                 }
41716             }
41717             container = saveContainer;
41718             lastContainer = saveLastContainer;
41719             blockScopeContainer = saveBlockScopeContainer;
41720             parent = saveParent;
41721             currentFlow = saveCurrentFlow;
41722         }
41723         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
41724         // check for reserved words used as identifiers in strict mode code, as well as `yield` or `await` in
41725         // [Yield] or [Await] contexts, respectively.
41726         function checkContextualIdentifier(node) {
41727             // Report error only if there are no parse errors in file
41728             if (!file.parseDiagnostics.length &&
41729                 !(node.flags & 8388608 /* Ambient */) &&
41730                 !(node.flags & 4194304 /* JSDoc */) &&
41731                 !ts.isIdentifierName(node)) {
41732                 // strict mode identifiers
41733                 if (inStrictMode &&
41734                     node.originalKeywordKind >= 116 /* FirstFutureReservedWord */ &&
41735                     node.originalKeywordKind <= 124 /* LastFutureReservedWord */) {
41736                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
41737                 }
41738                 else if (node.originalKeywordKind === 130 /* AwaitKeyword */) {
41739                     if (ts.isExternalModule(file) && ts.isInTopLevelContext(node)) {
41740                         file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, ts.declarationNameToString(node)));
41741                     }
41742                     else if (node.flags & 32768 /* AwaitContext */) {
41743                         file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
41744                     }
41745                 }
41746                 else if (node.originalKeywordKind === 124 /* YieldKeyword */ && node.flags & 8192 /* YieldContext */) {
41747                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
41748                 }
41749             }
41750         }
41751         function getStrictModeIdentifierMessage(node) {
41752             // Provide specialized messages to help the user understand why we think they're in
41753             // strict mode.
41754             if (ts.getContainingClass(node)) {
41755                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
41756             }
41757             if (file.externalModuleIndicator) {
41758                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
41759             }
41760             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
41761         }
41762         // The binder visits every node, so this is a good place to check for
41763         // the reserved private name (there is only one)
41764         function checkPrivateIdentifier(node) {
41765             if (node.escapedText === "#constructor") {
41766                 // Report error only if there are no parse errors in file
41767                 if (!file.parseDiagnostics.length) {
41768                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
41769                 }
41770             }
41771         }
41772         function checkStrictModeBinaryExpression(node) {
41773             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
41774                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
41775                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
41776                 checkStrictModeEvalOrArguments(node, node.left);
41777             }
41778         }
41779         function checkStrictModeCatchClause(node) {
41780             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
41781             // Catch production is eval or arguments
41782             if (inStrictMode && node.variableDeclaration) {
41783                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
41784             }
41785         }
41786         function checkStrictModeDeleteExpression(node) {
41787             // Grammar checking
41788             if (inStrictMode && node.expression.kind === 78 /* Identifier */) {
41789                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
41790                 // UnaryExpression is a direct reference to a variable, function argument, or function name
41791                 var span = ts.getErrorSpanForNode(file, node.expression);
41792                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
41793             }
41794         }
41795         function isEvalOrArgumentsIdentifier(node) {
41796             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
41797         }
41798         function checkStrictModeEvalOrArguments(contextNode, name) {
41799             if (name && name.kind === 78 /* Identifier */) {
41800                 var identifier = name;
41801                 if (isEvalOrArgumentsIdentifier(identifier)) {
41802                     // We check first if the name is inside class declaration or class expression; if so give explicit message
41803                     // otherwise report generic error message.
41804                     var span = ts.getErrorSpanForNode(file, name);
41805                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
41806                 }
41807             }
41808         }
41809         function getStrictModeEvalOrArgumentsMessage(node) {
41810             // Provide specialized messages to help the user understand why we think they're in
41811             // strict mode.
41812             if (ts.getContainingClass(node)) {
41813                 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
41814             }
41815             if (file.externalModuleIndicator) {
41816                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
41817             }
41818             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
41819         }
41820         function checkStrictModeFunctionName(node) {
41821             if (inStrictMode) {
41822                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
41823                 checkStrictModeEvalOrArguments(node, node.name);
41824             }
41825         }
41826         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
41827             // Provide specialized messages to help the user understand why we think they're in
41828             // strict mode.
41829             if (ts.getContainingClass(node)) {
41830                 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;
41831             }
41832             if (file.externalModuleIndicator) {
41833                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
41834             }
41835             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
41836         }
41837         function checkStrictModeFunctionDeclaration(node) {
41838             if (languageVersion < 2 /* ES2015 */) {
41839                 // Report error if function is not top level function declaration
41840                 if (blockScopeContainer.kind !== 297 /* SourceFile */ &&
41841                     blockScopeContainer.kind !== 256 /* ModuleDeclaration */ &&
41842                     !ts.isFunctionLike(blockScopeContainer)) {
41843                     // We check first if the name is inside class declaration or class expression; if so give explicit message
41844                     // otherwise report generic error message.
41845                     var errorSpan = ts.getErrorSpanForNode(file, node);
41846                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
41847                 }
41848             }
41849         }
41850         function checkStrictModeNumericLiteral(node) {
41851             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
41852                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
41853             }
41854         }
41855         function checkStrictModePostfixUnaryExpression(node) {
41856             // Grammar checking
41857             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
41858             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
41859             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
41860             if (inStrictMode) {
41861                 checkStrictModeEvalOrArguments(node, node.operand);
41862             }
41863         }
41864         function checkStrictModePrefixUnaryExpression(node) {
41865             // Grammar checking
41866             if (inStrictMode) {
41867                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
41868                     checkStrictModeEvalOrArguments(node, node.operand);
41869                 }
41870             }
41871         }
41872         function checkStrictModeWithStatement(node) {
41873             // Grammar checking for withStatement
41874             if (inStrictMode) {
41875                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
41876             }
41877         }
41878         function checkStrictModeLabeledStatement(node) {
41879             // Grammar checking for labeledStatement
41880             if (inStrictMode && options.target >= 2 /* ES2015 */) {
41881                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
41882                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
41883                 }
41884             }
41885         }
41886         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
41887             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
41888             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
41889         }
41890         function errorOrSuggestionOnNode(isError, node, message) {
41891             errorOrSuggestionOnRange(isError, node, node, message);
41892         }
41893         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
41894             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
41895         }
41896         function addErrorOrSuggestionDiagnostic(isError, range, message) {
41897             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
41898             if (isError) {
41899                 file.bindDiagnostics.push(diag);
41900             }
41901             else {
41902                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
41903             }
41904         }
41905         function bind(node) {
41906             if (!node) {
41907                 return;
41908             }
41909             ts.setParent(node, parent);
41910             var saveInStrictMode = inStrictMode;
41911             // Even though in the AST the jsdoc @typedef node belongs to the current node,
41912             // its symbol might be in the same scope with the current node's symbol. Consider:
41913             //
41914             //     /** @typedef {string | number} MyType */
41915             //     function foo();
41916             //
41917             // Here the current node is "foo", which is a container, but the scope of "MyType" should
41918             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
41919             // and skip binding this tag later when binding all the other jsdoc tags.
41920             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
41921             // and then potentially add the symbol to an appropriate symbol table. Possible
41922             // destination symbol tables are:
41923             //
41924             //  1) The 'exports' table of the current container's symbol.
41925             //  2) The 'members' table of the current container's symbol.
41926             //  3) The 'locals' table of the current container.
41927             //
41928             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
41929             // (like TypeLiterals for example) will not be put in any table.
41930             bindWorker(node);
41931             // Then we recurse into the children of the node to bind them as well. For certain
41932             // symbols we do specialized work when we recurse. For example, we'll keep track of
41933             // the current 'container' node when it changes. This helps us know which symbol table
41934             // a local should go into for example. Since terminal nodes are known not to have
41935             // children, as an optimization we don't process those.
41936             if (node.kind > 156 /* LastToken */) {
41937                 var saveParent = parent;
41938                 parent = node;
41939                 var containerFlags = getContainerFlags(node);
41940                 if (containerFlags === 0 /* None */) {
41941                     bindChildren(node);
41942                 }
41943                 else {
41944                     bindContainer(node, containerFlags);
41945                 }
41946                 parent = saveParent;
41947             }
41948             else {
41949                 var saveParent = parent;
41950                 if (node.kind === 1 /* EndOfFileToken */)
41951                     parent = node;
41952                 bindJSDoc(node);
41953                 parent = saveParent;
41954             }
41955             inStrictMode = saveInStrictMode;
41956         }
41957         function bindJSDoc(node) {
41958             if (ts.hasJSDocNodes(node)) {
41959                 if (ts.isInJSFile(node)) {
41960                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
41961                         var j = _a[_i];
41962                         bind(j);
41963                     }
41964                 }
41965                 else {
41966                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
41967                         var j = _c[_b];
41968                         ts.setParent(j, node);
41969                         ts.setParentRecursive(j, /*incremental*/ false);
41970                     }
41971                 }
41972             }
41973         }
41974         function updateStrictModeStatementList(statements) {
41975             if (!inStrictMode) {
41976                 for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
41977                     var statement = statements_3[_i];
41978                     if (!ts.isPrologueDirective(statement)) {
41979                         return;
41980                     }
41981                     if (isUseStrictPrologueDirective(statement)) {
41982                         inStrictMode = true;
41983                         return;
41984                     }
41985                 }
41986             }
41987         }
41988         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
41989         function isUseStrictPrologueDirective(node) {
41990             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
41991             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
41992             // string to contain unicode escapes (as per ES5).
41993             return nodeText === '"use strict"' || nodeText === "'use strict'";
41994         }
41995         function bindWorker(node) {
41996             switch (node.kind) {
41997                 /* Strict mode checks */
41998                 case 78 /* Identifier */:
41999                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
42000                     // because it requires all containing namespaces to be in effect, namely the
42001                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
42002                     if (node.isInJSDocNamespace) {
42003                         var parentNode = node.parent;
42004                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
42005                             parentNode = parentNode.parent;
42006                         }
42007                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
42008                         break;
42009                     }
42010                 // falls through
42011                 case 107 /* ThisKeyword */:
42012                     if (currentFlow && (ts.isExpression(node) || parent.kind === 289 /* ShorthandPropertyAssignment */)) {
42013                         node.flowNode = currentFlow;
42014                     }
42015                     return checkContextualIdentifier(node);
42016                 case 105 /* SuperKeyword */:
42017                     node.flowNode = currentFlow;
42018                     break;
42019                 case 79 /* PrivateIdentifier */:
42020                     return checkPrivateIdentifier(node);
42021                 case 201 /* PropertyAccessExpression */:
42022                 case 202 /* ElementAccessExpression */:
42023                     var expr = node;
42024                     if (currentFlow && isNarrowableReference(expr)) {
42025                         expr.flowNode = currentFlow;
42026                     }
42027                     if (ts.isSpecialPropertyDeclaration(expr)) {
42028                         bindSpecialPropertyDeclaration(expr);
42029                     }
42030                     if (ts.isInJSFile(expr) &&
42031                         file.commonJsModuleIndicator &&
42032                         ts.isModuleExportsAccessExpression(expr) &&
42033                         !lookupSymbolForName(blockScopeContainer, "module")) {
42034                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
42035                     }
42036                     break;
42037                 case 216 /* BinaryExpression */:
42038                     var specialKind = ts.getAssignmentDeclarationKind(node);
42039                     switch (specialKind) {
42040                         case 1 /* ExportsProperty */:
42041                             bindExportsPropertyAssignment(node);
42042                             break;
42043                         case 2 /* ModuleExports */:
42044                             bindModuleExportsAssignment(node);
42045                             break;
42046                         case 3 /* PrototypeProperty */:
42047                             bindPrototypePropertyAssignment(node.left, node);
42048                             break;
42049                         case 6 /* Prototype */:
42050                             bindPrototypeAssignment(node);
42051                             break;
42052                         case 4 /* ThisProperty */:
42053                             bindThisPropertyAssignment(node);
42054                             break;
42055                         case 5 /* Property */:
42056                             var expression = node.left.expression;
42057                             if (ts.isInJSFile(node) && ts.isIdentifier(expression)) {
42058                                 var symbol = lookupSymbolForName(blockScopeContainer, expression.escapedText);
42059                                 if (ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration)) {
42060                                     bindThisPropertyAssignment(node);
42061                                     break;
42062                                 }
42063                             }
42064                             bindSpecialPropertyAssignment(node);
42065                             break;
42066                         case 0 /* None */:
42067                             // Nothing to do
42068                             break;
42069                         default:
42070                             ts.Debug.fail("Unknown binary expression special property assignment kind");
42071                     }
42072                     return checkStrictModeBinaryExpression(node);
42073                 case 287 /* CatchClause */:
42074                     return checkStrictModeCatchClause(node);
42075                 case 210 /* DeleteExpression */:
42076                     return checkStrictModeDeleteExpression(node);
42077                 case 8 /* NumericLiteral */:
42078                     return checkStrictModeNumericLiteral(node);
42079                 case 215 /* PostfixUnaryExpression */:
42080                     return checkStrictModePostfixUnaryExpression(node);
42081                 case 214 /* PrefixUnaryExpression */:
42082                     return checkStrictModePrefixUnaryExpression(node);
42083                 case 243 /* WithStatement */:
42084                     return checkStrictModeWithStatement(node);
42085                 case 245 /* LabeledStatement */:
42086                     return checkStrictModeLabeledStatement(node);
42087                 case 187 /* ThisType */:
42088                     seenThisKeyword = true;
42089                     return;
42090                 case 172 /* TypePredicate */:
42091                     break; // Binding the children will handle everything
42092                 case 159 /* TypeParameter */:
42093                     return bindTypeParameter(node);
42094                 case 160 /* Parameter */:
42095                     return bindParameter(node);
42096                 case 249 /* VariableDeclaration */:
42097                     return bindVariableDeclarationOrBindingElement(node);
42098                 case 198 /* BindingElement */:
42099                     node.flowNode = currentFlow;
42100                     return bindVariableDeclarationOrBindingElement(node);
42101                 case 163 /* PropertyDeclaration */:
42102                 case 162 /* PropertySignature */:
42103                     return bindPropertyWorker(node);
42104                 case 288 /* PropertyAssignment */:
42105                 case 289 /* ShorthandPropertyAssignment */:
42106                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
42107                 case 291 /* EnumMember */:
42108                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
42109                 case 169 /* CallSignature */:
42110                 case 170 /* ConstructSignature */:
42111                 case 171 /* IndexSignature */:
42112                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
42113                 case 165 /* MethodDeclaration */:
42114                 case 164 /* MethodSignature */:
42115                     // If this is an ObjectLiteralExpression method, then it sits in the same space
42116                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
42117                     // so that it will conflict with any other object literal members with the same
42118                     // name.
42119                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
42120                 case 251 /* FunctionDeclaration */:
42121                     return bindFunctionDeclaration(node);
42122                 case 166 /* Constructor */:
42123                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
42124                 case 167 /* GetAccessor */:
42125                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
42126                 case 168 /* SetAccessor */:
42127                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
42128                 case 174 /* FunctionType */:
42129                 case 308 /* JSDocFunctionType */:
42130                 case 313 /* JSDocSignature */:
42131                 case 175 /* ConstructorType */:
42132                     return bindFunctionOrConstructorType(node);
42133                 case 177 /* TypeLiteral */:
42134                 case 312 /* JSDocTypeLiteral */:
42135                 case 190 /* MappedType */:
42136                     return bindAnonymousTypeWorker(node);
42137                 case 319 /* JSDocClassTag */:
42138                     return bindJSDocClassTag(node);
42139                 case 200 /* ObjectLiteralExpression */:
42140                     return bindObjectLiteralExpression(node);
42141                 case 208 /* FunctionExpression */:
42142                 case 209 /* ArrowFunction */:
42143                     return bindFunctionExpression(node);
42144                 case 203 /* CallExpression */:
42145                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
42146                     switch (assignmentKind) {
42147                         case 7 /* ObjectDefinePropertyValue */:
42148                             return bindObjectDefinePropertyAssignment(node);
42149                         case 8 /* ObjectDefinePropertyExports */:
42150                             return bindObjectDefinePropertyExport(node);
42151                         case 9 /* ObjectDefinePrototypeProperty */:
42152                             return bindObjectDefinePrototypeProperty(node);
42153                         case 0 /* None */:
42154                             break; // Nothing to do
42155                         default:
42156                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
42157                     }
42158                     if (ts.isInJSFile(node)) {
42159                         bindCallExpression(node);
42160                     }
42161                     break;
42162                 // Members of classes, interfaces, and modules
42163                 case 221 /* ClassExpression */:
42164                 case 252 /* ClassDeclaration */:
42165                     // All classes are automatically in strict mode in ES6.
42166                     inStrictMode = true;
42167                     return bindClassLikeDeclaration(node);
42168                 case 253 /* InterfaceDeclaration */:
42169                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
42170                 case 254 /* TypeAliasDeclaration */:
42171                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
42172                 case 255 /* EnumDeclaration */:
42173                     return bindEnumDeclaration(node);
42174                 case 256 /* ModuleDeclaration */:
42175                     return bindModuleDeclaration(node);
42176                 // Jsx-attributes
42177                 case 281 /* JsxAttributes */:
42178                     return bindJsxAttributes(node);
42179                 case 280 /* JsxAttribute */:
42180                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
42181                 // Imports and exports
42182                 case 260 /* ImportEqualsDeclaration */:
42183                 case 263 /* NamespaceImport */:
42184                 case 265 /* ImportSpecifier */:
42185                 case 270 /* ExportSpecifier */:
42186                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42187                 case 259 /* NamespaceExportDeclaration */:
42188                     return bindNamespaceExportDeclaration(node);
42189                 case 262 /* ImportClause */:
42190                     return bindImportClause(node);
42191                 case 267 /* ExportDeclaration */:
42192                     return bindExportDeclaration(node);
42193                 case 266 /* ExportAssignment */:
42194                     return bindExportAssignment(node);
42195                 case 297 /* SourceFile */:
42196                     updateStrictModeStatementList(node.statements);
42197                     return bindSourceFileIfExternalModule();
42198                 case 230 /* Block */:
42199                     if (!ts.isFunctionLike(node.parent)) {
42200                         return;
42201                     }
42202                 // falls through
42203                 case 257 /* ModuleBlock */:
42204                     return updateStrictModeStatementList(node.statements);
42205                 case 326 /* JSDocParameterTag */:
42206                     if (node.parent.kind === 313 /* JSDocSignature */) {
42207                         return bindParameter(node);
42208                     }
42209                     if (node.parent.kind !== 312 /* JSDocTypeLiteral */) {
42210                         break;
42211                     }
42212                 // falls through
42213                 case 333 /* JSDocPropertyTag */:
42214                     var propTag = node;
42215                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 307 /* JSDocOptionalType */ ?
42216                         4 /* Property */ | 16777216 /* Optional */ :
42217                         4 /* Property */;
42218                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
42219                 case 331 /* JSDocTypedefTag */:
42220                 case 324 /* JSDocCallbackTag */:
42221                 case 325 /* JSDocEnumTag */:
42222                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
42223             }
42224         }
42225         function bindPropertyWorker(node) {
42226             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
42227         }
42228         function bindAnonymousTypeWorker(node) {
42229             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
42230         }
42231         function bindSourceFileIfExternalModule() {
42232             setExportContextFlag(file);
42233             if (ts.isExternalModule(file)) {
42234                 bindSourceFileAsExternalModule();
42235             }
42236             else if (ts.isJsonSourceFile(file)) {
42237                 bindSourceFileAsExternalModule();
42238                 // Create symbol equivalent for the module.exports = {}
42239                 var originalSymbol = file.symbol;
42240                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
42241                 file.symbol = originalSymbol;
42242             }
42243         }
42244         function bindSourceFileAsExternalModule() {
42245             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
42246         }
42247         function bindExportAssignment(node) {
42248             if (!container.symbol || !container.symbol.exports) {
42249                 // Export assignment in some sort of block construct
42250                 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
42251             }
42252             else {
42253                 var flags = ts.exportAssignmentIsAlias(node)
42254                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
42255                     ? 2097152 /* Alias */
42256                     // An export default clause with any other expression exports a value
42257                     : 4 /* Property */;
42258                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
42259                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
42260                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
42261                 if (node.isExportEquals) {
42262                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
42263                     ts.setValueDeclaration(symbol, node);
42264                 }
42265             }
42266         }
42267         function bindNamespaceExportDeclaration(node) {
42268             if (node.modifiers && node.modifiers.length) {
42269                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
42270             }
42271             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
42272                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
42273                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
42274                         : undefined;
42275             if (diag) {
42276                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
42277             }
42278             else {
42279                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
42280                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42281             }
42282         }
42283         function bindExportDeclaration(node) {
42284             if (!container.symbol || !container.symbol.exports) {
42285                 // Export * in some sort of block construct
42286                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
42287             }
42288             else if (!node.exportClause) {
42289                 // All export * declarations are collected in an __export symbol
42290                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
42291             }
42292             else if (ts.isNamespaceExport(node.exportClause)) {
42293                 // declareSymbol walks up parents to find name text, parent _must_ be set
42294                 // but won't be set by the normal binder walk until `bindChildren` later on.
42295                 ts.setParent(node.exportClause, node);
42296                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42297             }
42298         }
42299         function bindImportClause(node) {
42300             if (node.name) {
42301                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42302             }
42303         }
42304         function setCommonJsModuleIndicator(node) {
42305             if (file.externalModuleIndicator) {
42306                 return false;
42307             }
42308             if (!file.commonJsModuleIndicator) {
42309                 file.commonJsModuleIndicator = node;
42310                 bindSourceFileAsExternalModule();
42311             }
42312             return true;
42313         }
42314         function bindObjectDefinePropertyExport(node) {
42315             if (!setCommonJsModuleIndicator(node)) {
42316                 return;
42317             }
42318             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
42319                 if (symbol) {
42320                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
42321                 }
42322                 return symbol;
42323             });
42324             if (symbol) {
42325                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
42326                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
42327             }
42328         }
42329         function bindExportsPropertyAssignment(node) {
42330             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
42331             // expression is the declaration
42332             if (!setCommonJsModuleIndicator(node)) {
42333                 return;
42334             }
42335             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
42336                 if (symbol) {
42337                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
42338                 }
42339                 return symbol;
42340             });
42341             if (symbol) {
42342                 var isAlias = ts.isAliasableExpression(node.right) && (ts.isExportsIdentifier(node.left.expression) || ts.isModuleExportsAccessExpression(node.left.expression));
42343                 var flags = isAlias ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */;
42344                 ts.setParent(node.left, node);
42345                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
42346             }
42347         }
42348         function bindModuleExportsAssignment(node) {
42349             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
42350             // is still pointing to 'module.exports'.
42351             // We do not want to consider this as 'export=' since a module can have only one of these.
42352             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
42353             if (!setCommonJsModuleIndicator(node)) {
42354                 return;
42355             }
42356             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
42357             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
42358                 return;
42359             }
42360             if (ts.isObjectLiteralExpression(assignedExpression) && ts.every(assignedExpression.properties, ts.isShorthandPropertyAssignment)) {
42361                 ts.forEach(assignedExpression.properties, bindExportAssignedObjectMemberAlias);
42362                 return;
42363             }
42364             // 'module.exports = expr' assignment
42365             var flags = ts.exportAssignmentIsAlias(node)
42366                 ? 2097152 /* Alias */
42367                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
42368             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
42369             ts.setValueDeclaration(symbol, node);
42370         }
42371         function bindExportAssignedObjectMemberAlias(node) {
42372             declareSymbol(file.symbol.exports, file.symbol, node, 2097152 /* Alias */ | 67108864 /* Assignment */, 0 /* None */);
42373         }
42374         function bindThisPropertyAssignment(node) {
42375             ts.Debug.assert(ts.isInJSFile(node));
42376             // private identifiers *must* be declared (even in JS files)
42377             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
42378                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
42379             if (hasPrivateIdentifier) {
42380                 return;
42381             }
42382             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
42383             switch (thisContainer.kind) {
42384                 case 251 /* FunctionDeclaration */:
42385                 case 208 /* FunctionExpression */:
42386                     var constructorSymbol = thisContainer.symbol;
42387                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
42388                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
42389                         var l = thisContainer.parent.left;
42390                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
42391                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
42392                         }
42393                     }
42394                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
42395                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
42396                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
42397                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
42398                         if (ts.hasDynamicName(node)) {
42399                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
42400                         }
42401                         else {
42402                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
42403                         }
42404                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
42405                     }
42406                     break;
42407                 case 166 /* Constructor */:
42408                 case 163 /* PropertyDeclaration */:
42409                 case 165 /* MethodDeclaration */:
42410                 case 167 /* GetAccessor */:
42411                 case 168 /* SetAccessor */:
42412                     // this.foo assignment in a JavaScript class
42413                     // Bind this property to the containing class
42414                     var containingClass = thisContainer.parent;
42415                     var symbolTable = ts.hasSyntacticModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
42416                     if (ts.hasDynamicName(node)) {
42417                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
42418                     }
42419                     else {
42420                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
42421                     }
42422                     break;
42423                 case 297 /* SourceFile */:
42424                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
42425                     if (ts.hasDynamicName(node)) {
42426                         break;
42427                     }
42428                     else if (thisContainer.commonJsModuleIndicator) {
42429                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
42430                     }
42431                     else {
42432                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
42433                     }
42434                     break;
42435                 default:
42436                     ts.Debug.failBadSyntaxKind(thisContainer);
42437             }
42438         }
42439         function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
42440             bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
42441             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
42442         }
42443         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
42444             if (symbol) {
42445                 (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = new ts.Map())).set(ts.getNodeId(node), node);
42446             }
42447         }
42448         function bindSpecialPropertyDeclaration(node) {
42449             if (node.expression.kind === 107 /* ThisKeyword */) {
42450                 bindThisPropertyAssignment(node);
42451             }
42452             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 297 /* SourceFile */) {
42453                 if (ts.isPrototypeAccess(node.expression)) {
42454                     bindPrototypePropertyAssignment(node, node.parent);
42455                 }
42456                 else {
42457                     bindStaticPropertyAssignment(node);
42458                 }
42459             }
42460         }
42461         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
42462         function bindPrototypeAssignment(node) {
42463             ts.setParent(node.left, node);
42464             ts.setParent(node.right, node);
42465             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
42466         }
42467         function bindObjectDefinePrototypeProperty(node) {
42468             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
42469             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
42470                 // Ensure the namespace symbol becomes class-like
42471                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
42472             }
42473             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
42474         }
42475         /**
42476          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
42477          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
42478          */
42479         function bindPrototypePropertyAssignment(lhs, parent) {
42480             // Look up the function in the local scope, since prototype assignments should
42481             // follow the function declaration
42482             var classPrototype = lhs.expression;
42483             var constructorFunction = classPrototype.expression;
42484             // Fix up parent pointers since we're going to use these nodes before we bind into them
42485             ts.setParent(constructorFunction, classPrototype);
42486             ts.setParent(classPrototype, lhs);
42487             ts.setParent(lhs, parent);
42488             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
42489         }
42490         function bindObjectDefinePropertyAssignment(node) {
42491             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
42492             var isToplevel = node.parent.parent.kind === 297 /* SourceFile */;
42493             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
42494             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
42495         }
42496         function bindSpecialPropertyAssignment(node) {
42497             var _a;
42498             // Class declarations in Typescript do not allow property declarations
42499             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer);
42500             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
42501                 return;
42502             }
42503             var rootExpr = ts.getLeftmostAccessExpression(node.left);
42504             if (ts.isIdentifier(rootExpr) && ((_a = lookupSymbolForName(container, rootExpr.escapedText)) === null || _a === void 0 ? void 0 : _a.flags) & 2097152 /* Alias */) {
42505                 return;
42506             }
42507             // Fix up parent pointers since we're going to use these nodes before we bind into them
42508             ts.setParent(node.left, node);
42509             ts.setParent(node.right, node);
42510             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
42511                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
42512                 //    var util = module.exports;
42513                 //    util.property = function ...
42514                 bindExportsPropertyAssignment(node);
42515             }
42516             else if (ts.hasDynamicName(node)) {
42517                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
42518                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
42519                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
42520             }
42521             else {
42522                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
42523             }
42524         }
42525         /**
42526          * 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.
42527          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
42528          */
42529         function bindStaticPropertyAssignment(node) {
42530             ts.Debug.assert(!ts.isIdentifier(node));
42531             ts.setParent(node.expression, node);
42532             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
42533         }
42534         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
42535             if ((namespaceSymbol === null || namespaceSymbol === void 0 ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) {
42536                 return namespaceSymbol;
42537             }
42538             if (isToplevel && !isPrototypeProperty) {
42539                 // make symbols or add declarations for intermediate containers
42540                 var flags_2 = 1536 /* Module */ | 67108864 /* Assignment */;
42541                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
42542                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
42543                     if (symbol) {
42544                         addDeclarationToSymbol(symbol, id, flags_2);
42545                         return symbol;
42546                     }
42547                     else {
42548                         var table = parent ? parent.exports :
42549                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
42550                         return declareSymbol(table, parent, id, flags_2, excludeFlags_1);
42551                     }
42552                 });
42553             }
42554             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
42555                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
42556             }
42557             return namespaceSymbol;
42558         }
42559         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
42560             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
42561                 return;
42562             }
42563             // Set up the members collection if it doesn't exist already
42564             var symbolTable = isPrototypeProperty ?
42565                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
42566                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
42567             var includes = 0 /* None */;
42568             var excludes = 0 /* None */;
42569             // Method-like
42570             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
42571                 includes = 8192 /* Method */;
42572                 excludes = 103359 /* MethodExcludes */;
42573             }
42574             // Maybe accessor-like
42575             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
42576                 if (ts.some(declaration.arguments[2].properties, function (p) {
42577                     var id = ts.getNameOfDeclaration(p);
42578                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
42579                 })) {
42580                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
42581                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
42582                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
42583                     excludes |= 78783 /* SetAccessorExcludes */;
42584                 }
42585                 if (ts.some(declaration.arguments[2].properties, function (p) {
42586                     var id = ts.getNameOfDeclaration(p);
42587                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
42588                 })) {
42589                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
42590                     excludes |= 46015 /* GetAccessorExcludes */;
42591                 }
42592             }
42593             if (includes === 0 /* None */) {
42594                 includes = 4 /* Property */;
42595                 excludes = 0 /* PropertyExcludes */;
42596             }
42597             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
42598         }
42599         function isTopLevelNamespaceAssignment(propertyAccess) {
42600             return ts.isBinaryExpression(propertyAccess.parent)
42601                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 297 /* SourceFile */
42602                 : propertyAccess.parent.parent.kind === 297 /* SourceFile */;
42603         }
42604         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
42605             var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer);
42606             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
42607             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
42608             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
42609         }
42610         /**
42611          * Javascript expando values are:
42612          * - Functions
42613          * - classes
42614          * - namespaces
42615          * - variables initialized with function expressions
42616          * -                       with class expressions
42617          * -                       with empty object literals
42618          * -                       with non-empty object literals if assigned to the prototype property
42619          */
42620         function isExpandoSymbol(symbol) {
42621             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
42622                 return true;
42623             }
42624             var node = symbol.valueDeclaration;
42625             if (node && ts.isCallExpression(node)) {
42626                 return !!ts.getAssignedExpandoInitializer(node);
42627             }
42628             var init = !node ? undefined :
42629                 ts.isVariableDeclaration(node) ? node.initializer :
42630                     ts.isBinaryExpression(node) ? node.right :
42631                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
42632                             undefined;
42633             init = init && ts.getRightMostAssignedExpression(init);
42634             if (init) {
42635                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
42636                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
42637             }
42638             return false;
42639         }
42640         function getParentOfBinaryExpression(expr) {
42641             while (ts.isBinaryExpression(expr.parent)) {
42642                 expr = expr.parent;
42643             }
42644             return expr.parent;
42645         }
42646         function lookupSymbolForPropertyAccess(node, lookupContainer) {
42647             if (lookupContainer === void 0) { lookupContainer = container; }
42648             if (ts.isIdentifier(node)) {
42649                 return lookupSymbolForName(lookupContainer, node.escapedText);
42650             }
42651             else {
42652                 var symbol = lookupSymbolForPropertyAccess(node.expression);
42653                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
42654             }
42655         }
42656         function forEachIdentifierInEntityName(e, parent, action) {
42657             if (isExportsOrModuleExportsOrAlias(file, e)) {
42658                 return file.symbol;
42659             }
42660             else if (ts.isIdentifier(e)) {
42661                 return action(e, lookupSymbolForPropertyAccess(e), parent);
42662             }
42663             else {
42664                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
42665                 var name = ts.getNameOrArgument(e);
42666                 // unreachable
42667                 if (ts.isPrivateIdentifier(name)) {
42668                     ts.Debug.fail("unexpected PrivateIdentifier");
42669                 }
42670                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
42671             }
42672         }
42673         function bindCallExpression(node) {
42674             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
42675             // this check if we've already seen the module indicator
42676             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
42677                 setCommonJsModuleIndicator(node);
42678             }
42679         }
42680         function bindClassLikeDeclaration(node) {
42681             if (node.kind === 252 /* ClassDeclaration */) {
42682                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
42683             }
42684             else {
42685                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
42686                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
42687                 // Add name of class expression into the map for semantic classifier
42688                 if (node.name) {
42689                     classifiableNames.add(node.name.escapedText);
42690                 }
42691             }
42692             var symbol = node.symbol;
42693             // TypeScript 1.0 spec (April 2014): 8.4
42694             // Every class automatically contains a static property member named 'prototype', the
42695             // type of which is an instantiation of the class type with type Any supplied as a type
42696             // argument for each type parameter. It is an error to explicitly declare a static
42697             // property member with the name 'prototype'.
42698             //
42699             // Note: we check for this here because this class may be merging into a module.  The
42700             // module might have an exported variable called 'prototype'.  We can't allow that as
42701             // that would clash with the built-in 'prototype' for the class.
42702             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
42703             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
42704             if (symbolExport) {
42705                 if (node.name) {
42706                     ts.setParent(node.name, node);
42707                 }
42708                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
42709             }
42710             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
42711             prototypeSymbol.parent = symbol;
42712         }
42713         function bindEnumDeclaration(node) {
42714             return ts.isEnumConst(node)
42715                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
42716                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
42717         }
42718         function bindVariableDeclarationOrBindingElement(node) {
42719             if (inStrictMode) {
42720                 checkStrictModeEvalOrArguments(node, node.name);
42721             }
42722             if (!ts.isBindingPattern(node.name)) {
42723                 if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) && !ts.getJSDocTypeTag(node)) {
42724                     declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42725                 }
42726                 else if (ts.isBlockOrCatchScoped(node)) {
42727                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
42728                 }
42729                 else if (ts.isParameterDeclaration(node)) {
42730                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
42731                     // because its parent chain has already been set up, since parents are set before descending into children.
42732                     //
42733                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
42734                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
42735                     // For example:
42736                     //      function foo([a,a]) {} // Duplicate Identifier error
42737                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
42738                     //                             // which correctly set excluded symbols
42739                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
42740                 }
42741                 else {
42742                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
42743                 }
42744             }
42745         }
42746         function bindParameter(node) {
42747             if (node.kind === 326 /* JSDocParameterTag */ && container.kind !== 313 /* JSDocSignature */) {
42748                 return;
42749             }
42750             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
42751                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
42752                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
42753                 checkStrictModeEvalOrArguments(node, node.name);
42754             }
42755             if (ts.isBindingPattern(node.name)) {
42756                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
42757             }
42758             else {
42759                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
42760             }
42761             // If this is a property-parameter, then also declare the property symbol into the
42762             // containing class.
42763             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
42764                 var classDeclaration = node.parent.parent;
42765                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
42766             }
42767         }
42768         function bindFunctionDeclaration(node) {
42769             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
42770                 if (ts.isAsyncFunction(node)) {
42771                     emitFlags |= 2048 /* HasAsyncFunctions */;
42772                 }
42773             }
42774             checkStrictModeFunctionName(node);
42775             if (inStrictMode) {
42776                 checkStrictModeFunctionDeclaration(node);
42777                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
42778             }
42779             else {
42780                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
42781             }
42782         }
42783         function bindFunctionExpression(node) {
42784             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
42785                 if (ts.isAsyncFunction(node)) {
42786                     emitFlags |= 2048 /* HasAsyncFunctions */;
42787                 }
42788             }
42789             if (currentFlow) {
42790                 node.flowNode = currentFlow;
42791             }
42792             checkStrictModeFunctionName(node);
42793             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
42794             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
42795         }
42796         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
42797             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
42798                 emitFlags |= 2048 /* HasAsyncFunctions */;
42799             }
42800             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
42801                 node.flowNode = currentFlow;
42802             }
42803             return ts.hasDynamicName(node)
42804                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
42805                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
42806         }
42807         function getInferTypeContainer(node) {
42808             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
42809             return extendsType && extendsType.parent;
42810         }
42811         function bindTypeParameter(node) {
42812             if (ts.isJSDocTemplateTag(node.parent)) {
42813                 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
42814                 if (container_1) {
42815                     if (!container_1.locals) {
42816                         container_1.locals = ts.createSymbolTable();
42817                     }
42818                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
42819                 }
42820                 else {
42821                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
42822                 }
42823             }
42824             else if (node.parent.kind === 185 /* InferType */) {
42825                 var container_2 = getInferTypeContainer(node.parent);
42826                 if (container_2) {
42827                     if (!container_2.locals) {
42828                         container_2.locals = ts.createSymbolTable();
42829                     }
42830                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
42831                 }
42832                 else {
42833                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
42834                 }
42835             }
42836             else {
42837                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
42838             }
42839         }
42840         // reachability checks
42841         function shouldReportErrorOnModuleDeclaration(node) {
42842             var instanceState = getModuleInstanceState(node);
42843             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
42844         }
42845         function checkUnreachable(node) {
42846             if (!(currentFlow.flags & 1 /* Unreachable */)) {
42847                 return false;
42848             }
42849             if (currentFlow === unreachableFlow) {
42850                 var reportError = 
42851                 // report error on all statements except empty ones
42852                 (ts.isStatementButNotDeclaration(node) && node.kind !== 231 /* EmptyStatement */) ||
42853                     // report error on class declarations
42854                     node.kind === 252 /* ClassDeclaration */ ||
42855                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
42856                     (node.kind === 256 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
42857                 if (reportError) {
42858                     currentFlow = reportedUnreachableFlow;
42859                     if (!options.allowUnreachableCode) {
42860                         // unreachable code is reported if
42861                         // - user has explicitly asked about it AND
42862                         // - statement is in not ambient context (statements in ambient context is already an error
42863                         //   so we should not report extras) AND
42864                         //   - node is not variable statement OR
42865                         //   - node is block scoped variable statement OR
42866                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
42867                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
42868                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
42869                         var isError_1 = ts.unreachableCodeIsError(options) &&
42870                             !(node.flags & 8388608 /* Ambient */) &&
42871                             (!ts.isVariableStatement(node) ||
42872                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
42873                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
42874                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
42875                     }
42876                 }
42877             }
42878             return true;
42879         }
42880     }
42881     function eachUnreachableRange(node, cb) {
42882         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
42883             var statements = node.parent.statements;
42884             var slice_1 = ts.sliceAfter(statements, node);
42885             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
42886         }
42887         else {
42888             cb(node, node);
42889         }
42890     }
42891     // As opposed to a pure declaration like an `interface`
42892     function isExecutableStatement(s) {
42893         // Don't remove statements that can validly be used before they appear.
42894         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
42895             // `var x;` may declare a variable used above
42896             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
42897     }
42898     function isPurelyTypeDeclaration(s) {
42899         switch (s.kind) {
42900             case 253 /* InterfaceDeclaration */:
42901             case 254 /* TypeAliasDeclaration */:
42902                 return true;
42903             case 256 /* ModuleDeclaration */:
42904                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
42905             case 255 /* EnumDeclaration */:
42906                 return ts.hasSyntacticModifier(s, 2048 /* Const */);
42907             default:
42908                 return false;
42909         }
42910     }
42911     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
42912         var i = 0;
42913         var q = [node];
42914         while (q.length && i < 100) {
42915             i++;
42916             node = q.shift();
42917             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
42918                 return true;
42919             }
42920             else if (ts.isIdentifier(node)) {
42921                 var symbol = lookupSymbolForName(sourceFile, node.escapedText);
42922                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
42923                     var init = symbol.valueDeclaration.initializer;
42924                     q.push(init);
42925                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
42926                         q.push(init.left);
42927                         q.push(init.right);
42928                     }
42929                 }
42930             }
42931         }
42932         return false;
42933     }
42934     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
42935     function lookupSymbolForName(container, name) {
42936         var local = container.locals && container.locals.get(name);
42937         if (local) {
42938             return local.exportSymbol || local;
42939         }
42940         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
42941             return container.jsGlobalAugmentations.get(name);
42942         }
42943         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
42944     }
42945 })(ts || (ts = {}));
42946 /** @internal */
42947 var ts;
42948 (function (ts) {
42949     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
42950         return getSymbolWalker;
42951         function getSymbolWalker(accept) {
42952             if (accept === void 0) { accept = function () { return true; }; }
42953             var visitedTypes = []; // Sparse array from id to type
42954             var visitedSymbols = []; // Sparse array from id to symbol
42955             return {
42956                 walkType: function (type) {
42957                     try {
42958                         visitType(type);
42959                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
42960                     }
42961                     finally {
42962                         ts.clear(visitedTypes);
42963                         ts.clear(visitedSymbols);
42964                     }
42965                 },
42966                 walkSymbol: function (symbol) {
42967                     try {
42968                         visitSymbol(symbol);
42969                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
42970                     }
42971                     finally {
42972                         ts.clear(visitedTypes);
42973                         ts.clear(visitedSymbols);
42974                     }
42975                 },
42976             };
42977             function visitType(type) {
42978                 if (!type) {
42979                     return;
42980                 }
42981                 if (visitedTypes[type.id]) {
42982                     return;
42983                 }
42984                 visitedTypes[type.id] = type;
42985                 // Reuse visitSymbol to visit the type's symbol,
42986                 //  but be sure to bail on recuring into the type if accept declines the symbol.
42987                 var shouldBail = visitSymbol(type.symbol);
42988                 if (shouldBail)
42989                     return;
42990                 // Visit the type's related types, if any
42991                 if (type.flags & 524288 /* Object */) {
42992                     var objectType = type;
42993                     var objectFlags = objectType.objectFlags;
42994                     if (objectFlags & 4 /* Reference */) {
42995                         visitTypeReference(type);
42996                     }
42997                     if (objectFlags & 32 /* Mapped */) {
42998                         visitMappedType(type);
42999                     }
43000                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
43001                         visitInterfaceType(type);
43002                     }
43003                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
43004                         visitObjectType(objectType);
43005                     }
43006                 }
43007                 if (type.flags & 262144 /* TypeParameter */) {
43008                     visitTypeParameter(type);
43009                 }
43010                 if (type.flags & 3145728 /* UnionOrIntersection */) {
43011                     visitUnionOrIntersectionType(type);
43012                 }
43013                 if (type.flags & 4194304 /* Index */) {
43014                     visitIndexType(type);
43015                 }
43016                 if (type.flags & 8388608 /* IndexedAccess */) {
43017                     visitIndexedAccessType(type);
43018                 }
43019             }
43020             function visitTypeReference(type) {
43021                 visitType(type.target);
43022                 ts.forEach(getTypeArguments(type), visitType);
43023             }
43024             function visitTypeParameter(type) {
43025                 visitType(getConstraintOfTypeParameter(type));
43026             }
43027             function visitUnionOrIntersectionType(type) {
43028                 ts.forEach(type.types, visitType);
43029             }
43030             function visitIndexType(type) {
43031                 visitType(type.type);
43032             }
43033             function visitIndexedAccessType(type) {
43034                 visitType(type.objectType);
43035                 visitType(type.indexType);
43036                 visitType(type.constraint);
43037             }
43038             function visitMappedType(type) {
43039                 visitType(type.typeParameter);
43040                 visitType(type.constraintType);
43041                 visitType(type.templateType);
43042                 visitType(type.modifiersType);
43043             }
43044             function visitSignature(signature) {
43045                 var typePredicate = getTypePredicateOfSignature(signature);
43046                 if (typePredicate) {
43047                     visitType(typePredicate.type);
43048                 }
43049                 ts.forEach(signature.typeParameters, visitType);
43050                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
43051                     var parameter = _a[_i];
43052                     visitSymbol(parameter);
43053                 }
43054                 visitType(getRestTypeOfSignature(signature));
43055                 visitType(getReturnTypeOfSignature(signature));
43056             }
43057             function visitInterfaceType(interfaceT) {
43058                 visitObjectType(interfaceT);
43059                 ts.forEach(interfaceT.typeParameters, visitType);
43060                 ts.forEach(getBaseTypes(interfaceT), visitType);
43061                 visitType(interfaceT.thisType);
43062             }
43063             function visitObjectType(type) {
43064                 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
43065                 visitType(stringIndexType);
43066                 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
43067                 visitType(numberIndexType);
43068                 // The two checks above *should* have already resolved the type (if needed), so this should be cached
43069                 var resolved = resolveStructuredTypeMembers(type);
43070                 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
43071                     var signature = _a[_i];
43072                     visitSignature(signature);
43073                 }
43074                 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
43075                     var signature = _c[_b];
43076                     visitSignature(signature);
43077                 }
43078                 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
43079                     var p = _e[_d];
43080                     visitSymbol(p);
43081                 }
43082             }
43083             function visitSymbol(symbol) {
43084                 if (!symbol) {
43085                     return false;
43086                 }
43087                 var symbolId = ts.getSymbolId(symbol);
43088                 if (visitedSymbols[symbolId]) {
43089                     return false;
43090                 }
43091                 visitedSymbols[symbolId] = symbol;
43092                 if (!accept(symbol)) {
43093                     return true;
43094                 }
43095                 var t = getTypeOfSymbol(symbol);
43096                 visitType(t); // Should handle members on classes and such
43097                 if (symbol.exports) {
43098                     symbol.exports.forEach(visitSymbol);
43099                 }
43100                 ts.forEach(symbol.declarations, function (d) {
43101                     // Type queries are too far resolved when we just visit the symbol's type
43102                     //  (their type resolved directly to the member deeply referenced)
43103                     // So to get the intervening symbols, we need to check if there's a type
43104                     // query node on any of the symbol's declarations and get symbols there
43105                     if (d.type && d.type.kind === 176 /* TypeQuery */) {
43106                         var query = d.type;
43107                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
43108                         visitSymbol(entity);
43109                     }
43110                 });
43111                 return false;
43112             }
43113         }
43114     }
43115     ts.createGetSymbolWalker = createGetSymbolWalker;
43116 })(ts || (ts = {}));
43117 /* @internal */
43118 var ts;
43119 (function (ts) {
43120     var ambientModuleSymbolRegex = /^".+"$/;
43121     var anon = "(anonymous)";
43122     var nextSymbolId = 1;
43123     var nextNodeId = 1;
43124     var nextMergeId = 1;
43125     var nextFlowId = 1;
43126     var IterationUse;
43127     (function (IterationUse) {
43128         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
43129         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
43130         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
43131         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
43132         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
43133         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
43134         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
43135         IterationUse[IterationUse["PossiblyOutOfBounds"] = 128] = "PossiblyOutOfBounds";
43136         // Spread, Destructuring, Array element assignment
43137         IterationUse[IterationUse["Element"] = 1] = "Element";
43138         IterationUse[IterationUse["Spread"] = 33] = "Spread";
43139         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
43140         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
43141         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
43142         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
43143         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
43144         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
43145         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
43146     })(IterationUse || (IterationUse = {}));
43147     var IterationTypeKind;
43148     (function (IterationTypeKind) {
43149         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
43150         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
43151         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
43152     })(IterationTypeKind || (IterationTypeKind = {}));
43153     var WideningKind;
43154     (function (WideningKind) {
43155         WideningKind[WideningKind["Normal"] = 0] = "Normal";
43156         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
43157         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
43158         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
43159     })(WideningKind || (WideningKind = {}));
43160     var TypeFacts;
43161     (function (TypeFacts) {
43162         TypeFacts[TypeFacts["None"] = 0] = "None";
43163         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
43164         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
43165         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
43166         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
43167         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
43168         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
43169         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
43170         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
43171         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
43172         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
43173         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
43174         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
43175         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
43176         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
43177         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
43178         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
43179         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
43180         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
43181         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
43182         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
43183         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
43184         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
43185         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
43186         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
43187         TypeFacts[TypeFacts["All"] = 16777215] = "All";
43188         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
43189         // The presence of a particular fact means that the given test is true for some (and possibly all) values
43190         // of that kind of type.
43191         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
43192         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
43193         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
43194         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
43195         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
43196         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
43197         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
43198         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
43199         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
43200         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
43201         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
43202         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
43203         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
43204         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
43205         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
43206         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
43207         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
43208         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
43209         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
43210         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
43211         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
43212         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
43213         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
43214         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
43215         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
43216         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
43217         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
43218         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
43219         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
43220         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
43221         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
43222         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
43223         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
43224         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
43225         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
43226         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
43227         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
43228         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
43229         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
43230         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
43231         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
43232         TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE";
43233         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
43234     })(TypeFacts || (TypeFacts = {}));
43235     var typeofEQFacts = new ts.Map(ts.getEntries({
43236         string: 1 /* TypeofEQString */,
43237         number: 2 /* TypeofEQNumber */,
43238         bigint: 4 /* TypeofEQBigInt */,
43239         boolean: 8 /* TypeofEQBoolean */,
43240         symbol: 16 /* TypeofEQSymbol */,
43241         undefined: 65536 /* EQUndefined */,
43242         object: 32 /* TypeofEQObject */,
43243         function: 64 /* TypeofEQFunction */
43244     }));
43245     var typeofNEFacts = new ts.Map(ts.getEntries({
43246         string: 256 /* TypeofNEString */,
43247         number: 512 /* TypeofNENumber */,
43248         bigint: 1024 /* TypeofNEBigInt */,
43249         boolean: 2048 /* TypeofNEBoolean */,
43250         symbol: 4096 /* TypeofNESymbol */,
43251         undefined: 524288 /* NEUndefined */,
43252         object: 8192 /* TypeofNEObject */,
43253         function: 16384 /* TypeofNEFunction */
43254     }));
43255     var TypeSystemPropertyName;
43256     (function (TypeSystemPropertyName) {
43257         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
43258         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
43259         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
43260         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
43261         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
43262         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
43263         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
43264         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseTypes"] = 7] = "ResolvedBaseTypes";
43265     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
43266     var CheckMode;
43267     (function (CheckMode) {
43268         CheckMode[CheckMode["Normal"] = 0] = "Normal";
43269         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
43270         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
43271         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
43272         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
43273         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
43274     })(CheckMode || (CheckMode = {}));
43275     var AccessFlags;
43276     (function (AccessFlags) {
43277         AccessFlags[AccessFlags["None"] = 0] = "None";
43278         AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
43279         AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
43280         AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
43281         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
43282         AccessFlags[AccessFlags["ExpressionPosition"] = 16] = "ExpressionPosition";
43283     })(AccessFlags || (AccessFlags = {}));
43284     var SignatureCheckMode;
43285     (function (SignatureCheckMode) {
43286         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
43287         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
43288         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
43289         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
43290         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
43291     })(SignatureCheckMode || (SignatureCheckMode = {}));
43292     var IntersectionState;
43293     (function (IntersectionState) {
43294         IntersectionState[IntersectionState["None"] = 0] = "None";
43295         IntersectionState[IntersectionState["Source"] = 1] = "Source";
43296         IntersectionState[IntersectionState["Target"] = 2] = "Target";
43297         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
43298         IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
43299     })(IntersectionState || (IntersectionState = {}));
43300     var MappedTypeModifiers;
43301     (function (MappedTypeModifiers) {
43302         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
43303         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
43304         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
43305         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
43306     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
43307     var ExpandingFlags;
43308     (function (ExpandingFlags) {
43309         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
43310         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
43311         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
43312         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
43313     })(ExpandingFlags || (ExpandingFlags = {}));
43314     var MembersOrExportsResolutionKind;
43315     (function (MembersOrExportsResolutionKind) {
43316         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
43317         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
43318     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
43319     var UnusedKind;
43320     (function (UnusedKind) {
43321         UnusedKind[UnusedKind["Local"] = 0] = "Local";
43322         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
43323     })(UnusedKind || (UnusedKind = {}));
43324     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
43325     var DeclarationMeaning;
43326     (function (DeclarationMeaning) {
43327         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
43328         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
43329         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
43330         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
43331         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
43332         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
43333     })(DeclarationMeaning || (DeclarationMeaning = {}));
43334     var DeclarationSpaces;
43335     (function (DeclarationSpaces) {
43336         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
43337         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
43338         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
43339         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
43340     })(DeclarationSpaces || (DeclarationSpaces = {}));
43341     var MinArgumentCountFlags;
43342     (function (MinArgumentCountFlags) {
43343         MinArgumentCountFlags[MinArgumentCountFlags["None"] = 0] = "None";
43344         MinArgumentCountFlags[MinArgumentCountFlags["StrongArityForUntypedJS"] = 1] = "StrongArityForUntypedJS";
43345         MinArgumentCountFlags[MinArgumentCountFlags["VoidIsNonOptional"] = 2] = "VoidIsNonOptional";
43346     })(MinArgumentCountFlags || (MinArgumentCountFlags = {}));
43347     var IntrinsicTypeKind;
43348     (function (IntrinsicTypeKind) {
43349         IntrinsicTypeKind[IntrinsicTypeKind["Uppercase"] = 0] = "Uppercase";
43350         IntrinsicTypeKind[IntrinsicTypeKind["Lowercase"] = 1] = "Lowercase";
43351         IntrinsicTypeKind[IntrinsicTypeKind["Capitalize"] = 2] = "Capitalize";
43352         IntrinsicTypeKind[IntrinsicTypeKind["Uncapitalize"] = 3] = "Uncapitalize";
43353     })(IntrinsicTypeKind || (IntrinsicTypeKind = {}));
43354     var intrinsicTypeKinds = new ts.Map(ts.getEntries({
43355         Uppercase: 0 /* Uppercase */,
43356         Lowercase: 1 /* Lowercase */,
43357         Capitalize: 2 /* Capitalize */,
43358         Uncapitalize: 3 /* Uncapitalize */
43359     }));
43360     function SymbolLinks() {
43361     }
43362     function NodeLinks() {
43363         this.flags = 0;
43364     }
43365     function getNodeId(node) {
43366         if (!node.id) {
43367             node.id = nextNodeId;
43368             nextNodeId++;
43369         }
43370         return node.id;
43371     }
43372     ts.getNodeId = getNodeId;
43373     function getSymbolId(symbol) {
43374         if (!symbol.id) {
43375             symbol.id = nextSymbolId;
43376             nextSymbolId++;
43377         }
43378         return symbol.id;
43379     }
43380     ts.getSymbolId = getSymbolId;
43381     function isInstantiatedModule(node, preserveConstEnums) {
43382         var moduleState = ts.getModuleInstanceState(node);
43383         return moduleState === 1 /* Instantiated */ ||
43384             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
43385     }
43386     ts.isInstantiatedModule = isInstantiatedModule;
43387     function createTypeChecker(host, produceDiagnostics) {
43388         var getPackagesSet = ts.memoize(function () {
43389             var set = new ts.Set();
43390             host.getSourceFiles().forEach(function (sf) {
43391                 if (!sf.resolvedModules)
43392                     return;
43393                 ts.forEachEntry(sf.resolvedModules, function (r) {
43394                     if (r && r.packageId)
43395                         set.add(r.packageId.name);
43396                 });
43397             });
43398             return set;
43399         });
43400         // Cancellation that controls whether or not we can cancel in the middle of type checking.
43401         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
43402         // computing something, and we will leave our internals in an inconsistent state.  Callers
43403         // who set the cancellation token should catch if a cancellation exception occurs, and
43404         // should throw away and create a new TypeChecker.
43405         //
43406         // Currently we only support setting the cancellation token when getting diagnostics.  This
43407         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
43408         // they no longer need the information (for example, if the user started editing again).
43409         var cancellationToken;
43410         var requestedExternalEmitHelpers;
43411         var externalHelpersModule;
43412         var Symbol = ts.objectAllocator.getSymbolConstructor();
43413         var Type = ts.objectAllocator.getTypeConstructor();
43414         var Signature = ts.objectAllocator.getSignatureConstructor();
43415         var typeCount = 0;
43416         var symbolCount = 0;
43417         var enumCount = 0;
43418         var totalInstantiationCount = 0;
43419         var instantiationCount = 0;
43420         var instantiationDepth = 0;
43421         var constraintDepth = 0;
43422         var currentNode;
43423         var typeCatalog = []; // NB: id is index + 1
43424         var emptySymbols = ts.createSymbolTable();
43425         var arrayVariances = [1 /* Covariant */];
43426         var compilerOptions = host.getCompilerOptions();
43427         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
43428         var moduleKind = ts.getEmitModuleKind(compilerOptions);
43429         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
43430         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
43431         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
43432         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
43433         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
43434         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
43435         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
43436         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
43437         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
43438         var emitResolver = createResolver();
43439         var nodeBuilder = createNodeBuilder();
43440         var globals = ts.createSymbolTable();
43441         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
43442         undefinedSymbol.declarations = [];
43443         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
43444         globalThisSymbol.exports = globals;
43445         globalThisSymbol.declarations = [];
43446         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
43447         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
43448         var requireSymbol = createSymbol(4 /* Property */, "require");
43449         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
43450         var apparentArgumentCount;
43451         // for public members that accept a Node or one of its subtypes, we must guard against
43452         // synthetic nodes created during transformations by calling `getParseTreeNode`.
43453         // for most of these, we perform the guard only on `checker` to avoid any possible
43454         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
43455         // checker.
43456         var checker = {
43457             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
43458             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
43459             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
43460             getTypeCatalog: function () { return typeCatalog; },
43461             getTypeCount: function () { return typeCount; },
43462             getInstantiationCount: function () { return totalInstantiationCount; },
43463             getRelationCacheSizes: function () { return ({
43464                 assignable: assignableRelation.size,
43465                 identity: identityRelation.size,
43466                 subtype: subtypeRelation.size,
43467                 strictSubtype: strictSubtypeRelation.size,
43468             }); },
43469             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
43470             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
43471             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
43472             getMergedSymbol: getMergedSymbol,
43473             getDiagnostics: getDiagnostics,
43474             getGlobalDiagnostics: getGlobalDiagnostics,
43475             getRecursionIdentity: getRecursionIdentity,
43476             getTypeOfSymbolAtLocation: function (symbol, locationIn) {
43477                 var location = ts.getParseTreeNode(locationIn);
43478                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
43479             },
43480             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
43481                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
43482                 if (parameter === undefined)
43483                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
43484                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
43485             },
43486             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
43487             getPropertiesOfType: getPropertiesOfType,
43488             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
43489             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
43490                 var node = ts.getParseTreeNode(location);
43491                 if (!node) {
43492                     return undefined;
43493                 }
43494                 var propName = ts.escapeLeadingUnderscores(name);
43495                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
43496                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
43497             },
43498             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
43499             getIndexInfoOfType: getIndexInfoOfType,
43500             getSignaturesOfType: getSignaturesOfType,
43501             getIndexTypeOfType: getIndexTypeOfType,
43502             getBaseTypes: getBaseTypes,
43503             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
43504             getWidenedType: getWidenedType,
43505             getTypeFromTypeNode: function (nodeIn) {
43506                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
43507                 return node ? getTypeFromTypeNode(node) : errorType;
43508             },
43509             getParameterType: getTypeAtPosition,
43510             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
43511             getAwaitedType: function (type) { return getAwaitedType(type); },
43512             getReturnTypeOfSignature: getReturnTypeOfSignature,
43513             isNullableType: isNullableType,
43514             getNullableType: getNullableType,
43515             getNonNullableType: getNonNullableType,
43516             getNonOptionalType: removeOptionalTypeMarker,
43517             getTypeArguments: getTypeArguments,
43518             typeToTypeNode: nodeBuilder.typeToTypeNode,
43519             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
43520             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
43521             symbolToEntityName: nodeBuilder.symbolToEntityName,
43522             symbolToExpression: nodeBuilder.symbolToExpression,
43523             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
43524             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
43525             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
43526             getSymbolsInScope: function (locationIn, meaning) {
43527                 var location = ts.getParseTreeNode(locationIn);
43528                 return location ? getSymbolsInScope(location, meaning) : [];
43529             },
43530             getSymbolAtLocation: function (nodeIn) {
43531                 var node = ts.getParseTreeNode(nodeIn);
43532                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
43533                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
43534             },
43535             getShorthandAssignmentValueSymbol: function (nodeIn) {
43536                 var node = ts.getParseTreeNode(nodeIn);
43537                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
43538             },
43539             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
43540                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
43541                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
43542             },
43543             getExportSymbolOfSymbol: function (symbol) {
43544                 return getMergedSymbol(symbol.exportSymbol || symbol);
43545             },
43546             getTypeAtLocation: function (nodeIn) {
43547                 var node = ts.getParseTreeNode(nodeIn);
43548                 return node ? getTypeOfNode(node) : errorType;
43549             },
43550             getTypeOfAssignmentPattern: function (nodeIn) {
43551                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
43552                 return node && getTypeOfAssignmentPattern(node) || errorType;
43553             },
43554             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
43555                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
43556                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
43557             },
43558             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
43559                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
43560             },
43561             typeToString: function (type, enclosingDeclaration, flags) {
43562                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
43563             },
43564             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
43565                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
43566             },
43567             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
43568                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
43569             },
43570             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
43571                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
43572             },
43573             writeType: function (type, enclosingDeclaration, flags, writer) {
43574                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
43575             },
43576             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
43577                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
43578             },
43579             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
43580                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
43581             },
43582             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
43583             getRootSymbols: getRootSymbols,
43584             getSymbolOfExpando: getSymbolOfExpando,
43585             getContextualType: function (nodeIn, contextFlags) {
43586                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
43587                 if (!node) {
43588                     return undefined;
43589                 }
43590                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
43591                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
43592                 if (contextFlags & 4 /* Completions */ && containingCall) {
43593                     var toMarkSkip = node;
43594                     do {
43595                         getNodeLinks(toMarkSkip).skipDirectInference = true;
43596                         toMarkSkip = toMarkSkip.parent;
43597                     } while (toMarkSkip && toMarkSkip !== containingCall);
43598                     getNodeLinks(containingCall).resolvedSignature = undefined;
43599                 }
43600                 var result = getContextualType(node, contextFlags);
43601                 if (contextFlags & 4 /* Completions */ && containingCall) {
43602                     var toMarkSkip = node;
43603                     do {
43604                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
43605                         toMarkSkip = toMarkSkip.parent;
43606                     } while (toMarkSkip && toMarkSkip !== containingCall);
43607                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
43608                 }
43609                 return result;
43610             },
43611             getContextualTypeForObjectLiteralElement: function (nodeIn) {
43612                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
43613                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
43614             },
43615             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
43616                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
43617                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
43618             },
43619             getContextualTypeForJsxAttribute: function (nodeIn) {
43620                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
43621                 return node && getContextualTypeForJsxAttribute(node);
43622             },
43623             isContextSensitive: isContextSensitive,
43624             getFullyQualifiedName: getFullyQualifiedName,
43625             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
43626                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
43627             },
43628             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
43629                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
43630             },
43631             getExpandedParameters: getExpandedParameters,
43632             hasEffectiveRestParameter: hasEffectiveRestParameter,
43633             getConstantValue: function (nodeIn) {
43634                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
43635                 return node ? getConstantValue(node) : undefined;
43636             },
43637             isValidPropertyAccess: function (nodeIn, propertyName) {
43638                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
43639                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
43640             },
43641             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
43642                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
43643                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
43644             },
43645             getSignatureFromDeclaration: function (declarationIn) {
43646                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
43647                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
43648             },
43649             isImplementationOfOverload: function (nodeIn) {
43650                 var node = ts.getParseTreeNode(nodeIn, ts.isFunctionLike);
43651                 return node ? isImplementationOfOverload(node) : undefined;
43652             },
43653             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
43654             getAliasedSymbol: resolveAlias,
43655             getEmitResolver: getEmitResolver,
43656             getExportsOfModule: getExportsOfModuleAsArray,
43657             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
43658             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
43659             getAmbientModules: getAmbientModules,
43660             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
43661             isOptionalParameter: function (nodeIn) {
43662                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
43663                 return node ? isOptionalParameter(node) : false;
43664             },
43665             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
43666             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
43667             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
43668                 // we deliberately exclude augmentations
43669                 // since we are only interested in declarations of the module itself
43670                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
43671             },
43672             getApparentType: getApparentType,
43673             getUnionType: getUnionType,
43674             isTypeAssignableTo: isTypeAssignableTo,
43675             createAnonymousType: createAnonymousType,
43676             createSignature: createSignature,
43677             createSymbol: createSymbol,
43678             createIndexInfo: createIndexInfo,
43679             getAnyType: function () { return anyType; },
43680             getStringType: function () { return stringType; },
43681             getNumberType: function () { return numberType; },
43682             createPromiseType: createPromiseType,
43683             createArrayType: createArrayType,
43684             getElementTypeOfArrayType: getElementTypeOfArrayType,
43685             getBooleanType: function () { return booleanType; },
43686             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
43687             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
43688             getVoidType: function () { return voidType; },
43689             getUndefinedType: function () { return undefinedType; },
43690             getNullType: function () { return nullType; },
43691             getESSymbolType: function () { return esSymbolType; },
43692             getNeverType: function () { return neverType; },
43693             getOptionalType: function () { return optionalType; },
43694             isSymbolAccessible: isSymbolAccessible,
43695             isArrayType: isArrayType,
43696             isTupleType: isTupleType,
43697             isArrayLikeType: isArrayLikeType,
43698             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
43699             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
43700             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
43701             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
43702             getSuggestedSymbolForNonexistentJSXAttribute: getSuggestedSymbolForNonexistentJSXAttribute,
43703             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
43704             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
43705             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
43706             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
43707             getBaseConstraintOfType: getBaseConstraintOfType,
43708             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
43709             resolveName: function (name, location, meaning, excludeGlobals) {
43710                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
43711             },
43712             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
43713             getAccessibleSymbolChain: getAccessibleSymbolChain,
43714             getTypePredicateOfSignature: getTypePredicateOfSignature,
43715             resolveExternalModuleName: function (moduleSpecifierIn) {
43716                 var moduleSpecifier = ts.getParseTreeNode(moduleSpecifierIn, ts.isExpression);
43717                 return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
43718             },
43719             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
43720             tryGetThisTypeAt: function (nodeIn, includeGlobalThis) {
43721                 var node = ts.getParseTreeNode(nodeIn);
43722                 return node && tryGetThisTypeAt(node, includeGlobalThis);
43723             },
43724             getTypeArgumentConstraint: function (nodeIn) {
43725                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
43726                 return node && getTypeArgumentConstraint(node);
43727             },
43728             getSuggestionDiagnostics: function (fileIn, ct) {
43729                 var file = ts.getParseTreeNode(fileIn, ts.isSourceFile) || ts.Debug.fail("Could not determine parsed source file.");
43730                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
43731                     return ts.emptyArray;
43732                 }
43733                 var diagnostics;
43734                 try {
43735                     // Record the cancellation token so it can be checked later on during checkSourceElement.
43736                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
43737                     // this call is done.
43738                     cancellationToken = ct;
43739                     // Ensure file is type checked
43740                     checkSourceFile(file);
43741                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
43742                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
43743                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
43744                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
43745                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
43746                         }
43747                     });
43748                     return diagnostics || ts.emptyArray;
43749                 }
43750                 finally {
43751                     cancellationToken = undefined;
43752                 }
43753             },
43754             runWithCancellationToken: function (token, callback) {
43755                 try {
43756                     cancellationToken = token;
43757                     return callback(checker);
43758                 }
43759                 finally {
43760                     cancellationToken = undefined;
43761                 }
43762             },
43763             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
43764             isDeclarationVisible: isDeclarationVisible,
43765         };
43766         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
43767             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
43768             apparentArgumentCount = argumentCount;
43769             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
43770             apparentArgumentCount = undefined;
43771             return res;
43772         }
43773         var tupleTypes = new ts.Map();
43774         var unionTypes = new ts.Map();
43775         var intersectionTypes = new ts.Map();
43776         var literalTypes = new ts.Map();
43777         var indexedAccessTypes = new ts.Map();
43778         var templateLiteralTypes = new ts.Map();
43779         var stringMappingTypes = new ts.Map();
43780         var substitutionTypes = new ts.Map();
43781         var evolvingArrayTypes = [];
43782         var undefinedProperties = new ts.Map();
43783         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
43784         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
43785         var anyType = createIntrinsicType(1 /* Any */, "any");
43786         var autoType = createIntrinsicType(1 /* Any */, "any");
43787         var wildcardType = createIntrinsicType(1 /* Any */, "any");
43788         var errorType = createIntrinsicType(1 /* Any */, "error");
43789         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
43790         var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic");
43791         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
43792         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
43793         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
43794         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
43795         var nullType = createIntrinsicType(65536 /* Null */, "null");
43796         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
43797         var stringType = createIntrinsicType(4 /* String */, "string");
43798         var numberType = createIntrinsicType(8 /* Number */, "number");
43799         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
43800         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
43801         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
43802         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
43803         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
43804         trueType.regularType = regularTrueType;
43805         trueType.freshType = trueType;
43806         regularTrueType.regularType = regularTrueType;
43807         regularTrueType.freshType = trueType;
43808         falseType.regularType = regularFalseType;
43809         falseType.freshType = falseType;
43810         regularFalseType.regularType = regularFalseType;
43811         regularFalseType.freshType = falseType;
43812         var booleanType = createBooleanType([regularFalseType, regularTrueType]);
43813         // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
43814         // (The union is cached, so simply doing the marking here is sufficient)
43815         createBooleanType([regularFalseType, trueType]);
43816         createBooleanType([falseType, regularTrueType]);
43817         createBooleanType([falseType, trueType]);
43818         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
43819         var voidType = createIntrinsicType(16384 /* Void */, "void");
43820         var neverType = createIntrinsicType(131072 /* Never */, "never");
43821         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
43822         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
43823         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
43824         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
43825         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
43826         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
43827         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
43828         var numberOrBigIntType = getUnionType([numberType, bigintType]);
43829         var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]);
43830         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
43831         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
43832         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43833         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43834         emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
43835         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
43836         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
43837         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43838         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43839         emptyGenericType.instantiations = new ts.Map();
43840         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43841         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
43842         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
43843         anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
43844         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43845         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43846         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43847         var markerSuperType = createTypeParameter();
43848         var markerSubType = createTypeParameter();
43849         markerSubType.constraint = markerSuperType;
43850         var markerOtherType = createTypeParameter();
43851         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
43852         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
43853         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
43854         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
43855         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
43856         var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
43857         var iterationTypesCache = new ts.Map(); // cache for common IterationTypes instances
43858         var noIterationTypes = {
43859             get yieldType() { return ts.Debug.fail("Not supported"); },
43860             get returnType() { return ts.Debug.fail("Not supported"); },
43861             get nextType() { return ts.Debug.fail("Not supported"); },
43862         };
43863         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
43864         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
43865         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
43866         var asyncIterationTypesResolver = {
43867             iterableCacheKey: "iterationTypesOfAsyncIterable",
43868             iteratorCacheKey: "iterationTypesOfAsyncIterator",
43869             iteratorSymbolName: "asyncIterator",
43870             getGlobalIteratorType: getGlobalAsyncIteratorType,
43871             getGlobalIterableType: getGlobalAsyncIterableType,
43872             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
43873             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
43874             resolveIterationType: getAwaitedType,
43875             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
43876             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
43877             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property,
43878         };
43879         var syncIterationTypesResolver = {
43880             iterableCacheKey: "iterationTypesOfIterable",
43881             iteratorCacheKey: "iterationTypesOfIterator",
43882             iteratorSymbolName: "iterator",
43883             getGlobalIteratorType: getGlobalIteratorType,
43884             getGlobalIterableType: getGlobalIterableType,
43885             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
43886             getGlobalGeneratorType: getGlobalGeneratorType,
43887             resolveIterationType: function (type, _errorNode) { return type; },
43888             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
43889             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
43890             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
43891         };
43892         /** Key is "/path/to/a.ts|/path/to/b.ts". */
43893         var amalgamatedDuplicates;
43894         var reverseMappedCache = new ts.Map();
43895         var inInferTypeForHomomorphicMappedType = false;
43896         var ambientModulesCache;
43897         /**
43898          * List of every ambient module with a "*" wildcard.
43899          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
43900          * This is only used if there is no exact match.
43901          */
43902         var patternAmbientModules;
43903         var patternAmbientModuleAugmentations;
43904         var globalObjectType;
43905         var globalFunctionType;
43906         var globalCallableFunctionType;
43907         var globalNewableFunctionType;
43908         var globalArrayType;
43909         var globalReadonlyArrayType;
43910         var globalStringType;
43911         var globalNumberType;
43912         var globalBooleanType;
43913         var globalRegExpType;
43914         var globalThisType;
43915         var anyArrayType;
43916         var autoArrayType;
43917         var anyReadonlyArrayType;
43918         var deferredGlobalNonNullableTypeAlias;
43919         // The library files are only loaded when the feature is used.
43920         // This allows users to just specify library files they want to used through --lib
43921         // and they will not get an error from not having unrelated library files
43922         var deferredGlobalESSymbolConstructorSymbol;
43923         var deferredGlobalESSymbolType;
43924         var deferredGlobalTypedPropertyDescriptorType;
43925         var deferredGlobalPromiseType;
43926         var deferredGlobalPromiseLikeType;
43927         var deferredGlobalPromiseConstructorSymbol;
43928         var deferredGlobalPromiseConstructorLikeType;
43929         var deferredGlobalIterableType;
43930         var deferredGlobalIteratorType;
43931         var deferredGlobalIterableIteratorType;
43932         var deferredGlobalGeneratorType;
43933         var deferredGlobalIteratorYieldResultType;
43934         var deferredGlobalIteratorReturnResultType;
43935         var deferredGlobalAsyncIterableType;
43936         var deferredGlobalAsyncIteratorType;
43937         var deferredGlobalAsyncIterableIteratorType;
43938         var deferredGlobalAsyncGeneratorType;
43939         var deferredGlobalTemplateStringsArrayType;
43940         var deferredGlobalImportMetaType;
43941         var deferredGlobalExtractSymbol;
43942         var deferredGlobalOmitSymbol;
43943         var deferredGlobalBigIntType;
43944         var allPotentiallyUnusedIdentifiers = new ts.Map(); // key is file name
43945         var flowLoopStart = 0;
43946         var flowLoopCount = 0;
43947         var sharedFlowCount = 0;
43948         var flowAnalysisDisabled = false;
43949         var flowInvocationCount = 0;
43950         var lastFlowNode;
43951         var lastFlowNodeReachable;
43952         var flowTypeCache;
43953         var emptyStringType = getLiteralType("");
43954         var zeroType = getLiteralType(0);
43955         var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
43956         var resolutionTargets = [];
43957         var resolutionResults = [];
43958         var resolutionPropertyNames = [];
43959         var suggestionCount = 0;
43960         var maximumSuggestionCount = 10;
43961         var mergedSymbols = [];
43962         var symbolLinks = [];
43963         var nodeLinks = [];
43964         var flowLoopCaches = [];
43965         var flowLoopNodes = [];
43966         var flowLoopKeys = [];
43967         var flowLoopTypes = [];
43968         var sharedFlowNodes = [];
43969         var sharedFlowTypes = [];
43970         var flowNodeReachable = [];
43971         var flowNodePostSuper = [];
43972         var potentialThisCollisions = [];
43973         var potentialNewTargetCollisions = [];
43974         var potentialWeakMapCollisions = [];
43975         var awaitedTypeStack = [];
43976         var diagnostics = ts.createDiagnosticCollection();
43977         var suggestionDiagnostics = ts.createDiagnosticCollection();
43978         var typeofTypesByName = new ts.Map(ts.getEntries({
43979             string: stringType,
43980             number: numberType,
43981             bigint: bigintType,
43982             boolean: booleanType,
43983             symbol: esSymbolType,
43984             undefined: undefinedType
43985         }));
43986         var typeofType = createTypeofType();
43987         var _jsxNamespace;
43988         var _jsxFactoryEntity;
43989         var outofbandVarianceMarkerHandler;
43990         var subtypeRelation = new ts.Map();
43991         var strictSubtypeRelation = new ts.Map();
43992         var assignableRelation = new ts.Map();
43993         var comparableRelation = new ts.Map();
43994         var identityRelation = new ts.Map();
43995         var enumRelation = new ts.Map();
43996         var builtinGlobals = ts.createSymbolTable();
43997         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
43998         initializeTypeChecker();
43999         return checker;
44000         function getJsxNamespace(location) {
44001             if (location) {
44002                 var file = ts.getSourceFileOfNode(location);
44003                 if (file) {
44004                     if (ts.isJsxOpeningFragment(location)) {
44005                         if (file.localJsxFragmentNamespace) {
44006                             return file.localJsxFragmentNamespace;
44007                         }
44008                         var jsxFragmentPragma = file.pragmas.get("jsxfrag");
44009                         if (jsxFragmentPragma) {
44010                             var chosenPragma = ts.isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma;
44011                             file.localJsxFragmentFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
44012                             ts.visitNode(file.localJsxFragmentFactory, markAsSynthetic);
44013                             if (file.localJsxFragmentFactory) {
44014                                 return file.localJsxFragmentNamespace = ts.getFirstIdentifier(file.localJsxFragmentFactory).escapedText;
44015                             }
44016                         }
44017                         var entity = getJsxFragmentFactoryEntity(location);
44018                         if (entity) {
44019                             file.localJsxFragmentFactory = entity;
44020                             return file.localJsxFragmentNamespace = ts.getFirstIdentifier(entity).escapedText;
44021                         }
44022                     }
44023                     else {
44024                         if (file.localJsxNamespace) {
44025                             return file.localJsxNamespace;
44026                         }
44027                         var jsxPragma = file.pragmas.get("jsx");
44028                         if (jsxPragma) {
44029                             var chosenPragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
44030                             file.localJsxFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
44031                             ts.visitNode(file.localJsxFactory, markAsSynthetic);
44032                             if (file.localJsxFactory) {
44033                                 return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
44034                             }
44035                         }
44036                     }
44037                 }
44038             }
44039             if (!_jsxNamespace) {
44040                 _jsxNamespace = "React";
44041                 if (compilerOptions.jsxFactory) {
44042                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
44043                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
44044                     if (_jsxFactoryEntity) {
44045                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
44046                     }
44047                 }
44048                 else if (compilerOptions.reactNamespace) {
44049                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
44050                 }
44051             }
44052             if (!_jsxFactoryEntity) {
44053                 _jsxFactoryEntity = ts.factory.createQualifiedName(ts.factory.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
44054             }
44055             return _jsxNamespace;
44056             function markAsSynthetic(node) {
44057                 ts.setTextRangePosEnd(node, -1, -1);
44058                 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
44059             }
44060         }
44061         function getEmitResolver(sourceFile, cancellationToken) {
44062             // Ensure we have all the type information in place for this file so that all the
44063             // emitter questions of this resolver will return the right information.
44064             getDiagnostics(sourceFile, cancellationToken);
44065             return emitResolver;
44066         }
44067         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
44068             var diagnostic = location
44069                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
44070                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
44071             var existing = diagnostics.lookup(diagnostic);
44072             if (existing) {
44073                 return existing;
44074             }
44075             else {
44076                 diagnostics.add(diagnostic);
44077                 return diagnostic;
44078             }
44079         }
44080         function errorSkippedOn(key, location, message, arg0, arg1, arg2, arg3) {
44081             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
44082             diagnostic.skippedOn = key;
44083             return diagnostic;
44084         }
44085         function error(location, message, arg0, arg1, arg2, arg3) {
44086             var diagnostic = location
44087                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
44088                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
44089             diagnostics.add(diagnostic);
44090             return diagnostic;
44091         }
44092         function addErrorOrSuggestion(isError, diagnostic) {
44093             if (isError) {
44094                 diagnostics.add(diagnostic);
44095             }
44096             else {
44097                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
44098             }
44099         }
44100         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
44101             // Pseudo-synthesized input node
44102             if (location.pos < 0 || location.end < 0) {
44103                 if (!isError) {
44104                     return; // Drop suggestions (we have no span to suggest on)
44105                 }
44106                 // Issue errors globally
44107                 var file = ts.getSourceFileOfNode(location);
44108                 addErrorOrSuggestion(isError, "message" in message ? ts.createFileDiagnostic(file, 0, 0, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForFileFromMessageChain(file, message)); // eslint-disable-line no-in-operator
44109                 return;
44110             }
44111             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
44112         }
44113         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
44114             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
44115             if (maybeMissingAwait) {
44116                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
44117                 ts.addRelatedInfo(diagnostic, related);
44118             }
44119             return diagnostic;
44120         }
44121         function createSymbol(flags, name, checkFlags) {
44122             symbolCount++;
44123             var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
44124             symbol.checkFlags = checkFlags || 0;
44125             return symbol;
44126         }
44127         function getExcludedSymbolFlags(flags) {
44128             var result = 0;
44129             if (flags & 2 /* BlockScopedVariable */)
44130                 result |= 111551 /* BlockScopedVariableExcludes */;
44131             if (flags & 1 /* FunctionScopedVariable */)
44132                 result |= 111550 /* FunctionScopedVariableExcludes */;
44133             if (flags & 4 /* Property */)
44134                 result |= 0 /* PropertyExcludes */;
44135             if (flags & 8 /* EnumMember */)
44136                 result |= 900095 /* EnumMemberExcludes */;
44137             if (flags & 16 /* Function */)
44138                 result |= 110991 /* FunctionExcludes */;
44139             if (flags & 32 /* Class */)
44140                 result |= 899503 /* ClassExcludes */;
44141             if (flags & 64 /* Interface */)
44142                 result |= 788872 /* InterfaceExcludes */;
44143             if (flags & 256 /* RegularEnum */)
44144                 result |= 899327 /* RegularEnumExcludes */;
44145             if (flags & 128 /* ConstEnum */)
44146                 result |= 899967 /* ConstEnumExcludes */;
44147             if (flags & 512 /* ValueModule */)
44148                 result |= 110735 /* ValueModuleExcludes */;
44149             if (flags & 8192 /* Method */)
44150                 result |= 103359 /* MethodExcludes */;
44151             if (flags & 32768 /* GetAccessor */)
44152                 result |= 46015 /* GetAccessorExcludes */;
44153             if (flags & 65536 /* SetAccessor */)
44154                 result |= 78783 /* SetAccessorExcludes */;
44155             if (flags & 262144 /* TypeParameter */)
44156                 result |= 526824 /* TypeParameterExcludes */;
44157             if (flags & 524288 /* TypeAlias */)
44158                 result |= 788968 /* TypeAliasExcludes */;
44159             if (flags & 2097152 /* Alias */)
44160                 result |= 2097152 /* AliasExcludes */;
44161             return result;
44162         }
44163         function recordMergedSymbol(target, source) {
44164             if (!source.mergeId) {
44165                 source.mergeId = nextMergeId;
44166                 nextMergeId++;
44167             }
44168             mergedSymbols[source.mergeId] = target;
44169         }
44170         function cloneSymbol(symbol) {
44171             var result = createSymbol(symbol.flags, symbol.escapedName);
44172             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
44173             result.parent = symbol.parent;
44174             if (symbol.valueDeclaration)
44175                 result.valueDeclaration = symbol.valueDeclaration;
44176             if (symbol.constEnumOnlyModule)
44177                 result.constEnumOnlyModule = true;
44178             if (symbol.members)
44179                 result.members = new ts.Map(symbol.members);
44180             if (symbol.exports)
44181                 result.exports = new ts.Map(symbol.exports);
44182             recordMergedSymbol(result, symbol);
44183             return result;
44184         }
44185         /**
44186          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
44187          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
44188          */
44189         function mergeSymbol(target, source, unidirectional) {
44190             if (unidirectional === void 0) { unidirectional = false; }
44191             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
44192                 (source.flags | target.flags) & 67108864 /* Assignment */) {
44193                 if (source === target) {
44194                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
44195                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
44196                     return target;
44197                 }
44198                 if (!(target.flags & 33554432 /* Transient */)) {
44199                     var resolvedTarget = resolveSymbol(target);
44200                     if (resolvedTarget === unknownSymbol) {
44201                         return source;
44202                     }
44203                     target = cloneSymbol(resolvedTarget);
44204                 }
44205                 // Javascript static-property-assignment declarations always merge, even though they are also values
44206                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
44207                     // reset flag when merging instantiated module into value module that has only const enums
44208                     target.constEnumOnlyModule = false;
44209                 }
44210                 target.flags |= source.flags;
44211                 if (source.valueDeclaration) {
44212                     ts.setValueDeclaration(target, source.valueDeclaration);
44213                 }
44214                 ts.addRange(target.declarations, source.declarations);
44215                 if (source.members) {
44216                     if (!target.members)
44217                         target.members = ts.createSymbolTable();
44218                     mergeSymbolTable(target.members, source.members, unidirectional);
44219                 }
44220                 if (source.exports) {
44221                     if (!target.exports)
44222                         target.exports = ts.createSymbolTable();
44223                     mergeSymbolTable(target.exports, source.exports, unidirectional);
44224                 }
44225                 if (!unidirectional) {
44226                     recordMergedSymbol(target, source);
44227                 }
44228             }
44229             else if (target.flags & 1024 /* NamespaceModule */) {
44230                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
44231                 // as we will already report a "Declaration name conflicts..." error, and this error
44232                 // won't make much sense.
44233                 if (target !== globalThisSymbol) {
44234                     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));
44235                 }
44236             }
44237             else { // error
44238                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
44239                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
44240                 var message = isEitherEnum
44241                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
44242                     : isEitherBlockScoped_1
44243                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
44244                         : ts.Diagnostics.Duplicate_identifier_0;
44245                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
44246                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
44247                 var symbolName_1 = symbolToString(source);
44248                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
44249                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
44250                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
44251                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
44252                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
44253                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: new ts.Map() });
44254                     });
44255                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
44256                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
44257                     });
44258                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
44259                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
44260                 }
44261                 else {
44262                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
44263                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
44264                 }
44265             }
44266             return target;
44267             function addDuplicateLocations(locs, symbol) {
44268                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
44269                     var decl = _a[_i];
44270                     ts.pushIfUnique(locs, decl);
44271                 }
44272             }
44273         }
44274         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
44275             ts.forEach(target.declarations, function (node) {
44276                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
44277             });
44278         }
44279         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
44280             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
44281             var err = lookupOrIssueError(errorNode, message, symbolName);
44282             var _loop_7 = function (relatedNode) {
44283                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
44284                 if (adjustedNode === errorNode)
44285                     return "continue";
44286                 err.relatedInformation = err.relatedInformation || [];
44287                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
44288                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
44289                 if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; }))
44290                     return "continue";
44291                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
44292             };
44293             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
44294                 var relatedNode = _a[_i];
44295                 _loop_7(relatedNode);
44296             }
44297         }
44298         function combineSymbolTables(first, second) {
44299             if (!(first === null || first === void 0 ? void 0 : first.size))
44300                 return second;
44301             if (!(second === null || second === void 0 ? void 0 : second.size))
44302                 return first;
44303             var combined = ts.createSymbolTable();
44304             mergeSymbolTable(combined, first);
44305             mergeSymbolTable(combined, second);
44306             return combined;
44307         }
44308         function mergeSymbolTable(target, source, unidirectional) {
44309             if (unidirectional === void 0) { unidirectional = false; }
44310             source.forEach(function (sourceSymbol, id) {
44311                 var targetSymbol = target.get(id);
44312                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
44313             });
44314         }
44315         function mergeModuleAugmentation(moduleName) {
44316             var _a, _b;
44317             var moduleAugmentation = moduleName.parent;
44318             if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
44319                 // this is a combined symbol for multiple augmentations within the same file.
44320                 // its symbol already has accumulated information for all declarations
44321                 // so we need to add it just once - do the work only for first declaration
44322                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
44323                 return;
44324             }
44325             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
44326                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
44327             }
44328             else {
44329                 // find a module that about to be augmented
44330                 // do not validate names of augmentations that are defined in ambient context
44331                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
44332                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
44333                     : undefined;
44334                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
44335                 if (!mainModule_1) {
44336                     return;
44337                 }
44338                 // obtain item referenced by 'export='
44339                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
44340                 if (mainModule_1.flags & 1920 /* Namespace */) {
44341                     // If we're merging an augmentation to a pattern ambient module, we want to
44342                     // perform the merge unidirectionally from the augmentation ('a.foo') to
44343                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
44344                     // all the exports both from the pattern and from the augmentation, but
44345                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
44346                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
44347                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
44348                         if (!patternAmbientModuleAugmentations) {
44349                             patternAmbientModuleAugmentations = new ts.Map();
44350                         }
44351                         // moduleName will be a StringLiteral since this is not `declare global`.
44352                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
44353                     }
44354                     else {
44355                         if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) {
44356                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
44357                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
44358                             for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
44359                                 var _d = _c[_i], key = _d[0], value = _d[1];
44360                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
44361                                     mergeSymbol(resolvedExports.get(key), value);
44362                                 }
44363                             }
44364                         }
44365                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
44366                     }
44367                 }
44368                 else {
44369                     // moduleName will be a StringLiteral since this is not `declare global`.
44370                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
44371                 }
44372             }
44373         }
44374         function addToSymbolTable(target, source, message) {
44375             source.forEach(function (sourceSymbol, id) {
44376                 var targetSymbol = target.get(id);
44377                 if (targetSymbol) {
44378                     // Error on redeclarations
44379                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
44380                 }
44381                 else {
44382                     target.set(id, sourceSymbol);
44383                 }
44384             });
44385             function addDeclarationDiagnostic(id, message) {
44386                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
44387             }
44388         }
44389         function getSymbolLinks(symbol) {
44390             if (symbol.flags & 33554432 /* Transient */)
44391                 return symbol;
44392             var id = getSymbolId(symbol);
44393             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
44394         }
44395         function getNodeLinks(node) {
44396             var nodeId = getNodeId(node);
44397             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
44398         }
44399         function isGlobalSourceFile(node) {
44400             return node.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
44401         }
44402         function getSymbol(symbols, name, meaning) {
44403             if (meaning) {
44404                 var symbol = getMergedSymbol(symbols.get(name));
44405                 if (symbol) {
44406                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
44407                     if (symbol.flags & meaning) {
44408                         return symbol;
44409                     }
44410                     if (symbol.flags & 2097152 /* Alias */) {
44411                         var target = resolveAlias(symbol);
44412                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
44413                         if (target === unknownSymbol || target.flags & meaning) {
44414                             return symbol;
44415                         }
44416                     }
44417                 }
44418             }
44419             // return undefined if we can't find a symbol.
44420         }
44421         /**
44422          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
44423          * @param parameter a parameterDeclaration node
44424          * @param parameterName a name of the parameter to get the symbols for.
44425          * @return a tuple of two symbols
44426          */
44427         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
44428             var constructorDeclaration = parameter.parent;
44429             var classDeclaration = parameter.parent.parent;
44430             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
44431             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
44432             if (parameterSymbol && propertySymbol) {
44433                 return [parameterSymbol, propertySymbol];
44434             }
44435             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
44436         }
44437         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
44438             var declarationFile = ts.getSourceFileOfNode(declaration);
44439             var useFile = ts.getSourceFileOfNode(usage);
44440             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
44441             if (declarationFile !== useFile) {
44442                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
44443                     (!ts.outFile(compilerOptions)) ||
44444                     isInTypeQuery(usage) ||
44445                     declaration.flags & 8388608 /* Ambient */) {
44446                     // nodes are in different files and order cannot be determined
44447                     return true;
44448                 }
44449                 // declaration is after usage
44450                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
44451                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
44452                     return true;
44453                 }
44454                 var sourceFiles = host.getSourceFiles();
44455                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
44456             }
44457             if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) {
44458                 // declaration is before usage
44459                 if (declaration.kind === 198 /* BindingElement */) {
44460                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
44461                     var errorBindingElement = ts.getAncestor(usage, 198 /* BindingElement */);
44462                     if (errorBindingElement) {
44463                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
44464                             declaration.pos < errorBindingElement.pos;
44465                     }
44466                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
44467                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 249 /* VariableDeclaration */), usage);
44468                 }
44469                 else if (declaration.kind === 249 /* VariableDeclaration */) {
44470                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
44471                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
44472                 }
44473                 else if (ts.isClassDeclaration(declaration)) {
44474                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
44475                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
44476                 }
44477                 else if (ts.isPropertyDeclaration(declaration)) {
44478                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
44479                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
44480                 }
44481                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
44482                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
44483                     return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
44484                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
44485                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
44486                 }
44487                 return true;
44488             }
44489             // declaration is after usage, but it can still be legal if usage is deferred:
44490             // 1. inside an export specifier
44491             // 2. inside a function
44492             // 3. inside an instance property initializer, a reference to a non-instance property
44493             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
44494             // 4. inside a static property initializer, a reference to a static method in the same class
44495             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
44496             // or if usage is in a type context:
44497             // 1. inside a type query (typeof in type position)
44498             // 2. inside a jsdoc comment
44499             if (usage.parent.kind === 270 /* ExportSpecifier */ || (usage.parent.kind === 266 /* ExportAssignment */ && usage.parent.isExportEquals)) {
44500                 // export specifiers do not use the variable, they only make it available for use
44501                 return true;
44502             }
44503             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
44504             if (usage.kind === 266 /* ExportAssignment */ && usage.isExportEquals) {
44505                 return true;
44506             }
44507             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
44508                 return true;
44509             }
44510             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
44511                 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
44512                     && ts.getContainingClass(declaration)
44513                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
44514                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
44515                 }
44516                 else {
44517                     return true;
44518                 }
44519             }
44520             return false;
44521             function usageInTypeDeclaration() {
44522                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
44523             }
44524             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
44525                 switch (declaration.parent.parent.kind) {
44526                     case 232 /* VariableStatement */:
44527                     case 237 /* ForStatement */:
44528                     case 239 /* ForOfStatement */:
44529                         // variable statement/for/for-of statement case,
44530                         // use site should not be inside variable declaration (initializer of declaration or binding element)
44531                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
44532                             return true;
44533                         }
44534                         break;
44535                 }
44536                 // ForIn/ForOf case - use site should not be used in expression part
44537                 var grandparent = declaration.parent.parent;
44538                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
44539             }
44540             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
44541                 return !!ts.findAncestor(usage, function (current) {
44542                     if (current === declContainer) {
44543                         return "quit";
44544                     }
44545                     if (ts.isFunctionLike(current)) {
44546                         return true;
44547                     }
44548                     var initializerOfProperty = current.parent &&
44549                         current.parent.kind === 163 /* PropertyDeclaration */ &&
44550                         current.parent.initializer === current;
44551                     if (initializerOfProperty) {
44552                         if (ts.hasSyntacticModifier(current.parent, 32 /* Static */)) {
44553                             if (declaration.kind === 165 /* MethodDeclaration */) {
44554                                 return true;
44555                             }
44556                         }
44557                         else {
44558                             var isDeclarationInstanceProperty = declaration.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */);
44559                             if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
44560                                 return true;
44561                             }
44562                         }
44563                     }
44564                     return false;
44565                 });
44566             }
44567             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
44568             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
44569                 // always legal if usage is after declaration
44570                 if (usage.end > declaration.end) {
44571                     return false;
44572                 }
44573                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
44574                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
44575                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
44576                     if (node === declaration) {
44577                         return "quit";
44578                     }
44579                     switch (node.kind) {
44580                         case 209 /* ArrowFunction */:
44581                             return true;
44582                         case 163 /* PropertyDeclaration */:
44583                             // even when stopping at any property declaration, they need to come from the same class
44584                             return stopAtAnyPropertyDeclaration &&
44585                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
44586                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
44587                                 ? "quit" : true;
44588                         case 230 /* Block */:
44589                             switch (node.parent.kind) {
44590                                 case 167 /* GetAccessor */:
44591                                 case 165 /* MethodDeclaration */:
44592                                 case 168 /* SetAccessor */:
44593                                     return true;
44594                                 default:
44595                                     return false;
44596                             }
44597                         default:
44598                             return false;
44599                     }
44600                 });
44601                 return ancestorChangingReferenceScope === undefined;
44602             }
44603         }
44604         function useOuterVariableScopeInParameter(result, location, lastLocation) {
44605             var target = ts.getEmitScriptTarget(compilerOptions);
44606             var functionLocation = location;
44607             if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
44608                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
44609                 // - static field in a class expression
44610                 // - optional chaining pre-es2020
44611                 // - nullish coalesce pre-es2020
44612                 // - spread assignment in binding pattern pre-es2017
44613                 if (target >= 2 /* ES2015 */) {
44614                     var links = getNodeLinks(functionLocation);
44615                     if (links.declarationRequiresScopeChange === undefined) {
44616                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
44617                     }
44618                     return !links.declarationRequiresScopeChange;
44619                 }
44620             }
44621             return false;
44622             function requiresScopeChange(node) {
44623                 return requiresScopeChangeWorker(node.name)
44624                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
44625             }
44626             function requiresScopeChangeWorker(node) {
44627                 switch (node.kind) {
44628                     case 209 /* ArrowFunction */:
44629                     case 208 /* FunctionExpression */:
44630                     case 251 /* FunctionDeclaration */:
44631                     case 166 /* Constructor */:
44632                         // do not descend into these
44633                         return false;
44634                     case 165 /* MethodDeclaration */:
44635                     case 167 /* GetAccessor */:
44636                     case 168 /* SetAccessor */:
44637                     case 288 /* PropertyAssignment */:
44638                         return requiresScopeChangeWorker(node.name);
44639                     case 163 /* PropertyDeclaration */:
44640                         // static properties in classes introduce temporary variables
44641                         if (ts.hasStaticModifier(node)) {
44642                             return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
44643                         }
44644                         return requiresScopeChangeWorker(node.name);
44645                     default:
44646                         // null coalesce and optional chain pre-es2020 produce temporary variables
44647                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
44648                             return target < 7 /* ES2020 */;
44649                         }
44650                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
44651                             return target < 4 /* ES2017 */;
44652                         }
44653                         if (ts.isTypeNode(node))
44654                             return false;
44655                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
44656                 }
44657             }
44658         }
44659         /**
44660          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
44661          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
44662          * the given name can be found.
44663          *
44664          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
44665          */
44666         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
44667             if (excludeGlobals === void 0) { excludeGlobals = false; }
44668             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
44669         }
44670         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
44671             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
44672             var result;
44673             var lastLocation;
44674             var lastSelfReferenceLocation;
44675             var propertyWithInvalidInitializer;
44676             var associatedDeclarationForContainingInitializerOrBindingName;
44677             var withinDeferredContext = false;
44678             var errorLocation = location;
44679             var grandparent;
44680             var isInExternalModule = false;
44681             loop: while (location) {
44682                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
44683                 if (location.locals && !isGlobalSourceFile(location)) {
44684                     if (result = lookup(location.locals, name, meaning)) {
44685                         var useResult = true;
44686                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
44687                             // symbol lookup restrictions for function-like declarations
44688                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
44689                             //   list and return type. However, local types are only in scope in the function body.
44690                             // - parameters are only in the scope of function body
44691                             // This restriction does not apply to JSDoc comment types because they are parented
44692                             // at a higher level than type parameters would normally be
44693                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 311 /* JSDocComment */) {
44694                                 useResult = result.flags & 262144 /* TypeParameter */
44695                                     // type parameters are visible in parameter list, return type and type parameter list
44696                                     ? lastLocation === location.type ||
44697                                         lastLocation.kind === 160 /* Parameter */ ||
44698                                         lastLocation.kind === 159 /* TypeParameter */
44699                                     // local types not visible outside the function body
44700                                     : false;
44701                             }
44702                             if (meaning & result.flags & 3 /* Variable */) {
44703                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
44704                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
44705                                     useResult = false;
44706                                 }
44707                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
44708                                     // parameters are visible only inside function body, parameter list and return type
44709                                     // technically for parameter list case here we might mix parameters and variables declared in function,
44710                                     // however it is detected separately when checking initializers of parameters
44711                                     // to make sure that they reference no variables declared after them.
44712                                     useResult =
44713                                         lastLocation.kind === 160 /* Parameter */ ||
44714                                             (lastLocation === location.type &&
44715                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
44716                                 }
44717                             }
44718                         }
44719                         else if (location.kind === 184 /* ConditionalType */) {
44720                             // A type parameter declared using 'infer T' in a conditional type is visible only in
44721                             // the true branch of the conditional type.
44722                             useResult = lastLocation === location.trueType;
44723                         }
44724                         if (useResult) {
44725                             break loop;
44726                         }
44727                         else {
44728                             result = undefined;
44729                         }
44730                     }
44731                 }
44732                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
44733                 switch (location.kind) {
44734                     case 297 /* SourceFile */:
44735                         if (!ts.isExternalOrCommonJsModule(location))
44736                             break;
44737                         isInExternalModule = true;
44738                     // falls through
44739                     case 256 /* ModuleDeclaration */:
44740                         var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
44741                         if (location.kind === 297 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
44742                             // It's an external module. First see if the module has an export default and if the local
44743                             // name of that export default matches.
44744                             if (result = moduleExports.get("default" /* Default */)) {
44745                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
44746                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
44747                                     break loop;
44748                                 }
44749                                 result = undefined;
44750                             }
44751                             // Because of module/namespace merging, a module's exports are in scope,
44752                             // yet we never want to treat an export specifier as putting a member in scope.
44753                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
44754                             // Two things to note about this:
44755                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
44756                             //        on an export specifier is that it might find the export specifier itself, and try to
44757                             //        resolve it as an alias. This will cause the checker to consider the export specifier
44758                             //        a circular alias reference when it might not be.
44759                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
44760                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
44761                             //        which is not the desired behavior.
44762                             var moduleExport = moduleExports.get(name);
44763                             if (moduleExport &&
44764                                 moduleExport.flags === 2097152 /* Alias */ &&
44765                                 (ts.getDeclarationOfKind(moduleExport, 270 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 269 /* NamespaceExport */))) {
44766                                 break;
44767                             }
44768                         }
44769                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
44770                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
44771                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
44772                                 result = undefined;
44773                             }
44774                             else {
44775                                 break loop;
44776                             }
44777                         }
44778                         break;
44779                     case 255 /* EnumDeclaration */:
44780                         if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
44781                             break loop;
44782                         }
44783                         break;
44784                     case 163 /* PropertyDeclaration */:
44785                         // TypeScript 1.0 spec (April 2014): 8.4.1
44786                         // Initializer expressions for instance member variables are evaluated in the scope
44787                         // of the class constructor body but are not permitted to reference parameters or
44788                         // local variables of the constructor. This effectively means that entities from outer scopes
44789                         // by the same name as a constructor parameter or local variable are inaccessible
44790                         // in initializer expressions for instance member variables.
44791                         if (!ts.hasSyntacticModifier(location, 32 /* Static */)) {
44792                             var ctor = findConstructorDeclaration(location.parent);
44793                             if (ctor && ctor.locals) {
44794                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
44795                                     // Remember the property node, it will be used later to report appropriate error
44796                                     propertyWithInvalidInitializer = location;
44797                                 }
44798                             }
44799                         }
44800                         break;
44801                     case 252 /* ClassDeclaration */:
44802                     case 221 /* ClassExpression */:
44803                     case 253 /* InterfaceDeclaration */:
44804                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
44805                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
44806                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
44807                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
44808                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
44809                                 // ignore type parameters not declared in this container
44810                                 result = undefined;
44811                                 break;
44812                             }
44813                             if (lastLocation && ts.hasSyntacticModifier(lastLocation, 32 /* Static */)) {
44814                                 // TypeScript 1.0 spec (April 2014): 3.4.1
44815                                 // The scope of a type parameter extends over the entire declaration with which the type
44816                                 // parameter list is associated, with the exception of static member declarations in classes.
44817                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
44818                                 return undefined;
44819                             }
44820                             break loop;
44821                         }
44822                         if (location.kind === 221 /* ClassExpression */ && meaning & 32 /* Class */) {
44823                             var className = location.name;
44824                             if (className && name === className.escapedText) {
44825                                 result = location.symbol;
44826                                 break loop;
44827                             }
44828                         }
44829                         break;
44830                     case 223 /* ExpressionWithTypeArguments */:
44831                         // The type parameters of a class are not in scope in the base class expression.
44832                         if (lastLocation === location.expression && location.parent.token === 93 /* ExtendsKeyword */) {
44833                             var container = location.parent.parent;
44834                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
44835                                 if (nameNotFoundMessage) {
44836                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
44837                                 }
44838                                 return undefined;
44839                             }
44840                         }
44841                         break;
44842                     // It is not legal to reference a class's own type parameters from a computed property name that
44843                     // belongs to the class. For example:
44844                     //
44845                     //   function foo<T>() { return '' }
44846                     //   class C<T> { // <-- Class's own type parameter T
44847                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
44848                     //   }
44849                     //
44850                     case 158 /* ComputedPropertyName */:
44851                         grandparent = location.parent.parent;
44852                         if (ts.isClassLike(grandparent) || grandparent.kind === 253 /* InterfaceDeclaration */) {
44853                             // A reference to this grandparent's type parameters would be an error
44854                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
44855                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
44856                                 return undefined;
44857                             }
44858                         }
44859                         break;
44860                     case 209 /* ArrowFunction */:
44861                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
44862                         // for lower compile targets the resolved symbol is used to emit an error
44863                         if (compilerOptions.target >= 2 /* ES2015 */) {
44864                             break;
44865                         }
44866                     // falls through
44867                     case 165 /* MethodDeclaration */:
44868                     case 166 /* Constructor */:
44869                     case 167 /* GetAccessor */:
44870                     case 168 /* SetAccessor */:
44871                     case 251 /* FunctionDeclaration */:
44872                         if (meaning & 3 /* Variable */ && name === "arguments") {
44873                             result = argumentsSymbol;
44874                             break loop;
44875                         }
44876                         break;
44877                     case 208 /* FunctionExpression */:
44878                         if (meaning & 3 /* Variable */ && name === "arguments") {
44879                             result = argumentsSymbol;
44880                             break loop;
44881                         }
44882                         if (meaning & 16 /* Function */) {
44883                             var functionName = location.name;
44884                             if (functionName && name === functionName.escapedText) {
44885                                 result = location.symbol;
44886                                 break loop;
44887                             }
44888                         }
44889                         break;
44890                     case 161 /* Decorator */:
44891                         // Decorators are resolved at the class declaration. Resolving at the parameter
44892                         // or member would result in looking up locals in the method.
44893                         //
44894                         //   function y() {}
44895                         //   class C {
44896                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
44897                         //   }
44898                         //
44899                         if (location.parent && location.parent.kind === 160 /* Parameter */) {
44900                             location = location.parent;
44901                         }
44902                         //
44903                         //   function y() {}
44904                         //   class C {
44905                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
44906                         //   }
44907                         //
44908                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
44909                         //
44910                         //   type T = number;
44911                         //   declare function y(x: T): any;
44912                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
44913                         //   class C<T> {}
44914                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 252 /* ClassDeclaration */)) {
44915                             location = location.parent;
44916                         }
44917                         break;
44918                     case 331 /* JSDocTypedefTag */:
44919                     case 324 /* JSDocCallbackTag */:
44920                     case 325 /* JSDocEnumTag */:
44921                         // js type aliases do not resolve names from their host, so skip past it
44922                         location = ts.getJSDocHost(location);
44923                         break;
44924                     case 160 /* Parameter */:
44925                         if (lastLocation && (lastLocation === location.initializer ||
44926                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
44927                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
44928                                 associatedDeclarationForContainingInitializerOrBindingName = location;
44929                             }
44930                         }
44931                         break;
44932                     case 198 /* BindingElement */:
44933                         if (lastLocation && (lastLocation === location.initializer ||
44934                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
44935                             if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) {
44936                                 associatedDeclarationForContainingInitializerOrBindingName = location;
44937                             }
44938                         }
44939                         break;
44940                     case 185 /* InferType */:
44941                         if (meaning & 262144 /* TypeParameter */) {
44942                             var parameterName = location.typeParameter.name;
44943                             if (parameterName && name === parameterName.escapedText) {
44944                                 result = location.typeParameter.symbol;
44945                                 break loop;
44946                             }
44947                         }
44948                         break;
44949                 }
44950                 if (isSelfReferenceLocation(location)) {
44951                     lastSelfReferenceLocation = location;
44952                 }
44953                 lastLocation = location;
44954                 location = location.parent;
44955             }
44956             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
44957             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
44958             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
44959             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
44960                 result.isReferenced |= meaning;
44961             }
44962             if (!result) {
44963                 if (lastLocation) {
44964                     ts.Debug.assert(lastLocation.kind === 297 /* SourceFile */);
44965                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
44966                         return lastLocation.symbol;
44967                     }
44968                 }
44969                 if (!excludeGlobals) {
44970                     result = lookup(globals, name, meaning);
44971                 }
44972             }
44973             if (!result) {
44974                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
44975                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
44976                         return requireSymbol;
44977                     }
44978                 }
44979             }
44980             if (!result) {
44981                 if (nameNotFoundMessage) {
44982                     if (!errorLocation ||
44983                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
44984                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
44985                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
44986                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
44987                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
44988                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
44989                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
44990                         var suggestion = void 0;
44991                         if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
44992                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
44993                             if (suggestion) {
44994                                 var suggestionName = symbolToString(suggestion);
44995                                 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
44996                                 if (suggestion.valueDeclaration) {
44997                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
44998                                 }
44999                             }
45000                         }
45001                         if (!suggestion) {
45002                             if (nameArg) {
45003                                 var lib = getSuggestedLibForNonExistentName(nameArg);
45004                                 if (lib) {
45005                                     error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib);
45006                                 }
45007                                 else {
45008                                     error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
45009                                 }
45010                             }
45011                         }
45012                         suggestionCount++;
45013                     }
45014                 }
45015                 return undefined;
45016             }
45017             // Perform extra checks only if error reporting was requested
45018             if (nameNotFoundMessage) {
45019                 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
45020                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
45021                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
45022                     // with ESNext+useDefineForClassFields because the scope semantics are different.
45023                     var propertyName = propertyWithInvalidInitializer.name;
45024                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
45025                     return undefined;
45026                 }
45027                 // Only check for block-scoped variable if we have an error location and are looking for the
45028                 // name with variable meaning
45029                 //      For example,
45030                 //          declare module foo {
45031                 //              interface bar {}
45032                 //          }
45033                 //      const foo/*1*/: foo/*2*/.bar;
45034                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
45035                 // block-scoped variable and namespace module. However, only when we
45036                 // try to resolve name in /*1*/ which is used in variable position,
45037                 // we want to check for block-scoped
45038                 if (errorLocation &&
45039                     (meaning & 2 /* BlockScopedVariable */ ||
45040                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
45041                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
45042                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
45043                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
45044                     }
45045                 }
45046                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
45047                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
45048                     var merged = getMergedSymbol(result);
45049                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
45050                         errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name));
45051                     }
45052                 }
45053                 // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right
45054                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
45055                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
45056                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
45057                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
45058                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
45059                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
45060                     }
45061                     // And it cannot refer to any declarations which come after it
45062                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
45063                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
45064                     }
45065                 }
45066                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
45067                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
45068                 }
45069             }
45070             return result;
45071         }
45072         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
45073             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
45074                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
45075                 if (typeOnlyDeclaration) {
45076                     var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
45077                     var message = isExport
45078                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
45079                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
45080                     var relatedMessage = isExport
45081                         ? ts.Diagnostics._0_was_exported_here
45082                         : ts.Diagnostics._0_was_imported_here;
45083                     var unescapedName = ts.unescapeLeadingUnderscores(name);
45084                     ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
45085                 }
45086             }
45087         }
45088         function getIsDeferredContext(location, lastLocation) {
45089             if (location.kind !== 209 /* ArrowFunction */ && location.kind !== 208 /* FunctionExpression */) {
45090                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
45091                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
45092                     (location.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
45093             }
45094             if (lastLocation && lastLocation === location.name) {
45095                 return false;
45096             }
45097             // generator functions and async functions are not inlined in control flow when immediately invoked
45098             if (location.asteriskToken || ts.hasSyntacticModifier(location, 256 /* Async */)) {
45099                 return true;
45100             }
45101             return !ts.getImmediatelyInvokedFunctionExpression(location);
45102         }
45103         function isSelfReferenceLocation(node) {
45104             switch (node.kind) {
45105                 case 251 /* FunctionDeclaration */:
45106                 case 252 /* ClassDeclaration */:
45107                 case 253 /* InterfaceDeclaration */:
45108                 case 255 /* EnumDeclaration */:
45109                 case 254 /* TypeAliasDeclaration */:
45110                 case 256 /* ModuleDeclaration */: // For `namespace N { N; }`
45111                     return true;
45112                 default:
45113                     return false;
45114             }
45115         }
45116         function diagnosticName(nameArg) {
45117             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
45118         }
45119         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
45120             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
45121                 var decl = _a[_i];
45122                 if (decl.kind === 159 /* TypeParameter */) {
45123                     var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
45124                     if (parent === container) {
45125                         return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
45126                     }
45127                 }
45128             }
45129             return false;
45130         }
45131         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
45132             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
45133                 return false;
45134             }
45135             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
45136             var location = container;
45137             while (location) {
45138                 if (ts.isClassLike(location.parent)) {
45139                     var classSymbol = getSymbolOfNode(location.parent);
45140                     if (!classSymbol) {
45141                         break;
45142                     }
45143                     // Check to see if a static member exists.
45144                     var constructorType = getTypeOfSymbol(classSymbol);
45145                     if (getPropertyOfType(constructorType, name)) {
45146                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
45147                         return true;
45148                     }
45149                     // No static member is present.
45150                     // Check if we're in an instance method and look for a relevant instance member.
45151                     if (location === container && !ts.hasSyntacticModifier(location, 32 /* Static */)) {
45152                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
45153                         if (getPropertyOfType(instanceType, name)) {
45154                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
45155                             return true;
45156                         }
45157                     }
45158                 }
45159                 location = location.parent;
45160             }
45161             return false;
45162         }
45163         function checkAndReportErrorForExtendingInterface(errorLocation) {
45164             var expression = getEntityNameForExtendingInterface(errorLocation);
45165             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
45166                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
45167                 return true;
45168             }
45169             return false;
45170         }
45171         /**
45172          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
45173          * but returns undefined if that expression is not an EntityNameExpression.
45174          */
45175         function getEntityNameForExtendingInterface(node) {
45176             switch (node.kind) {
45177                 case 78 /* Identifier */:
45178                 case 201 /* PropertyAccessExpression */:
45179                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
45180                 case 223 /* ExpressionWithTypeArguments */:
45181                     if (ts.isEntityNameExpression(node.expression)) {
45182                         return node.expression;
45183                     }
45184                 // falls through
45185                 default:
45186                     return undefined;
45187             }
45188         }
45189         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
45190             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
45191             if (meaning === namespaceMeaning) {
45192                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45193                 var parent = errorLocation.parent;
45194                 if (symbol) {
45195                     if (ts.isQualifiedName(parent)) {
45196                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
45197                         var propName = parent.right.escapedText;
45198                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
45199                         if (propType) {
45200                             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));
45201                             return true;
45202                         }
45203                     }
45204                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
45205                     return true;
45206                 }
45207             }
45208             return false;
45209         }
45210         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
45211             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
45212                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45213                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
45214                     error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.unescapeLeadingUnderscores(name));
45215                     return true;
45216                 }
45217             }
45218             return false;
45219         }
45220         function isPrimitiveTypeName(name) {
45221             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
45222         }
45223         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
45224             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 270 /* ExportSpecifier */) {
45225                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
45226                 return true;
45227             }
45228             return false;
45229         }
45230         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
45231             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
45232                 if (isPrimitiveTypeName(name)) {
45233                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
45234                     return true;
45235                 }
45236                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45237                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
45238                     var rawName = ts.unescapeLeadingUnderscores(name);
45239                     if (isES2015OrLaterConstructorName(name)) {
45240                         error(errorLocation, 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, rawName);
45241                     }
45242                     else if (maybeMappedType(errorLocation, symbol)) {
45243                         error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0, rawName, rawName === "K" ? "P" : "K");
45244                     }
45245                     else {
45246                         error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName);
45247                     }
45248                     return true;
45249                 }
45250             }
45251             return false;
45252         }
45253         function maybeMappedType(node, symbol) {
45254             var container = ts.findAncestor(node.parent, function (n) {
45255                 return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit";
45256             });
45257             if (container && container.members.length === 1) {
45258                 var type = getDeclaredTypeOfSymbol(symbol);
45259                 return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true);
45260             }
45261             return false;
45262         }
45263         function isES2015OrLaterConstructorName(n) {
45264             switch (n) {
45265                 case "Promise":
45266                 case "Symbol":
45267                 case "Map":
45268                 case "WeakMap":
45269                 case "Set":
45270                 case "WeakSet":
45271                     return true;
45272             }
45273             return false;
45274         }
45275         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
45276             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
45277                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45278                 if (symbol) {
45279                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
45280                     return true;
45281                 }
45282             }
45283             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
45284                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45285                 if (symbol) {
45286                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
45287                     return true;
45288                 }
45289             }
45290             return false;
45291         }
45292         function checkResolvedBlockScopedVariable(result, errorLocation) {
45293             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
45294             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
45295                 // constructor functions aren't block scoped
45296                 return;
45297             }
45298             // Block-scoped variables cannot be used before their definition
45299             var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 255 /* EnumDeclaration */); });
45300             if (declaration === undefined)
45301                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
45302             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
45303                 var diagnosticMessage = void 0;
45304                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
45305                 if (result.flags & 2 /* BlockScopedVariable */) {
45306                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
45307                 }
45308                 else if (result.flags & 32 /* Class */) {
45309                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
45310                 }
45311                 else if (result.flags & 256 /* RegularEnum */) {
45312                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
45313                 }
45314                 else {
45315                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
45316                     if (compilerOptions.preserveConstEnums) {
45317                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
45318                     }
45319                 }
45320                 if (diagnosticMessage) {
45321                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
45322                 }
45323             }
45324         }
45325         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
45326          * If at any point current node is equal to 'parent' node - return true.
45327          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
45328          */
45329         function isSameScopeDescendentOf(initial, parent, stopAt) {
45330             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
45331         }
45332         function getAnyImportSyntax(node) {
45333             switch (node.kind) {
45334                 case 260 /* ImportEqualsDeclaration */:
45335                     return node;
45336                 case 262 /* ImportClause */:
45337                     return node.parent;
45338                 case 263 /* NamespaceImport */:
45339                     return node.parent.parent;
45340                 case 265 /* ImportSpecifier */:
45341                     return node.parent.parent.parent;
45342                 default:
45343                     return undefined;
45344             }
45345         }
45346         function getDeclarationOfAliasSymbol(symbol) {
45347             return ts.find(symbol.declarations, isAliasSymbolDeclaration);
45348         }
45349         /**
45350          * An alias symbol is created by one of the following declarations:
45351          * import <symbol> = ...
45352          * import <symbol> from ...
45353          * import * as <symbol> from ...
45354          * import { x as <symbol> } from ...
45355          * export { x as <symbol> } from ...
45356          * export * as ns <symbol> from ...
45357          * export = <EntityNameExpression>
45358          * export default <EntityNameExpression>
45359          * module.exports = <EntityNameExpression>
45360          * {<Identifier>}
45361          * {name: <EntityNameExpression>}
45362          */
45363         function isAliasSymbolDeclaration(node) {
45364             return node.kind === 260 /* ImportEqualsDeclaration */
45365                 || node.kind === 259 /* NamespaceExportDeclaration */
45366                 || node.kind === 262 /* ImportClause */ && !!node.name
45367                 || node.kind === 263 /* NamespaceImport */
45368                 || node.kind === 269 /* NamespaceExport */
45369                 || node.kind === 265 /* ImportSpecifier */
45370                 || node.kind === 270 /* ExportSpecifier */
45371                 || node.kind === 266 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node)
45372                 || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node)
45373                 || ts.isAccessExpression(node)
45374                     && ts.isBinaryExpression(node.parent)
45375                     && node.parent.left === node
45376                     && node.parent.operatorToken.kind === 62 /* EqualsToken */
45377                     && isAliasableOrJsExpression(node.parent.right)
45378                 || node.kind === 289 /* ShorthandPropertyAssignment */
45379                 || node.kind === 288 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer)
45380                 || ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true);
45381         }
45382         function isAliasableOrJsExpression(e) {
45383             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
45384         }
45385         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
45386             var commonJSPropertyAccess = getCommonJSPropertyAccess(node);
45387             if (commonJSPropertyAccess) {
45388                 var name = ts.getLeftmostAccessExpression(commonJSPropertyAccess.expression).arguments[0];
45389                 return ts.isIdentifier(commonJSPropertyAccess.name)
45390                     ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText))
45391                     : undefined;
45392             }
45393             if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 272 /* ExternalModuleReference */) {
45394                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node));
45395                 var resolved_4 = resolveExternalModuleSymbol(immediate);
45396                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
45397                 return resolved_4;
45398             }
45399             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
45400             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
45401             return resolved;
45402         }
45403         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
45404             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
45405                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
45406                 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
45407                 var message = isExport
45408                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
45409                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
45410                 var relatedMessage = isExport
45411                     ? ts.Diagnostics._0_was_exported_here
45412                     : ts.Diagnostics._0_was_imported_here;
45413                 // Non-null assertion is safe because the optionality comes from ImportClause,
45414                 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
45415                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
45416                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
45417             }
45418         }
45419         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
45420             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
45421             var exportSymbol = exportValue ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : moduleSymbol.exports.get(name);
45422             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
45423             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
45424             return resolved;
45425         }
45426         function isSyntacticDefault(node) {
45427             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
45428         }
45429         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
45430             if (!allowSyntheticDefaultImports) {
45431                 return false;
45432             }
45433             // Declaration files (and ambient modules)
45434             if (!file || file.isDeclarationFile) {
45435                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
45436                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
45437                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
45438                     return false;
45439                 }
45440                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
45441                 // So we check a bit more,
45442                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
45443                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
45444                     // it definitely is a module and does not have a synthetic default
45445                     return false;
45446                 }
45447                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
45448                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
45449                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
45450                 return true;
45451             }
45452             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
45453             if (!ts.isSourceFileJS(file)) {
45454                 return hasExportAssignmentSymbol(moduleSymbol);
45455             }
45456             // 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
45457             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
45458         }
45459         function getTargetOfImportClause(node, dontResolveAlias) {
45460             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
45461             if (moduleSymbol) {
45462                 var exportDefaultSymbol = void 0;
45463                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
45464                     exportDefaultSymbol = moduleSymbol;
45465                 }
45466                 else {
45467                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
45468                 }
45469                 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
45470                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
45471                 if (!exportDefaultSymbol && !hasSyntheticDefault) {
45472                     if (hasExportAssignmentSymbol(moduleSymbol)) {
45473                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
45474                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
45475                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
45476                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
45477                         ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName));
45478                     }
45479                     else {
45480                         reportNonDefaultExport(moduleSymbol, node);
45481                     }
45482                 }
45483                 else if (hasSyntheticDefault) {
45484                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
45485                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
45486                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
45487                     return resolved;
45488                 }
45489                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
45490                 return exportDefaultSymbol;
45491             }
45492         }
45493         function reportNonDefaultExport(moduleSymbol, node) {
45494             var _a, _b;
45495             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
45496                 error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol));
45497             }
45498             else {
45499                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
45500                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
45501                 if (exportStar) {
45502                     var defaultExport = ts.find(exportStar.declarations, function (decl) {
45503                         var _a, _b;
45504                         return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)));
45505                     });
45506                     if (defaultExport) {
45507                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
45508                     }
45509                 }
45510             }
45511         }
45512         function getTargetOfNamespaceImport(node, dontResolveAlias) {
45513             var moduleSpecifier = node.parent.parent.moduleSpecifier;
45514             var immediate = resolveExternalModuleName(node, moduleSpecifier);
45515             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
45516             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
45517             return resolved;
45518         }
45519         function getTargetOfNamespaceExport(node, dontResolveAlias) {
45520             var moduleSpecifier = node.parent.moduleSpecifier;
45521             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
45522             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
45523             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
45524             return resolved;
45525         }
45526         // This function creates a synthetic symbol that combines the value side of one symbol with the
45527         // type/namespace side of another symbol. Consider this example:
45528         //
45529         //   declare module graphics {
45530         //       interface Point {
45531         //           x: number;
45532         //           y: number;
45533         //       }
45534         //   }
45535         //   declare var graphics: {
45536         //       Point: new (x: number, y: number) => graphics.Point;
45537         //   }
45538         //   declare module "graphics" {
45539         //       export = graphics;
45540         //   }
45541         //
45542         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
45543         // property with the type/namespace side interface 'Point'.
45544         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
45545             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
45546                 return unknownSymbol;
45547             }
45548             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
45549                 return valueSymbol;
45550             }
45551             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
45552             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
45553             result.parent = valueSymbol.parent || typeSymbol.parent;
45554             if (valueSymbol.valueDeclaration)
45555                 result.valueDeclaration = valueSymbol.valueDeclaration;
45556             if (typeSymbol.members)
45557                 result.members = new ts.Map(typeSymbol.members);
45558             if (valueSymbol.exports)
45559                 result.exports = new ts.Map(valueSymbol.exports);
45560             return result;
45561         }
45562         function getExportOfModule(symbol, name, specifier, dontResolveAlias) {
45563             if (symbol.flags & 1536 /* Module */) {
45564                 var exportSymbol = getExportsOfSymbol(symbol).get(name.escapedText);
45565                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
45566                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
45567                 return resolved;
45568             }
45569         }
45570         function getPropertyOfVariable(symbol, name) {
45571             if (symbol.flags & 3 /* Variable */) {
45572                 var typeAnnotation = symbol.valueDeclaration.type;
45573                 if (typeAnnotation) {
45574                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
45575                 }
45576             }
45577         }
45578         function getExternalModuleMember(node, specifier, dontResolveAlias) {
45579             var _a;
45580             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
45581             var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier;
45582             var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217
45583             var name = !ts.isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name;
45584             if (!ts.isIdentifier(name)) {
45585                 return undefined;
45586             }
45587             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
45588             var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError);
45589             if (targetSymbol) {
45590                 if (name.escapedText) {
45591                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
45592                         return moduleSymbol;
45593                     }
45594                     var symbolFromVariable = void 0;
45595                     // First check if module was specified with "export=". If so, get the member from the resolved type
45596                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
45597                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
45598                     }
45599                     else {
45600                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
45601                     }
45602                     // if symbolFromVariable is export - get its final target
45603                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
45604                     var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias);
45605                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
45606                         var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
45607                         if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
45608                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
45609                         }
45610                     }
45611                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
45612                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
45613                         symbolFromModule || symbolFromVariable;
45614                     if (!symbol) {
45615                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
45616                         var declarationName = ts.declarationNameToString(name);
45617                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
45618                         if (suggestion !== undefined) {
45619                             var suggestionName = symbolToString(suggestion);
45620                             var diagnostic = error(name, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
45621                             if (suggestion.valueDeclaration) {
45622                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
45623                             }
45624                         }
45625                         else {
45626                             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
45627                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
45628                             }
45629                             else {
45630                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
45631                             }
45632                         }
45633                     }
45634                     return symbol;
45635                 }
45636             }
45637         }
45638         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
45639             var _a;
45640             var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
45641             var exports = moduleSymbol.exports;
45642             if (localSymbol) {
45643                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
45644                 if (exportedEqualsSymbol) {
45645                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
45646                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
45647                 }
45648                 else {
45649                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
45650                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
45651                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
45652                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
45653                         return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
45654                     })));
45655                 }
45656             }
45657             else {
45658                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
45659             }
45660         }
45661         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
45662             if (moduleKind >= ts.ModuleKind.ES2015) {
45663                 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
45664                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
45665                 error(name, message, declarationName);
45666             }
45667             else {
45668                 if (ts.isInJSFile(node)) {
45669                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
45670                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
45671                     error(name, message, declarationName);
45672                 }
45673                 else {
45674                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
45675                         ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
45676                     error(name, message, declarationName, declarationName, moduleName);
45677                 }
45678             }
45679         }
45680         function getTargetOfImportSpecifier(node, dontResolveAlias) {
45681             var root = ts.isBindingElement(node) ? ts.getRootDeclaration(node) : node.parent.parent.parent;
45682             var commonJSPropertyAccess = getCommonJSPropertyAccess(root);
45683             var resolved = getExternalModuleMember(root, commonJSPropertyAccess || node, dontResolveAlias);
45684             var name = node.propertyName || node.name;
45685             if (commonJSPropertyAccess && resolved && ts.isIdentifier(name)) {
45686                 return resolveSymbol(getPropertyOfType(getTypeOfSymbol(resolved), name.escapedText), dontResolveAlias);
45687             }
45688             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
45689             return resolved;
45690         }
45691         function getCommonJSPropertyAccess(node) {
45692             if (ts.isVariableDeclaration(node) && node.initializer && ts.isPropertyAccessExpression(node.initializer)) {
45693                 return node.initializer;
45694             }
45695         }
45696         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
45697             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
45698             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
45699             return resolved;
45700         }
45701         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
45702             var resolved = node.parent.parent.moduleSpecifier ?
45703                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
45704                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
45705             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
45706             return resolved;
45707         }
45708         function getTargetOfExportAssignment(node, dontResolveAlias) {
45709             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
45710             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
45711             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
45712             return resolved;
45713         }
45714         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
45715             if (ts.isClassExpression(expression)) {
45716                 return checkExpressionCached(expression).symbol;
45717             }
45718             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
45719                 return undefined;
45720             }
45721             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
45722             if (aliasLike) {
45723                 return aliasLike;
45724             }
45725             checkExpressionCached(expression);
45726             return getNodeLinks(expression).resolvedSymbol;
45727         }
45728         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
45729             var expression = node.initializer;
45730             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
45731         }
45732         function getTargetOfAccessExpression(node, dontRecursivelyResolve) {
45733             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
45734                 return undefined;
45735             }
45736             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
45737         }
45738         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
45739             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
45740             switch (node.kind) {
45741                 case 260 /* ImportEqualsDeclaration */:
45742                 case 249 /* VariableDeclaration */:
45743                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
45744                 case 262 /* ImportClause */:
45745                     return getTargetOfImportClause(node, dontRecursivelyResolve);
45746                 case 263 /* NamespaceImport */:
45747                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
45748                 case 269 /* NamespaceExport */:
45749                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
45750                 case 265 /* ImportSpecifier */:
45751                 case 198 /* BindingElement */:
45752                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
45753                 case 270 /* ExportSpecifier */:
45754                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
45755                 case 266 /* ExportAssignment */:
45756                 case 216 /* BinaryExpression */:
45757                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
45758                 case 259 /* NamespaceExportDeclaration */:
45759                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
45760                 case 289 /* ShorthandPropertyAssignment */:
45761                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
45762                 case 288 /* PropertyAssignment */:
45763                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
45764                 case 202 /* ElementAccessExpression */:
45765                 case 201 /* PropertyAccessExpression */:
45766                     return getTargetOfAccessExpression(node, dontRecursivelyResolve);
45767                 default:
45768                     return ts.Debug.fail();
45769             }
45770         }
45771         /**
45772          * Indicates that a symbol is an alias that does not merge with a local declaration.
45773          * OR Is a JSContainer which may merge an alias with a local declaration
45774          */
45775         function isNonLocalAlias(symbol, excludes) {
45776             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
45777             if (!symbol)
45778                 return false;
45779             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
45780         }
45781         function resolveSymbol(symbol, dontResolveAlias) {
45782             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
45783         }
45784         function resolveAlias(symbol) {
45785             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
45786             var links = getSymbolLinks(symbol);
45787             if (!links.target) {
45788                 links.target = resolvingSymbol;
45789                 var node = getDeclarationOfAliasSymbol(symbol);
45790                 if (!node)
45791                     return ts.Debug.fail();
45792                 var target = getTargetOfAliasDeclaration(node);
45793                 if (links.target === resolvingSymbol) {
45794                     links.target = target || unknownSymbol;
45795                 }
45796                 else {
45797                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
45798                 }
45799             }
45800             else if (links.target === resolvingSymbol) {
45801                 links.target = unknownSymbol;
45802             }
45803             return links.target;
45804         }
45805         function tryResolveAlias(symbol) {
45806             var links = getSymbolLinks(symbol);
45807             if (links.target !== resolvingSymbol) {
45808                 return resolveAlias(symbol);
45809             }
45810             return undefined;
45811         }
45812         /**
45813          * Marks a symbol as type-only if its declaration is syntactically type-only.
45814          * If it is not itself marked type-only, but resolves to a type-only alias
45815          * somewhere in its resolution chain, save a reference to the type-only alias declaration
45816          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
45817          *
45818          * This function is called on each alias declaration that could be type-only or resolve to
45819          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
45820          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
45821          * and issue an error if so.
45822          *
45823          * @param aliasDeclaration The alias declaration not marked as type-only
45824          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
45825          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
45826          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
45827          * must still be checked for a type-only marker, overwriting the previous negative result if found.
45828          * @param immediateTarget The symbol to which the alias declaration immediately resolves
45829          * @param finalTarget The symbol to which the alias declaration ultimately resolves
45830          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
45831          */
45832         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
45833             if (!aliasDeclaration || ts.isPropertyAccessExpression(aliasDeclaration))
45834                 return false;
45835             // If the declaration itself is type-only, mark it and return.
45836             // No need to check what it resolves to.
45837             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
45838             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
45839                 var links_1 = getSymbolLinks(sourceSymbol);
45840                 links_1.typeOnlyDeclaration = aliasDeclaration;
45841                 return true;
45842             }
45843             var links = getSymbolLinks(sourceSymbol);
45844             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
45845                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
45846         }
45847         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
45848             var _a, _b, _c;
45849             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
45850                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
45851                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
45852                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
45853             }
45854             return !!aliasDeclarationLinks.typeOnlyDeclaration;
45855         }
45856         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
45857         function getTypeOnlyAliasDeclaration(symbol) {
45858             if (!(symbol.flags & 2097152 /* Alias */)) {
45859                 return undefined;
45860             }
45861             var links = getSymbolLinks(symbol);
45862             return links.typeOnlyDeclaration || undefined;
45863         }
45864         function markExportAsReferenced(node) {
45865             var symbol = getSymbolOfNode(node);
45866             var target = resolveAlias(symbol);
45867             if (target) {
45868                 var markAlias = target === unknownSymbol ||
45869                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
45870                 if (markAlias) {
45871                     markAliasSymbolAsReferenced(symbol);
45872                 }
45873             }
45874         }
45875         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
45876         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
45877         // the alias as an expression (which recursively takes us back here if the target references another alias).
45878         function markAliasSymbolAsReferenced(symbol) {
45879             var links = getSymbolLinks(symbol);
45880             if (!links.referenced) {
45881                 links.referenced = true;
45882                 var node = getDeclarationOfAliasSymbol(symbol);
45883                 if (!node)
45884                     return ts.Debug.fail();
45885                 // We defer checking of the reference of an `import =` until the import itself is referenced,
45886                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
45887                 // position.
45888                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
45889                     var target = resolveSymbol(symbol);
45890                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
45891                         // import foo = <symbol>
45892                         checkExpressionCached(node.moduleReference);
45893                     }
45894                 }
45895             }
45896         }
45897         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
45898         // but their usage in value positions must be tracked to determine if the import can be type-only.
45899         function markConstEnumAliasAsReferenced(symbol) {
45900             var links = getSymbolLinks(symbol);
45901             if (!links.constEnumReferenced) {
45902                 links.constEnumReferenced = true;
45903             }
45904         }
45905         // This function is only for imports with entity names
45906         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
45907             // There are three things we might try to look for. In the following examples,
45908             // the search term is enclosed in |...|:
45909             //
45910             //     import a = |b|; // Namespace
45911             //     import a = |b.c|; // Value, type, namespace
45912             //     import a = |b.c|.d; // Namespace
45913             if (entityName.kind === 78 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
45914                 entityName = entityName.parent;
45915             }
45916             // Check for case 1 and 3 in the above example
45917             if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 157 /* QualifiedName */) {
45918                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
45919             }
45920             else {
45921                 // Case 2 in above example
45922                 // entityName.kind could be a QualifiedName or a Missing identifier
45923                 ts.Debug.assert(entityName.parent.kind === 260 /* ImportEqualsDeclaration */);
45924                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
45925             }
45926         }
45927         function getFullyQualifiedName(symbol, containingLocation) {
45928             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
45929         }
45930         /**
45931          * Resolves a qualified name and any involved aliases.
45932          */
45933         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
45934             if (ts.nodeIsMissing(name)) {
45935                 return undefined;
45936             }
45937             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
45938             var symbol;
45939             if (name.kind === 78 /* Identifier */) {
45940                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
45941                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
45942                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
45943                 if (!symbol) {
45944                     return getMergedSymbol(symbolFromJSPrototype);
45945                 }
45946             }
45947             else if (name.kind === 157 /* QualifiedName */ || name.kind === 201 /* PropertyAccessExpression */) {
45948                 var left = name.kind === 157 /* QualifiedName */ ? name.left : name.expression;
45949                 var right = name.kind === 157 /* QualifiedName */ ? name.right : name.name;
45950                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
45951                 if (!namespace || ts.nodeIsMissing(right)) {
45952                     return undefined;
45953                 }
45954                 else if (namespace === unknownSymbol) {
45955                     return namespace;
45956                 }
45957                 if (ts.isInJSFile(name)) {
45958                     if (namespace.valueDeclaration &&
45959                         ts.isVariableDeclaration(namespace.valueDeclaration) &&
45960                         namespace.valueDeclaration.initializer &&
45961                         isCommonJsRequire(namespace.valueDeclaration.initializer)) {
45962                         var moduleName = namespace.valueDeclaration.initializer.arguments[0];
45963                         var moduleSym = resolveExternalModuleName(moduleName, moduleName);
45964                         if (moduleSym) {
45965                             var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
45966                             if (resolvedModuleSymbol) {
45967                                 namespace = resolvedModuleSymbol;
45968                             }
45969                         }
45970                     }
45971                 }
45972                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
45973                 if (!symbol) {
45974                     if (!ignoreErrors) {
45975                         var namespaceName = getFullyQualifiedName(namespace);
45976                         var declarationName = ts.declarationNameToString(right);
45977                         var suggestion = getSuggestedSymbolForNonexistentModule(right, namespace);
45978                         suggestion ?
45979                             error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestion)) :
45980                             error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName);
45981                     }
45982                     return undefined;
45983                 }
45984             }
45985             else {
45986                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
45987             }
45988             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
45989             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 266 /* ExportAssignment */)) {
45990                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
45991             }
45992             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
45993         }
45994         /**
45995          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
45996          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
45997          * name resolution won't work either.
45998          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
45999          */
46000         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
46001             if (isJSDocTypeReference(name.parent)) {
46002                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
46003                 if (secondaryLocation) {
46004                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
46005                 }
46006             }
46007         }
46008         function getAssignmentDeclarationLocation(node) {
46009             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
46010             if (typeAlias) {
46011                 return;
46012             }
46013             var host = ts.getJSDocHost(node);
46014             if (ts.isExpressionStatement(host) &&
46015                 ts.isBinaryExpression(host.expression) &&
46016                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
46017                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
46018                 var symbol = getSymbolOfNode(host.expression.left);
46019                 if (symbol) {
46020                     return getDeclarationOfJSPrototypeContainer(symbol);
46021                 }
46022             }
46023             if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
46024                 ts.isBinaryExpression(host.parent.parent) &&
46025                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
46026                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
46027                 var symbol = getSymbolOfNode(host.parent.parent.left);
46028                 if (symbol) {
46029                     return getDeclarationOfJSPrototypeContainer(symbol);
46030                 }
46031             }
46032             var sig = ts.getEffectiveJSDocHost(node);
46033             if (sig && ts.isFunctionLike(sig)) {
46034                 var symbol = getSymbolOfNode(sig);
46035                 return symbol && symbol.valueDeclaration;
46036             }
46037         }
46038         function getDeclarationOfJSPrototypeContainer(symbol) {
46039             var decl = symbol.parent.valueDeclaration;
46040             if (!decl) {
46041                 return undefined;
46042             }
46043             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
46044                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
46045                     undefined;
46046             return initializer || decl;
46047         }
46048         /**
46049          * Get the real symbol of a declaration with an expando initializer.
46050          *
46051          * Normally, declarations have an associated symbol, but when a declaration has an expando
46052          * initializer, the expando's symbol is the one that has all the members merged into it.
46053          */
46054         function getExpandoSymbol(symbol) {
46055             var decl = symbol.valueDeclaration;
46056             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
46057                 return undefined;
46058             }
46059             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
46060             if (init) {
46061                 var initSymbol = getSymbolOfNode(init);
46062                 if (initSymbol) {
46063                     return mergeJSSymbols(initSymbol, symbol);
46064                 }
46065             }
46066         }
46067         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
46068             var isClassic = ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Classic;
46069             var errorMessage = isClassic ?
46070                 ts.Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
46071                 : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
46072             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : errorMessage);
46073         }
46074         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
46075             if (isForAugmentation === void 0) { isForAugmentation = false; }
46076             return ts.isStringLiteralLike(moduleReferenceExpression)
46077                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
46078                 : undefined;
46079         }
46080         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
46081             if (isForAugmentation === void 0) { isForAugmentation = false; }
46082             if (ts.startsWith(moduleReference, "@types/")) {
46083                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
46084                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
46085                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
46086             }
46087             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
46088             if (ambientModule) {
46089                 return ambientModule;
46090             }
46091             var currentSourceFile = ts.getSourceFileOfNode(location);
46092             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
46093             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
46094             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
46095             if (sourceFile) {
46096                 if (sourceFile.symbol) {
46097                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
46098                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
46099                     }
46100                     // merged symbol is module declaration symbol combined with all augmentations
46101                     return getMergedSymbol(sourceFile.symbol);
46102                 }
46103                 if (moduleNotFoundError) {
46104                     // report errors only if it was requested
46105                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
46106                 }
46107                 return undefined;
46108             }
46109             if (patternAmbientModules) {
46110                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
46111                 if (pattern) {
46112                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
46113                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
46114                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
46115                     // from a.foo.
46116                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
46117                     if (augmentation) {
46118                         return getMergedSymbol(augmentation);
46119                     }
46120                     return getMergedSymbol(pattern.symbol);
46121                 }
46122             }
46123             // May be an untyped module. If so, ignore resolutionDiagnostic.
46124             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) {
46125                 if (isForAugmentation) {
46126                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
46127                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
46128                 }
46129                 else {
46130                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
46131                 }
46132                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
46133                 return undefined;
46134             }
46135             if (moduleNotFoundError) {
46136                 // See if this was possibly a projectReference redirect
46137                 if (resolvedModule) {
46138                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
46139                     if (redirect) {
46140                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
46141                         return undefined;
46142                     }
46143                 }
46144                 if (resolutionDiagnostic) {
46145                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
46146                 }
46147                 else {
46148                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
46149                     if (tsExtension) {
46150                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
46151                         error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
46152                     }
46153                     else if (!compilerOptions.resolveJsonModule &&
46154                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
46155                         ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
46156                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
46157                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
46158                     }
46159                     else {
46160                         error(errorNode, moduleNotFoundError, moduleReference);
46161                     }
46162                 }
46163             }
46164             return undefined;
46165         }
46166         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
46167             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
46168             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
46169                 ? typesPackageExists(packageId.name)
46170                     ? ts.chainDiagnosticMessages(
46171                     /*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))
46172                     : ts.chainDiagnosticMessages(
46173                     /*details*/ undefined, ts.Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name))
46174                 : undefined;
46175             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));
46176         }
46177         function typesPackageExists(packageName) {
46178             return getPackagesSet().has(ts.getTypesPackageName(packageName));
46179         }
46180         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
46181             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
46182                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
46183                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
46184                 return getMergedSymbol(exported) || moduleSymbol;
46185             }
46186             return undefined;
46187         }
46188         function getCommonJsExportEquals(exported, moduleSymbol) {
46189             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
46190                 return exported;
46191             }
46192             var links = getSymbolLinks(exported);
46193             if (links.cjsExportMerged) {
46194                 return links.cjsExportMerged;
46195             }
46196             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
46197             merged.flags = merged.flags | 512 /* ValueModule */;
46198             if (merged.exports === undefined) {
46199                 merged.exports = ts.createSymbolTable();
46200             }
46201             moduleSymbol.exports.forEach(function (s, name) {
46202                 if (name === "export=" /* ExportEquals */)
46203                     return;
46204                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
46205             });
46206             getSymbolLinks(merged).cjsExportMerged = merged;
46207             return links.cjsExportMerged = merged;
46208         }
46209         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
46210         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
46211         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
46212         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
46213             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
46214             if (!dontResolveAlias && symbol) {
46215                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 297 /* SourceFile */)) {
46216                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
46217                         ? "allowSyntheticDefaultImports"
46218                         : "esModuleInterop";
46219                     error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName);
46220                     return symbol;
46221                 }
46222                 if (compilerOptions.esModuleInterop) {
46223                     var referenceParent = referencingLocation.parent;
46224                     if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
46225                         ts.isImportCall(referenceParent)) {
46226                         var type = getTypeOfSymbol(symbol);
46227                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
46228                         if (!sigs || !sigs.length) {
46229                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
46230                         }
46231                         if (sigs && sigs.length) {
46232                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
46233                             // Create a new symbol which has the module's type less the call and construct signatures
46234                             var result = createSymbol(symbol.flags, symbol.escapedName);
46235                             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
46236                             result.parent = symbol.parent;
46237                             result.target = symbol;
46238                             result.originatingImport = referenceParent;
46239                             if (symbol.valueDeclaration)
46240                                 result.valueDeclaration = symbol.valueDeclaration;
46241                             if (symbol.constEnumOnlyModule)
46242                                 result.constEnumOnlyModule = true;
46243                             if (symbol.members)
46244                                 result.members = new ts.Map(symbol.members);
46245                             if (symbol.exports)
46246                                 result.exports = new ts.Map(symbol.exports);
46247                             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
46248                             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
46249                             return result;
46250                         }
46251                     }
46252                 }
46253             }
46254             return symbol;
46255         }
46256         function hasExportAssignmentSymbol(moduleSymbol) {
46257             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
46258         }
46259         function getExportsOfModuleAsArray(moduleSymbol) {
46260             return symbolsToArray(getExportsOfModule(moduleSymbol));
46261         }
46262         function getExportsAndPropertiesOfModule(moduleSymbol) {
46263             var exports = getExportsOfModuleAsArray(moduleSymbol);
46264             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
46265             if (exportEquals !== moduleSymbol) {
46266                 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
46267             }
46268             return exports;
46269         }
46270         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
46271             var symbolTable = getExportsOfModule(moduleSymbol);
46272             if (symbolTable) {
46273                 return symbolTable.get(memberName);
46274             }
46275         }
46276         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
46277             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
46278             if (symbol) {
46279                 return symbol;
46280             }
46281             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
46282             if (exportEquals === moduleSymbol) {
46283                 return undefined;
46284             }
46285             var type = getTypeOfSymbol(exportEquals);
46286             return type.flags & 131068 /* Primitive */ ||
46287                 ts.getObjectFlags(type) & 1 /* Class */ ||
46288                 isArrayOrTupleLikeType(type)
46289                 ? undefined
46290                 : getPropertyOfType(type, memberName);
46291         }
46292         function getExportsOfSymbol(symbol) {
46293             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
46294                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
46295                     symbol.exports || emptySymbols;
46296         }
46297         function getExportsOfModule(moduleSymbol) {
46298             var links = getSymbolLinks(moduleSymbol);
46299             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
46300         }
46301         /**
46302          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
46303          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
46304          */
46305         function extendExportSymbols(target, source, lookupTable, exportNode) {
46306             if (!source)
46307                 return;
46308             source.forEach(function (sourceSymbol, id) {
46309                 if (id === "default" /* Default */)
46310                     return;
46311                 var targetSymbol = target.get(id);
46312                 if (!targetSymbol) {
46313                     target.set(id, sourceSymbol);
46314                     if (lookupTable && exportNode) {
46315                         lookupTable.set(id, {
46316                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
46317                         });
46318                     }
46319                 }
46320                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
46321                     var collisionTracker = lookupTable.get(id);
46322                     if (!collisionTracker.exportsWithDuplicate) {
46323                         collisionTracker.exportsWithDuplicate = [exportNode];
46324                     }
46325                     else {
46326                         collisionTracker.exportsWithDuplicate.push(exportNode);
46327                     }
46328                 }
46329             });
46330         }
46331         function getExportsOfModuleWorker(moduleSymbol) {
46332             var visitedSymbols = [];
46333             // A module defined by an 'export=' consists of one export that needs to be resolved
46334             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
46335             return visit(moduleSymbol) || emptySymbols;
46336             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
46337             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
46338             function visit(symbol) {
46339                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
46340                     return;
46341                 }
46342                 var symbols = new ts.Map(symbol.exports);
46343                 // All export * declarations are collected in an __export symbol by the binder
46344                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
46345                 if (exportStars) {
46346                     var nestedSymbols = ts.createSymbolTable();
46347                     var lookupTable_1 = new ts.Map();
46348                     for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
46349                         var node = _a[_i];
46350                         var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
46351                         var exportedSymbols = visit(resolvedModule);
46352                         extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
46353                     }
46354                     lookupTable_1.forEach(function (_a, id) {
46355                         var exportsWithDuplicate = _a.exportsWithDuplicate;
46356                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
46357                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
46358                             return;
46359                         }
46360                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
46361                             var node = exportsWithDuplicate_1[_i];
46362                             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)));
46363                         }
46364                     });
46365                     extendExportSymbols(symbols, nestedSymbols);
46366                 }
46367                 return symbols;
46368             }
46369         }
46370         function getMergedSymbol(symbol) {
46371             var merged;
46372             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
46373         }
46374         function getSymbolOfNode(node) {
46375             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
46376         }
46377         function getParentOfSymbol(symbol) {
46378             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
46379         }
46380         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
46381             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
46382             var id = getNodeId(containingFile);
46383             var links = getSymbolLinks(symbol);
46384             var results;
46385             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
46386                 return results;
46387             }
46388             if (containingFile && containingFile.imports) {
46389                 // Try to make an import using an import already in the enclosing file, if possible
46390                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
46391                     var importRef = _a[_i];
46392                     if (ts.nodeIsSynthesized(importRef))
46393                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
46394                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
46395                     if (!resolvedModule)
46396                         continue;
46397                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
46398                     if (!ref)
46399                         continue;
46400                     results = ts.append(results, resolvedModule);
46401                 }
46402                 if (ts.length(results)) {
46403                     (links.extendedContainersByFile || (links.extendedContainersByFile = new ts.Map())).set(id, results);
46404                     return results;
46405                 }
46406             }
46407             if (links.extendedContainers) {
46408                 return links.extendedContainers;
46409             }
46410             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
46411             var otherFiles = host.getSourceFiles();
46412             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
46413                 var file = otherFiles_1[_b];
46414                 if (!ts.isExternalModule(file))
46415                     continue;
46416                 var sym = getSymbolOfNode(file);
46417                 var ref = getAliasForSymbolInContainer(sym, symbol);
46418                 if (!ref)
46419                     continue;
46420                 results = ts.append(results, sym);
46421             }
46422             return links.extendedContainers = results || ts.emptyArray;
46423         }
46424         /**
46425          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
46426          * is just its' `.parent`, but for locals, this value is `undefined`
46427          */
46428         function getContainersOfSymbol(symbol, enclosingDeclaration, meaning) {
46429             var container = getParentOfSymbol(symbol);
46430             // Type parameters end up in the `members` lists but are not externally visible
46431             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
46432                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
46433                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
46434                 var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning);
46435                 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
46436                     return ts.append(ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); // This order expresses a preference for the real container if it is in scope
46437                 }
46438                 var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer);
46439                 return ts.concatenate(res, reexportContainers);
46440             }
46441             var candidates = ts.mapDefined(symbol.declarations, function (d) {
46442                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
46443                     return getSymbolOfNode(d.parent);
46444                 }
46445                 if (ts.isClassExpression(d) && ts.isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isAccessExpression(d.parent.left) && ts.isEntityNameExpression(d.parent.left.expression)) {
46446                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
46447                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
46448                     }
46449                     checkExpressionCached(d.parent.left.expression);
46450                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
46451                 }
46452             });
46453             if (!ts.length(candidates)) {
46454                 return undefined;
46455             }
46456             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
46457             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
46458                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
46459             }
46460         }
46461         function getVariableDeclarationOfObjectLiteral(symbol, meaning) {
46462             // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
46463             // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
46464             // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
46465             var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
46466             if (meaning & 111551 /* Value */ && firstDecl && firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent)) {
46467                 if (ts.isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || ts.isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) {
46468                     return getSymbolOfNode(firstDecl.parent);
46469                 }
46470             }
46471         }
46472         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
46473             var fileSymbol = getExternalModuleContainer(d);
46474             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
46475             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
46476         }
46477         function getAliasForSymbolInContainer(container, symbol) {
46478             if (container === getParentOfSymbol(symbol)) {
46479                 // fast path, `symbol` is either already the alias or isn't aliased
46480                 return symbol;
46481             }
46482             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
46483             // the container itself as the alias for the symbol
46484             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
46485             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
46486                 return container;
46487             }
46488             var exports = getExportsOfSymbol(container);
46489             var quick = exports.get(symbol.escapedName);
46490             if (quick && getSymbolIfSameReference(quick, symbol)) {
46491                 return quick;
46492             }
46493             return ts.forEachEntry(exports, function (exported) {
46494                 if (getSymbolIfSameReference(exported, symbol)) {
46495                     return exported;
46496                 }
46497             });
46498         }
46499         /**
46500          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
46501          */
46502         function getSymbolIfSameReference(s1, s2) {
46503             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
46504                 return s1;
46505             }
46506         }
46507         function getExportSymbolOfValueSymbolIfExported(symbol) {
46508             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
46509         }
46510         function symbolIsValue(symbol) {
46511             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
46512         }
46513         function findConstructorDeclaration(node) {
46514             var members = node.members;
46515             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
46516                 var member = members_3[_i];
46517                 if (member.kind === 166 /* Constructor */ && ts.nodeIsPresent(member.body)) {
46518                     return member;
46519                 }
46520             }
46521         }
46522         function createType(flags) {
46523             var result = new Type(checker, flags);
46524             typeCount++;
46525             result.id = typeCount;
46526             typeCatalog.push(result);
46527             return result;
46528         }
46529         function createIntrinsicType(kind, intrinsicName, objectFlags) {
46530             if (objectFlags === void 0) { objectFlags = 0; }
46531             var type = createType(kind);
46532             type.intrinsicName = intrinsicName;
46533             type.objectFlags = objectFlags;
46534             return type;
46535         }
46536         function createBooleanType(trueFalseTypes) {
46537             var type = getUnionType(trueFalseTypes);
46538             type.flags |= 16 /* Boolean */;
46539             type.intrinsicName = "boolean";
46540             return type;
46541         }
46542         function createObjectType(objectFlags, symbol) {
46543             var type = createType(524288 /* Object */);
46544             type.objectFlags = objectFlags;
46545             type.symbol = symbol;
46546             type.members = undefined;
46547             type.properties = undefined;
46548             type.callSignatures = undefined;
46549             type.constructSignatures = undefined;
46550             type.stringIndexInfo = undefined;
46551             type.numberIndexInfo = undefined;
46552             return type;
46553         }
46554         function createTypeofType() {
46555             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
46556         }
46557         function createTypeParameter(symbol) {
46558             var type = createType(262144 /* TypeParameter */);
46559             if (symbol)
46560                 type.symbol = symbol;
46561             return type;
46562         }
46563         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
46564         // @, or #. A third underscore indicates an escaped form of an identifier that started
46565         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
46566         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
46567         function isReservedMemberName(name) {
46568             return name.charCodeAt(0) === 95 /* _ */ &&
46569                 name.charCodeAt(1) === 95 /* _ */ &&
46570                 name.charCodeAt(2) !== 95 /* _ */ &&
46571                 name.charCodeAt(2) !== 64 /* at */ &&
46572                 name.charCodeAt(2) !== 35 /* hash */;
46573         }
46574         function getNamedMembers(members) {
46575             var result;
46576             members.forEach(function (symbol, id) {
46577                 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
46578                     (result || (result = [])).push(symbol);
46579                 }
46580             });
46581             return result || ts.emptyArray;
46582         }
46583         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
46584             type.members = members;
46585             type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
46586             type.callSignatures = callSignatures;
46587             type.constructSignatures = constructSignatures;
46588             type.stringIndexInfo = stringIndexInfo;
46589             type.numberIndexInfo = numberIndexInfo;
46590             return type;
46591         }
46592         function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
46593             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
46594         }
46595         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
46596             var result;
46597             var _loop_8 = function (location) {
46598                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
46599                 if (location.locals && !isGlobalSourceFile(location)) {
46600                     if (result = callback(location.locals)) {
46601                         return { value: result };
46602                     }
46603                 }
46604                 switch (location.kind) {
46605                     case 297 /* SourceFile */:
46606                         if (!ts.isExternalOrCommonJsModule(location)) {
46607                             break;
46608                         }
46609                     // falls through
46610                     case 256 /* ModuleDeclaration */:
46611                         var sym = getSymbolOfNode(location);
46612                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
46613                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
46614                         // to one another anyway)
46615                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
46616                             return { value: result };
46617                         }
46618                         break;
46619                     case 252 /* ClassDeclaration */:
46620                     case 221 /* ClassExpression */:
46621                     case 253 /* InterfaceDeclaration */:
46622                         // Type parameters are bound into `members` lists so they can merge across declarations
46623                         // This is troublesome, since in all other respects, they behave like locals :cries:
46624                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
46625                         // lookup logic in terms of `resolveName` would be nice
46626                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
46627                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
46628                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
46629                         var table_1;
46630                         // TODO: Should this filtered table be cached in some way?
46631                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
46632                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
46633                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
46634                             }
46635                         });
46636                         if (table_1 && (result = callback(table_1))) {
46637                             return { value: result };
46638                         }
46639                         break;
46640                 }
46641             };
46642             for (var location = enclosingDeclaration; location; location = location.parent) {
46643                 var state_2 = _loop_8(location);
46644                 if (typeof state_2 === "object")
46645                     return state_2.value;
46646             }
46647             return callback(globals);
46648         }
46649         function getQualifiedLeftMeaning(rightMeaning) {
46650             // If we are looking in value space, the parent meaning is value, other wise it is namespace
46651             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
46652         }
46653         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
46654             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = new ts.Map(); }
46655             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
46656                 return undefined;
46657             }
46658             var id = getSymbolId(symbol);
46659             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
46660             if (!visitedSymbolTables) {
46661                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
46662             }
46663             return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
46664             /**
46665              * @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)
46666              */
46667             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
46668                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
46669                     return undefined;
46670                 }
46671                 var result = trySymbolTable(symbols, ignoreQualification);
46672                 visitedSymbolTables.pop();
46673                 return result;
46674             }
46675             function canQualifySymbol(symbolFromSymbolTable, meaning) {
46676                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
46677                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
46678                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
46679                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
46680             }
46681             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
46682                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
46683                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
46684                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
46685                     // check the symbol can be qualified, it is only then this symbol is accessible
46686                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
46687                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
46688             }
46689             function trySymbolTable(symbols, ignoreQualification) {
46690                 // If symbol is directly available by its name in the symbol table
46691                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
46692                     return [symbol];
46693                 }
46694                 // Check if symbol is any of the aliases in scope
46695                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
46696                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
46697                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
46698                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
46699                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
46700                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
46701                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
46702                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
46703                         // See similar comment in `resolveName` for details
46704                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */))) {
46705                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
46706                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
46707                         if (candidate) {
46708                             return candidate;
46709                         }
46710                     }
46711                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
46712                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
46713                             return [symbol];
46714                         }
46715                     }
46716                 });
46717                 // If there's no result and we're looking at the global symbol table, treat `globalThis` like an alias and try to lookup thru that
46718                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
46719             }
46720             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
46721                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
46722                     return [symbolFromSymbolTable];
46723                 }
46724                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
46725                 // but only if the symbolFromSymbolTable can be qualified
46726                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
46727                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
46728                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
46729                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
46730                 }
46731             }
46732         }
46733         function needsQualification(symbol, enclosingDeclaration, meaning) {
46734             var qualify = false;
46735             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
46736                 // If symbol of this name is not available in the symbol table we are ok
46737                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
46738                 if (!symbolFromSymbolTable) {
46739                     // Continue to the next symbol table
46740                     return false;
46741                 }
46742                 // If the symbol with this name is present it should refer to the symbol
46743                 if (symbolFromSymbolTable === symbol) {
46744                     // No need to qualify
46745                     return true;
46746                 }
46747                 // Qualify if the symbol from symbol table has same meaning as expected
46748                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
46749                 if (symbolFromSymbolTable.flags & meaning) {
46750                     qualify = true;
46751                     return true;
46752                 }
46753                 // Continue to the next symbol table
46754                 return false;
46755             });
46756             return qualify;
46757         }
46758         function isPropertyOrMethodDeclarationSymbol(symbol) {
46759             if (symbol.declarations && symbol.declarations.length) {
46760                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
46761                     var declaration = _a[_i];
46762                     switch (declaration.kind) {
46763                         case 163 /* PropertyDeclaration */:
46764                         case 165 /* MethodDeclaration */:
46765                         case 167 /* GetAccessor */:
46766                         case 168 /* SetAccessor */:
46767                             continue;
46768                         default:
46769                             return false;
46770                     }
46771                 }
46772                 return true;
46773             }
46774             return false;
46775         }
46776         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
46777             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
46778             return access.accessibility === 0 /* Accessible */;
46779         }
46780         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
46781             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
46782             return access.accessibility === 0 /* Accessible */;
46783         }
46784         function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) {
46785             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, flags, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ false);
46786             return access.accessibility === 0 /* Accessible */;
46787         }
46788         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
46789             if (!ts.length(symbols))
46790                 return;
46791             var hadAccessibleChain;
46792             var earlyModuleBail = false;
46793             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
46794                 var symbol = _a[_i];
46795                 // Symbol is accessible if it by itself is accessible
46796                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
46797                 if (accessibleSymbolChain) {
46798                     hadAccessibleChain = symbol;
46799                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
46800                     if (hasAccessibleDeclarations) {
46801                         return hasAccessibleDeclarations;
46802                     }
46803                 }
46804                 else if (allowModules) {
46805                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
46806                         if (shouldComputeAliasesToMakeVisible) {
46807                             earlyModuleBail = true;
46808                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
46809                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
46810                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
46811                             // all other visibility options (in order to capture the possible aliases used to reference the module)
46812                             continue;
46813                         }
46814                         // Any meaning of a module symbol is always accessible via an `import` type
46815                         return {
46816                             accessibility: 0 /* Accessible */
46817                         };
46818                     }
46819                 }
46820                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
46821                 // It could be a qualified symbol and hence verify the path
46822                 // e.g.:
46823                 // module m {
46824                 //     export class c {
46825                 //     }
46826                 // }
46827                 // const x: typeof m.c
46828                 // In the above example when we start with checking if typeof m.c symbol is accessible,
46829                 // we are going to see if c can be accessed in scope directly.
46830                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
46831                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
46832                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning);
46833                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules);
46834                 if (parentResult) {
46835                     return parentResult;
46836                 }
46837             }
46838             if (earlyModuleBail) {
46839                 return {
46840                     accessibility: 0 /* Accessible */
46841                 };
46842             }
46843             if (hadAccessibleChain) {
46844                 return {
46845                     accessibility: 1 /* NotAccessible */,
46846                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
46847                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
46848                 };
46849             }
46850         }
46851         /**
46852          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
46853          *
46854          * @param symbol a Symbol to check if accessible
46855          * @param enclosingDeclaration a Node containing reference to the symbol
46856          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
46857          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
46858          */
46859         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
46860             return isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, /*allowModules*/ true);
46861         }
46862         function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
46863             if (symbol && enclosingDeclaration) {
46864                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible, allowModules);
46865                 if (result) {
46866                     return result;
46867                 }
46868                 // This could be a symbol that is not exported in the external module
46869                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
46870                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
46871                 if (symbolExternalModule) {
46872                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
46873                     if (symbolExternalModule !== enclosingExternalModule) {
46874                         // name from different external module that is not visible
46875                         return {
46876                             accessibility: 2 /* CannotBeNamed */,
46877                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
46878                             errorModuleName: symbolToString(symbolExternalModule)
46879                         };
46880                     }
46881                 }
46882                 // Just a local name that is not accessible
46883                 return {
46884                     accessibility: 1 /* NotAccessible */,
46885                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
46886                 };
46887             }
46888             return { accessibility: 0 /* Accessible */ };
46889         }
46890         function getExternalModuleContainer(declaration) {
46891             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
46892             return node && getSymbolOfNode(node);
46893         }
46894         function hasExternalModuleSymbol(declaration) {
46895             return ts.isAmbientModule(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
46896         }
46897         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
46898             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
46899         }
46900         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
46901             var aliasesToMakeVisible;
46902             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 78 /* Identifier */; }), getIsDeclarationVisible)) {
46903                 return undefined;
46904             }
46905             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
46906             function getIsDeclarationVisible(declaration) {
46907                 var _a, _b;
46908                 if (!isDeclarationVisible(declaration)) {
46909                     // Mark the unexported alias as visible if its parent is visible
46910                     // because these kind of aliases can be used to name types in declaration file
46911                     var anyImportSyntax = getAnyImportSyntax(declaration);
46912                     if (anyImportSyntax &&
46913                         !ts.hasSyntacticModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
46914                         isDeclarationVisible(anyImportSyntax.parent)) {
46915                         return addVisibleAlias(declaration, anyImportSyntax);
46916                     }
46917                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
46918                         !ts.hasSyntacticModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
46919                         isDeclarationVisible(declaration.parent.parent.parent)) {
46920                         return addVisibleAlias(declaration, declaration.parent.parent);
46921                     }
46922                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
46923                         && !ts.hasSyntacticModifier(declaration, 1 /* Export */)
46924                         && isDeclarationVisible(declaration.parent)) {
46925                         return addVisibleAlias(declaration, declaration);
46926                     }
46927                     else if (symbol.flags & 2097152 /* Alias */ && ts.isBindingElement(declaration) && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement
46928                         && ts.isVariableDeclaration(declaration.parent.parent)
46929                         && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent)
46930                         && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* Export */)
46931                         && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file)
46932                         && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) {
46933                         return addVisibleAlias(declaration, declaration.parent.parent.parent.parent);
46934                     }
46935                     // Declaration is not visible
46936                     return false;
46937                 }
46938                 return true;
46939             }
46940             function addVisibleAlias(declaration, aliasingStatement) {
46941                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
46942                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
46943                 // since we will do the emitting later in trackSymbol.
46944                 if (shouldComputeAliasToMakeVisible) {
46945                     getNodeLinks(declaration).isVisible = true;
46946                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
46947                 }
46948                 return true;
46949             }
46950         }
46951         function isEntityNameVisible(entityName, enclosingDeclaration) {
46952             // get symbol of the first identifier of the entityName
46953             var meaning;
46954             if (entityName.parent.kind === 176 /* TypeQuery */ ||
46955                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
46956                 entityName.parent.kind === 158 /* ComputedPropertyName */) {
46957                 // Typeof value
46958                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
46959             }
46960             else if (entityName.kind === 157 /* QualifiedName */ || entityName.kind === 201 /* PropertyAccessExpression */ ||
46961                 entityName.parent.kind === 260 /* ImportEqualsDeclaration */) {
46962                 // Left identifier from type reference or TypeAlias
46963                 // Entity name of the import declaration
46964                 meaning = 1920 /* Namespace */;
46965             }
46966             else {
46967                 // Type Reference or TypeAlias entity = Identifier
46968                 meaning = 788968 /* Type */;
46969             }
46970             var firstIdentifier = ts.getFirstIdentifier(entityName);
46971             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
46972             if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */) {
46973                 return { accessibility: 0 /* Accessible */ };
46974             }
46975             // Verify if the symbol is accessible
46976             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
46977                 accessibility: 1 /* NotAccessible */,
46978                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
46979                 errorNode: firstIdentifier
46980             };
46981         }
46982         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
46983             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
46984             var nodeFlags = 70221824 /* IgnoreErrors */;
46985             if (flags & 2 /* UseOnlyExternalAliasing */) {
46986                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
46987             }
46988             if (flags & 1 /* WriteTypeParametersOrArguments */) {
46989                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
46990             }
46991             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
46992                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
46993             }
46994             if (flags & 16 /* DoNotIncludeSymbolChain */) {
46995                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
46996             }
46997             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
46998             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
46999             function symbolToStringWorker(writer) {
47000                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
47001                 // add neverAsciiEscape for GH#39027
47002                 var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 297 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true });
47003                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
47004                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
47005                 return writer;
47006             }
47007         }
47008         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
47009             if (flags === void 0) { flags = 0 /* None */; }
47010             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
47011             function signatureToStringWorker(writer) {
47012                 var sigOutput;
47013                 if (flags & 262144 /* WriteArrowStyleSignature */) {
47014                     sigOutput = kind === 1 /* Construct */ ? 175 /* ConstructorType */ : 174 /* FunctionType */;
47015                 }
47016                 else {
47017                     sigOutput = kind === 1 /* Construct */ ? 170 /* ConstructSignature */ : 169 /* CallSignature */;
47018                 }
47019                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
47020                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
47021                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
47022                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
47023                 return writer;
47024             }
47025         }
47026         function typeToString(type, enclosingDeclaration, flags, writer) {
47027             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
47028             if (writer === void 0) { writer = ts.createTextWriter(""); }
47029             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
47030             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
47031             if (typeNode === undefined)
47032                 return ts.Debug.fail("should always get typenode");
47033             var options = { removeComments: true };
47034             var printer = ts.createPrinter(options);
47035             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
47036             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
47037             var result = writer.getText();
47038             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
47039             if (maxLength && result && result.length >= maxLength) {
47040                 return result.substr(0, maxLength - "...".length) + "...";
47041             }
47042             return result;
47043         }
47044         function getTypeNamesForErrorDisplay(left, right) {
47045             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
47046             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
47047             if (leftStr === rightStr) {
47048                 leftStr = getTypeNameForErrorDisplay(left);
47049                 rightStr = getTypeNameForErrorDisplay(right);
47050             }
47051             return [leftStr, rightStr];
47052         }
47053         function getTypeNameForErrorDisplay(type) {
47054             return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
47055         }
47056         function symbolValueDeclarationIsContextSensitive(symbol) {
47057             return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
47058         }
47059         function toNodeBuilderFlags(flags) {
47060             if (flags === void 0) { flags = 0 /* None */; }
47061             return flags & 814775659 /* NodeBuilderFlagsMask */;
47062         }
47063         function isClassInstanceSide(type) {
47064             return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */));
47065         }
47066         function createNodeBuilder() {
47067             return {
47068                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
47069                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
47070                 },
47071                 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
47072                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context, /*typeNode*/ undefined); });
47073                 },
47074                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
47075                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
47076                 },
47077                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
47078                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
47079                 },
47080                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
47081                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
47082                 },
47083                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
47084                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
47085                 },
47086                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
47087                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
47088                 },
47089                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
47090                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
47091                 },
47092                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
47093                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
47094                 },
47095             };
47096             function withContext(enclosingDeclaration, flags, tracker, cb) {
47097                 var _a, _b;
47098                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
47099                 var context = {
47100                     enclosingDeclaration: enclosingDeclaration,
47101                     flags: flags || 0 /* None */,
47102                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
47103                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
47104                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
47105                             getSourceFiles: function () { return host.getSourceFiles(); },
47106                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
47107                             getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache),
47108                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
47109                             redirectTargetsMap: host.redirectTargetsMap,
47110                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
47111                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
47112                             fileExists: function (fileName) { return host.fileExists(fileName); },
47113                         } : undefined },
47114                     encounteredError: false,
47115                     visitedTypes: undefined,
47116                     symbolDepth: undefined,
47117                     inferTypeParameters: undefined,
47118                     approximateLength: 0
47119                 };
47120                 var resultingNode = cb(context);
47121                 if (context.truncating && context.flags & 1 /* NoTruncation */) {
47122                     (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportTruncationError) === null || _b === void 0 ? void 0 : _b.call(_a);
47123                 }
47124                 return context.encounteredError ? undefined : resultingNode;
47125             }
47126             function checkTruncationLength(context) {
47127                 if (context.truncating)
47128                     return context.truncating;
47129                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
47130             }
47131             function typeToTypeNodeHelper(type, context) {
47132                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
47133                     cancellationToken.throwIfCancellationRequested();
47134                 }
47135                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
47136                 context.flags &= ~8388608 /* InTypeAlias */;
47137                 if (!type) {
47138                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
47139                         context.encounteredError = true;
47140                         return undefined; // TODO: GH#18217
47141                     }
47142                     context.approximateLength += 3;
47143                     return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47144                 }
47145                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
47146                     type = getReducedType(type);
47147                 }
47148                 if (type.flags & 1 /* Any */) {
47149                     context.approximateLength += 3;
47150                     return ts.factory.createKeywordTypeNode(type === intrinsicMarkerType ? 136 /* IntrinsicKeyword */ : 128 /* AnyKeyword */);
47151                 }
47152                 if (type.flags & 2 /* Unknown */) {
47153                     return ts.factory.createKeywordTypeNode(152 /* UnknownKeyword */);
47154                 }
47155                 if (type.flags & 4 /* String */) {
47156                     context.approximateLength += 6;
47157                     return ts.factory.createKeywordTypeNode(147 /* StringKeyword */);
47158                 }
47159                 if (type.flags & 8 /* Number */) {
47160                     context.approximateLength += 6;
47161                     return ts.factory.createKeywordTypeNode(144 /* NumberKeyword */);
47162                 }
47163                 if (type.flags & 64 /* BigInt */) {
47164                     context.approximateLength += 6;
47165                     return ts.factory.createKeywordTypeNode(155 /* BigIntKeyword */);
47166                 }
47167                 if (type.flags & 16 /* Boolean */) {
47168                     context.approximateLength += 7;
47169                     return ts.factory.createKeywordTypeNode(131 /* BooleanKeyword */);
47170                 }
47171                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
47172                     var parentSymbol = getParentOfSymbol(type.symbol);
47173                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
47174                     if (getDeclaredTypeOfSymbol(parentSymbol) === type) {
47175                         return parentName;
47176                     }
47177                     var memberName = ts.symbolName(type.symbol);
47178                     if (ts.isIdentifierText(memberName, 0 /* ES3 */)) {
47179                         return appendReferenceToType(parentName, ts.factory.createTypeReferenceNode(memberName, /*typeArguments*/ undefined));
47180                     }
47181                     if (ts.isImportTypeNode(parentName)) {
47182                         parentName.isTypeOf = true; // mutably update, node is freshly manufactured anyhow
47183                         return ts.factory.createIndexedAccessTypeNode(parentName, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(memberName)));
47184                     }
47185                     else if (ts.isTypeReferenceNode(parentName)) {
47186                         return ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeQueryNode(parentName.typeName), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(memberName)));
47187                     }
47188                     else {
47189                         return ts.Debug.fail("Unhandled type node kind returned from `symbolToTypeNode`.");
47190                     }
47191                 }
47192                 if (type.flags & 1056 /* EnumLike */) {
47193                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
47194                 }
47195                 if (type.flags & 128 /* StringLiteral */) {
47196                     context.approximateLength += (type.value.length + 2);
47197                     return ts.factory.createLiteralTypeNode(ts.setEmitFlags(ts.factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
47198                 }
47199                 if (type.flags & 256 /* NumberLiteral */) {
47200                     var value = type.value;
47201                     context.approximateLength += ("" + value).length;
47202                     return ts.factory.createLiteralTypeNode(value < 0 ? ts.factory.createPrefixUnaryExpression(40 /* MinusToken */, ts.factory.createNumericLiteral(-value)) : ts.factory.createNumericLiteral(value));
47203                 }
47204                 if (type.flags & 2048 /* BigIntLiteral */) {
47205                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
47206                     return ts.factory.createLiteralTypeNode((ts.factory.createBigIntLiteral(type.value)));
47207                 }
47208                 if (type.flags & 512 /* BooleanLiteral */) {
47209                     context.approximateLength += type.intrinsicName.length;
47210                     return ts.factory.createLiteralTypeNode(type.intrinsicName === "true" ? ts.factory.createTrue() : ts.factory.createFalse());
47211                 }
47212                 if (type.flags & 8192 /* UniqueESSymbol */) {
47213                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
47214                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
47215                             context.approximateLength += 6;
47216                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
47217                         }
47218                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
47219                             context.tracker.reportInaccessibleUniqueSymbolError();
47220                         }
47221                     }
47222                     context.approximateLength += 13;
47223                     return ts.factory.createTypeOperatorNode(151 /* UniqueKeyword */, ts.factory.createKeywordTypeNode(148 /* SymbolKeyword */));
47224                 }
47225                 if (type.flags & 16384 /* Void */) {
47226                     context.approximateLength += 4;
47227                     return ts.factory.createKeywordTypeNode(113 /* VoidKeyword */);
47228                 }
47229                 if (type.flags & 32768 /* Undefined */) {
47230                     context.approximateLength += 9;
47231                     return ts.factory.createKeywordTypeNode(150 /* UndefinedKeyword */);
47232                 }
47233                 if (type.flags & 65536 /* Null */) {
47234                     context.approximateLength += 4;
47235                     return ts.factory.createLiteralTypeNode(ts.factory.createNull());
47236                 }
47237                 if (type.flags & 131072 /* Never */) {
47238                     context.approximateLength += 5;
47239                     return ts.factory.createKeywordTypeNode(141 /* NeverKeyword */);
47240                 }
47241                 if (type.flags & 4096 /* ESSymbol */) {
47242                     context.approximateLength += 6;
47243                     return ts.factory.createKeywordTypeNode(148 /* SymbolKeyword */);
47244                 }
47245                 if (type.flags & 67108864 /* NonPrimitive */) {
47246                     context.approximateLength += 6;
47247                     return ts.factory.createKeywordTypeNode(145 /* ObjectKeyword */);
47248                 }
47249                 if (isThisTypeParameter(type)) {
47250                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
47251                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
47252                             context.encounteredError = true;
47253                         }
47254                         if (context.tracker.reportInaccessibleThisError) {
47255                             context.tracker.reportInaccessibleThisError();
47256                         }
47257                     }
47258                     context.approximateLength += 4;
47259                     return ts.factory.createThisTypeNode();
47260                 }
47261                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
47262                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
47263                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
47264                         return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes);
47265                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
47266                 }
47267                 var objectFlags = ts.getObjectFlags(type);
47268                 if (objectFlags & 4 /* Reference */) {
47269                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
47270                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
47271                 }
47272                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
47273                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
47274                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
47275                         return ts.factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
47276                     }
47277                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
47278                         type.flags & 262144 /* TypeParameter */ &&
47279                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
47280                         var name = typeParameterToName(type, context);
47281                         context.approximateLength += ts.idText(name).length;
47282                         return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
47283                     }
47284                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
47285                     return type.symbol
47286                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
47287                         : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("?"), /*typeArguments*/ undefined);
47288                 }
47289                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
47290                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
47291                     if (ts.length(types) === 1) {
47292                         return typeToTypeNodeHelper(types[0], context);
47293                     }
47294                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
47295                     if (typeNodes && typeNodes.length > 0) {
47296                         var unionOrIntersectionTypeNode = type.flags & 1048576 /* Union */ ? ts.factory.createUnionTypeNode(typeNodes) : ts.factory.createIntersectionTypeNode(typeNodes);
47297                         return unionOrIntersectionTypeNode;
47298                     }
47299                     else {
47300                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
47301                             context.encounteredError = true;
47302                         }
47303                         return undefined; // TODO: GH#18217
47304                     }
47305                 }
47306                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
47307                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
47308                     // The type is an object literal type.
47309                     return createAnonymousTypeNode(type);
47310                 }
47311                 if (type.flags & 4194304 /* Index */) {
47312                     var indexedType = type.type;
47313                     context.approximateLength += 6;
47314                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
47315                     return ts.factory.createTypeOperatorNode(138 /* KeyOfKeyword */, indexTypeNode);
47316                 }
47317                 if (type.flags & 134217728 /* TemplateLiteral */) {
47318                     var texts_1 = type.texts;
47319                     var types_1 = type.types;
47320                     var templateHead = ts.factory.createTemplateHead(texts_1[0]);
47321                     var templateSpans = ts.factory.createNodeArray(ts.map(types_1, function (t, i) { return ts.factory.createTemplateLiteralTypeSpan(typeToTypeNodeHelper(t, context), (i < types_1.length - 1 ? ts.factory.createTemplateMiddle : ts.factory.createTemplateTail)(texts_1[i + 1])); }));
47322                     context.approximateLength += 2;
47323                     return ts.factory.createTemplateLiteralType(templateHead, templateSpans);
47324                 }
47325                 if (type.flags & 268435456 /* StringMapping */) {
47326                     var typeNode = typeToTypeNodeHelper(type.type, context);
47327                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */, [typeNode]);
47328                 }
47329                 if (type.flags & 8388608 /* IndexedAccess */) {
47330                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
47331                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
47332                     context.approximateLength += 2;
47333                     return ts.factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
47334                 }
47335                 if (type.flags & 16777216 /* Conditional */) {
47336                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
47337                     var saveInferTypeParameters = context.inferTypeParameters;
47338                     context.inferTypeParameters = type.root.inferTypeParameters;
47339                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
47340                     context.inferTypeParameters = saveInferTypeParameters;
47341                     var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
47342                     var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
47343                     context.approximateLength += 15;
47344                     return ts.factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
47345                 }
47346                 if (type.flags & 33554432 /* Substitution */) {
47347                     return typeToTypeNodeHelper(type.baseType, context);
47348                 }
47349                 return ts.Debug.fail("Should be unreachable.");
47350                 function typeToTypeNodeOrCircularityElision(type) {
47351                     var _a, _b, _c;
47352                     if (type.flags & 1048576 /* Union */) {
47353                         if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(getTypeId(type))) {
47354                             if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
47355                                 context.encounteredError = true;
47356                                 (_c = (_b = context.tracker) === null || _b === void 0 ? void 0 : _b.reportCyclicStructureError) === null || _c === void 0 ? void 0 : _c.call(_b);
47357                             }
47358                             return createElidedInformationPlaceholder(context);
47359                         }
47360                         return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
47361                     }
47362                     return typeToTypeNodeHelper(type, context);
47363                 }
47364                 function createMappedTypeNodeFromType(type) {
47365                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
47366                     var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined;
47367                     var questionToken = type.declaration.questionToken ? ts.factory.createToken(type.declaration.questionToken.kind) : undefined;
47368                     var appropriateConstraintTypeNode;
47369                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
47370                         // We have a { [P in keyof T]: X }
47371                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
47372                         appropriateConstraintTypeNode = ts.factory.createTypeOperatorNode(138 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
47373                     }
47374                     else {
47375                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
47376                     }
47377                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
47378                     var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined;
47379                     var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
47380                     var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode);
47381                     context.approximateLength += 10;
47382                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
47383                 }
47384                 function createAnonymousTypeNode(type) {
47385                     var _a;
47386                     var typeId = type.id;
47387                     var symbol = type.symbol;
47388                     if (symbol) {
47389                         var isInstanceType = isClassInstanceSide(type) ? 788968 /* Type */ : 111551 /* Value */;
47390                         if (isJSConstructor(symbol.valueDeclaration)) {
47391                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
47392                             return symbolToTypeNode(symbol, context, isInstanceType);
47393                         }
47394                         // Always use 'typeof T' for type of class, enum, and module objects
47395                         else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 221 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
47396                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
47397                             shouldWriteTypeOfFunctionSymbol()) {
47398                             return symbolToTypeNode(symbol, context, isInstanceType);
47399                         }
47400                         else if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(typeId)) {
47401                             // If type is an anonymous type literal in a type alias declaration, use type alias name
47402                             var typeAlias = getTypeAliasForTypeLiteral(type);
47403                             if (typeAlias) {
47404                                 // The specified symbol flags need to be reinterpreted as type flags
47405                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
47406                             }
47407                             else {
47408                                 return createElidedInformationPlaceholder(context);
47409                             }
47410                         }
47411                         else {
47412                             return visitAndTransformType(type, createTypeNodeFromObjectType);
47413                         }
47414                     }
47415                     else {
47416                         // Anonymous types without a symbol are never circular.
47417                         return createTypeNodeFromObjectType(type);
47418                     }
47419                     function shouldWriteTypeOfFunctionSymbol() {
47420                         var _a;
47421                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
47422                             ts.some(symbol.declarations, function (declaration) { return ts.hasSyntacticModifier(declaration, 32 /* Static */); });
47423                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
47424                             (symbol.parent || // is exported function symbol
47425                                 ts.forEach(symbol.declarations, function (declaration) {
47426                                     return declaration.parent.kind === 297 /* SourceFile */ || declaration.parent.kind === 257 /* ModuleBlock */;
47427                                 }));
47428                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
47429                             // typeof is allowed only for static/non local functions
47430                             return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(typeId))) && // it is type of the symbol uses itself recursively
47431                                 (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed
47432                         }
47433                     }
47434                 }
47435                 function visitAndTransformType(type, transform) {
47436                     var typeId = type.id;
47437                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
47438                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
47439                         type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
47440                             undefined;
47441                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
47442                     // of types allows us to catch circular references to instantiations of the same anonymous type
47443                     if (!context.visitedTypes) {
47444                         context.visitedTypes = new ts.Set();
47445                     }
47446                     if (id && !context.symbolDepth) {
47447                         context.symbolDepth = new ts.Map();
47448                     }
47449                     var depth;
47450                     if (id) {
47451                         depth = context.symbolDepth.get(id) || 0;
47452                         if (depth > 10) {
47453                             return createElidedInformationPlaceholder(context);
47454                         }
47455                         context.symbolDepth.set(id, depth + 1);
47456                     }
47457                     context.visitedTypes.add(typeId);
47458                     var result = transform(type);
47459                     context.visitedTypes.delete(typeId);
47460                     if (id) {
47461                         context.symbolDepth.set(id, depth);
47462                     }
47463                     return result;
47464                 }
47465                 function createTypeNodeFromObjectType(type) {
47466                     if (isGenericMappedType(type) || type.containsError) {
47467                         return createMappedTypeNodeFromType(type);
47468                     }
47469                     var resolved = resolveStructuredTypeMembers(type);
47470                     if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
47471                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
47472                             context.approximateLength += 2;
47473                             return ts.setEmitFlags(ts.factory.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
47474                         }
47475                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
47476                             var signature = resolved.callSignatures[0];
47477                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 174 /* FunctionType */, context);
47478                             return signatureNode;
47479                         }
47480                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
47481                             var signature = resolved.constructSignatures[0];
47482                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* ConstructorType */, context);
47483                             return signatureNode;
47484                         }
47485                     }
47486                     var savedFlags = context.flags;
47487                     context.flags |= 4194304 /* InObjectTypeLiteral */;
47488                     var members = createTypeNodesFromResolvedType(resolved);
47489                     context.flags = savedFlags;
47490                     var typeLiteralNode = ts.factory.createTypeLiteralNode(members);
47491                     context.approximateLength += 2;
47492                     return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
47493                 }
47494                 function typeReferenceToTypeNode(type) {
47495                     var typeArguments = getTypeArguments(type);
47496                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
47497                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
47498                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
47499                             return ts.factory.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
47500                         }
47501                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
47502                         var arrayType = ts.factory.createArrayTypeNode(elementType);
47503                         return type.target === globalArrayType ? arrayType : ts.factory.createTypeOperatorNode(142 /* ReadonlyKeyword */, arrayType);
47504                     }
47505                     else if (type.target.objectFlags & 8 /* Tuple */) {
47506                         if (typeArguments.length > 0) {
47507                             var arity = getTypeReferenceArity(type);
47508                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
47509                             if (tupleConstituentNodes) {
47510                                 if (type.target.labeledElementDeclarations) {
47511                                     for (var i = 0; i < tupleConstituentNodes.length; i++) {
47512                                         var flags = type.target.elementFlags[i];
47513                                         tupleConstituentNodes[i] = ts.factory.createNamedTupleMember(flags & 12 /* Variable */ ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined, ts.factory.createIdentifier(ts.unescapeLeadingUnderscores(getTupleElementLabel(type.target.labeledElementDeclarations[i]))), flags & 2 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, flags & 4 /* Rest */ ? ts.factory.createArrayTypeNode(tupleConstituentNodes[i]) :
47514                                             tupleConstituentNodes[i]);
47515                                     }
47516                                 }
47517                                 else {
47518                                     for (var i = 0; i < Math.min(arity, tupleConstituentNodes.length); i++) {
47519                                         var flags = type.target.elementFlags[i];
47520                                         tupleConstituentNodes[i] =
47521                                             flags & 12 /* Variable */ ? ts.factory.createRestTypeNode(flags & 4 /* Rest */ ? ts.factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) :
47522                                                 flags & 2 /* Optional */ ? ts.factory.createOptionalTypeNode(tupleConstituentNodes[i]) :
47523                                                     tupleConstituentNodes[i];
47524                                     }
47525                                 }
47526                                 var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode(tupleConstituentNodes), 1 /* SingleLine */);
47527                                 return type.target.readonly ? ts.factory.createTypeOperatorNode(142 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
47528                             }
47529                         }
47530                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
47531                             var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode([]), 1 /* SingleLine */);
47532                             return type.target.readonly ? ts.factory.createTypeOperatorNode(142 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
47533                         }
47534                         context.encounteredError = true;
47535                         return undefined; // TODO: GH#18217
47536                     }
47537                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
47538                         type.symbol.valueDeclaration &&
47539                         ts.isClassLike(type.symbol.valueDeclaration) &&
47540                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
47541                         return createAnonymousTypeNode(type);
47542                     }
47543                     else {
47544                         var outerTypeParameters = type.target.outerTypeParameters;
47545                         var i = 0;
47546                         var resultType = void 0;
47547                         if (outerTypeParameters) {
47548                             var length_2 = outerTypeParameters.length;
47549                             while (i < length_2) {
47550                                 // Find group of type arguments for type parameters with the same declaring container.
47551                                 var start = i;
47552                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
47553                                 do {
47554                                     i++;
47555                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
47556                                 // When type parameters are their own type arguments for the whole group (i.e. we have
47557                                 // the default outer type arguments), we don't show the group.
47558                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
47559                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
47560                                     var flags_3 = context.flags;
47561                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
47562                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
47563                                     context.flags = flags_3;
47564                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
47565                                 }
47566                             }
47567                         }
47568                         var typeArgumentNodes = void 0;
47569                         if (typeArguments.length > 0) {
47570                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
47571                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
47572                         }
47573                         var flags = context.flags;
47574                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
47575                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
47576                         context.flags = flags;
47577                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
47578                     }
47579                 }
47580                 function appendReferenceToType(root, ref) {
47581                     if (ts.isImportTypeNode(root)) {
47582                         // first shift type arguments
47583                         var typeArguments = root.typeArguments;
47584                         var qualifier = root.qualifier;
47585                         if (qualifier) {
47586                             if (ts.isIdentifier(qualifier)) {
47587                                 qualifier = ts.factory.updateIdentifier(qualifier, typeArguments);
47588                             }
47589                             else {
47590                                 qualifier = ts.factory.updateQualifiedName(qualifier, qualifier.left, ts.factory.updateIdentifier(qualifier.right, typeArguments));
47591                             }
47592                         }
47593                         typeArguments = ref.typeArguments;
47594                         // then move qualifiers
47595                         var ids = getAccessStack(ref);
47596                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
47597                             var id = ids_1[_i];
47598                             qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id;
47599                         }
47600                         return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf);
47601                     }
47602                     else {
47603                         // first shift type arguments
47604                         var typeArguments = root.typeArguments;
47605                         var typeName = root.typeName;
47606                         if (ts.isIdentifier(typeName)) {
47607                             typeName = ts.factory.updateIdentifier(typeName, typeArguments);
47608                         }
47609                         else {
47610                             typeName = ts.factory.updateQualifiedName(typeName, typeName.left, ts.factory.updateIdentifier(typeName.right, typeArguments));
47611                         }
47612                         typeArguments = ref.typeArguments;
47613                         // then move qualifiers
47614                         var ids = getAccessStack(ref);
47615                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
47616                             var id = ids_2[_a];
47617                             typeName = ts.factory.createQualifiedName(typeName, id);
47618                         }
47619                         return ts.factory.updateTypeReferenceNode(root, typeName, typeArguments);
47620                     }
47621                 }
47622                 function getAccessStack(ref) {
47623                     var state = ref.typeName;
47624                     var ids = [];
47625                     while (!ts.isIdentifier(state)) {
47626                         ids.unshift(state.right);
47627                         state = state.left;
47628                     }
47629                     ids.unshift(state);
47630                     return ids;
47631                 }
47632                 function createTypeNodesFromResolvedType(resolvedType) {
47633                     if (checkTruncationLength(context)) {
47634                         return [ts.factory.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined)];
47635                     }
47636                     var typeElements = [];
47637                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
47638                         var signature = _a[_i];
47639                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 169 /* CallSignature */, context));
47640                     }
47641                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
47642                         var signature = _c[_b];
47643                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* ConstructSignature */, context));
47644                     }
47645                     if (resolvedType.stringIndexInfo) {
47646                         var indexSignature = void 0;
47647                         if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
47648                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context));
47649                         }
47650                         else {
47651                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context, /*typeNode*/ undefined);
47652                         }
47653                         typeElements.push(indexSignature);
47654                     }
47655                     if (resolvedType.numberIndexInfo) {
47656                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context, /*typeNode*/ undefined));
47657                     }
47658                     var properties = resolvedType.properties;
47659                     if (!properties) {
47660                         return typeElements;
47661                     }
47662                     var i = 0;
47663                     for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
47664                         var propertySymbol = properties_1[_d];
47665                         i++;
47666                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
47667                             if (propertySymbol.flags & 4194304 /* Prototype */) {
47668                                 continue;
47669                             }
47670                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
47671                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
47672                             }
47673                         }
47674                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
47675                             typeElements.push(ts.factory.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined));
47676                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
47677                             break;
47678                         }
47679                         addPropertyToElementList(propertySymbol, context, typeElements);
47680                     }
47681                     return typeElements.length ? typeElements : undefined;
47682                 }
47683             }
47684             function createElidedInformationPlaceholder(context) {
47685                 context.approximateLength += 3;
47686                 if (!(context.flags & 1 /* NoTruncation */)) {
47687                     return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("..."), /*typeArguments*/ undefined);
47688                 }
47689                 return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47690             }
47691             function addPropertyToElementList(propertySymbol, context, typeElements) {
47692                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
47693                 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
47694                     anyType : getTypeOfSymbol(propertySymbol);
47695                 var saveEnclosingDeclaration = context.enclosingDeclaration;
47696                 context.enclosingDeclaration = undefined;
47697                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
47698                     var decl = ts.first(propertySymbol.declarations);
47699                     if (hasLateBindableName(decl)) {
47700                         if (ts.isBinaryExpression(decl)) {
47701                             var name = ts.getNameOfDeclaration(decl);
47702                             if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
47703                                 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
47704                             }
47705                         }
47706                         else {
47707                             trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
47708                         }
47709                     }
47710                 }
47711                 context.enclosingDeclaration = saveEnclosingDeclaration;
47712                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
47713                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
47714                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
47715                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
47716                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
47717                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
47718                         var signature = signatures_1[_i];
47719                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 164 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken });
47720                         typeElements.push(preserveCommentsOn(methodDeclaration));
47721                     }
47722                 }
47723                 else {
47724                     var savedFlags = context.flags;
47725                     context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
47726                     var propertyTypeNode = void 0;
47727                     if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
47728                         propertyTypeNode = createElidedInformationPlaceholder(context);
47729                     }
47730                     else {
47731                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47732                     }
47733                     context.flags = savedFlags;
47734                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined;
47735                     if (modifiers) {
47736                         context.approximateLength += 9;
47737                     }
47738                     var propertySignature = ts.factory.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode);
47739                     typeElements.push(preserveCommentsOn(propertySignature));
47740                 }
47741                 function preserveCommentsOn(node) {
47742                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; })) {
47743                         var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; });
47744                         var commentText = d.comment;
47745                         if (commentText) {
47746                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
47747                         }
47748                     }
47749                     else if (propertySymbol.valueDeclaration) {
47750                         // Copy comments to node for declaration emit
47751                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
47752                     }
47753                     return node;
47754                 }
47755             }
47756             function mapToTypeNodes(types, context, isBareList) {
47757                 if (ts.some(types)) {
47758                     if (checkTruncationLength(context)) {
47759                         if (!isBareList) {
47760                             return [ts.factory.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
47761                         }
47762                         else if (types.length > 2) {
47763                             return [
47764                                 typeToTypeNodeHelper(types[0], context),
47765                                 ts.factory.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
47766                                 typeToTypeNodeHelper(types[types.length - 1], context)
47767                             ];
47768                         }
47769                     }
47770                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
47771                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
47772                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
47773                     var result_4 = [];
47774                     var i = 0;
47775                     for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
47776                         var type = types_2[_i];
47777                         i++;
47778                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
47779                             result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
47780                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
47781                             if (typeNode_1) {
47782                                 result_4.push(typeNode_1);
47783                             }
47784                             break;
47785                         }
47786                         context.approximateLength += 2; // Account for whitespace + separator
47787                         var typeNode = typeToTypeNodeHelper(type, context);
47788                         if (typeNode) {
47789                             result_4.push(typeNode);
47790                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
47791                                 seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]);
47792                             }
47793                         }
47794                     }
47795                     if (seenNames) {
47796                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
47797                         // occurrences of the same name actually come from different
47798                         // namespaces, go through the single-identifier type reference nodes
47799                         // we just generated, and see if any names were generated more than
47800                         // once while referring to different types. If so, regenerate the
47801                         // type node for each entry by that name with the
47802                         // `UseFullyQualifiedType` flag enabled.
47803                         var saveContextFlags = context.flags;
47804                         context.flags |= 64 /* UseFullyQualifiedType */;
47805                         seenNames.forEach(function (types) {
47806                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
47807                                 var a = _a[0];
47808                                 var b = _b[0];
47809                                 return typesAreSameReference(a, b);
47810                             })) {
47811                                 for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
47812                                     var _a = types_3[_i], type = _a[0], resultIndex = _a[1];
47813                                     result_4[resultIndex] = typeToTypeNodeHelper(type, context);
47814                                 }
47815                             }
47816                         });
47817                         context.flags = saveContextFlags;
47818                     }
47819                     return result_4;
47820                 }
47821             }
47822             function typesAreSameReference(a, b) {
47823                 return a === b
47824                     || !!a.symbol && a.symbol === b.symbol
47825                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
47826             }
47827             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context, typeNode) {
47828                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
47829                 var indexerTypeNode = ts.factory.createKeywordTypeNode(kind === 0 /* String */ ? 147 /* StringKeyword */ : 144 /* NumberKeyword */);
47830                 var indexingParameter = ts.factory.createParameterDeclaration(
47831                 /*decorators*/ undefined, 
47832                 /*modifiers*/ undefined, 
47833                 /*dotDotDotToken*/ undefined, name, 
47834                 /*questionToken*/ undefined, indexerTypeNode, 
47835                 /*initializer*/ undefined);
47836                 if (!typeNode) {
47837                     typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
47838                 }
47839                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
47840                     context.encounteredError = true;
47841                 }
47842                 context.approximateLength += (name.length + 4);
47843                 return ts.factory.createIndexSignature(
47844                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
47845             }
47846             function signatureToSignatureDeclarationHelper(signature, kind, context, options) {
47847                 var _a, _b, _c, _d;
47848                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
47849                 if (suppressAny)
47850                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
47851                 var typeParameters;
47852                 var typeArguments;
47853                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
47854                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
47855                 }
47856                 else {
47857                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
47858                 }
47859                 var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0];
47860                 // If the expanded parameter list had a variadic in a non-trailing position, don't expand it
47861                 var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 166 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); });
47862                 if (signature.thisParameter) {
47863                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
47864                     parameters.unshift(thisParameter);
47865                 }
47866                 var returnTypeNode;
47867                 var typePredicate = getTypePredicateOfSignature(signature);
47868                 if (typePredicate) {
47869                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
47870                         ts.factory.createToken(127 /* AssertsKeyword */) :
47871                         undefined;
47872                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
47873                         ts.setEmitFlags(ts.factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
47874                         ts.factory.createThisTypeNode();
47875                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
47876                     returnTypeNode = ts.factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
47877                 }
47878                 else {
47879                     var returnType = getReturnTypeOfSignature(signature);
47880                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
47881                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports);
47882                     }
47883                     else if (!suppressAny) {
47884                         returnTypeNode = ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47885                     }
47886                 }
47887                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
47888                 var node = kind === 169 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) :
47889                     kind === 170 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) :
47890                         kind === 164 /* MethodSignature */ ? ts.factory.createMethodSignature(options === null || options === void 0 ? void 0 : options.modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) :
47891                             kind === 165 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) :
47892                                 kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, parameters, /*body*/ undefined) :
47893                                     kind === 167 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) :
47894                                         kind === 168 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) :
47895                                             kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, parameters, returnTypeNode) :
47896                                                 kind === 308 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) :
47897                                                     kind === 174 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
47898                                                         kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
47899                                                             kind === 251 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) :
47900                                                                 kind === 208 /* FunctionExpression */ ? ts.factory.createFunctionExpression(options === null || options === void 0 ? void 0 : options.modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) :
47901                                                                     kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(options === null || options === void 0 ? void 0 : options.modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) :
47902                                                                         ts.Debug.assertNever(kind);
47903                 if (typeArguments) {
47904                     node.typeArguments = ts.factory.createNodeArray(typeArguments);
47905                 }
47906                 return node;
47907             }
47908             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
47909                 var savedContextFlags = context.flags;
47910                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
47911                 var name = typeParameterToName(type, context);
47912                 var defaultParameter = getDefaultFromTypeParameter(type);
47913                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
47914                 context.flags = savedContextFlags;
47915                 return ts.factory.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
47916             }
47917             function typeParameterToDeclaration(type, context, constraint) {
47918                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
47919                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
47920                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
47921             }
47922             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
47923                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 160 /* Parameter */);
47924                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
47925                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 326 /* JSDocParameterTag */);
47926                 }
47927                 var parameterType = getTypeOfSymbol(parameterSymbol);
47928                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
47929                     parameterType = getOptionalType(parameterType);
47930                 }
47931                 if ((context.flags & 1073741824 /* NoUndefinedOptionalParameterType */) && parameterDeclaration && !ts.isJSDocParameterTag(parameterDeclaration) && isOptionalUninitializedParameter(parameterDeclaration)) {
47932                     parameterType = getTypeWithFacts(parameterType, 524288 /* NEUndefined */);
47933                 }
47934                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
47935                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined;
47936                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
47937                 var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined;
47938                 var name = parameterDeclaration ? parameterDeclaration.name ?
47939                     parameterDeclaration.name.kind === 78 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
47940                         parameterDeclaration.name.kind === 157 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
47941                             cloneBindingName(parameterDeclaration.name) :
47942                     ts.symbolName(parameterSymbol) :
47943                     ts.symbolName(parameterSymbol);
47944                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
47945                 var questionToken = isOptional ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
47946                 var parameterNode = ts.factory.createParameterDeclaration(
47947                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
47948                 /*initializer*/ undefined);
47949                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
47950                 return parameterNode;
47951                 function cloneBindingName(node) {
47952                     return elideInitializerAndSetEmitFlags(node);
47953                     function elideInitializerAndSetEmitFlags(node) {
47954                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
47955                             trackComputedName(node.expression, context.enclosingDeclaration, context);
47956                         }
47957                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
47958                         if (ts.isBindingElement(visited)) {
47959                             visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, 
47960                             /*initializer*/ undefined);
47961                         }
47962                         if (!ts.nodeIsSynthesized(visited)) {
47963                             visited = ts.factory.cloneNode(visited);
47964                         }
47965                         return ts.setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
47966                     }
47967                 }
47968             }
47969             function trackComputedName(accessExpression, enclosingDeclaration, context) {
47970                 if (!context.tracker.trackSymbol)
47971                     return;
47972                 // get symbol of the first identifier of the entityName
47973                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
47974                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
47975                 if (name) {
47976                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
47977                 }
47978             }
47979             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
47980                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
47981                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
47982             }
47983             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
47984                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
47985                 var chain;
47986                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
47987                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
47988                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
47989                     ts.Debug.assert(chain && chain.length > 0);
47990                 }
47991                 else {
47992                     chain = [symbol];
47993                 }
47994                 return chain;
47995                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
47996                 function getSymbolChain(symbol, meaning, endOfChain) {
47997                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
47998                     var parentSpecifiers;
47999                     if (!accessibleSymbolChain ||
48000                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
48001                         // Go up and add our parent.
48002                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration, meaning);
48003                         if (ts.length(parents_1)) {
48004                             parentSpecifiers = parents_1.map(function (symbol) {
48005                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
48006                                     ? getSpecifierForModuleSymbol(symbol, context)
48007                                     : undefined;
48008                             });
48009                             var indices = parents_1.map(function (_, i) { return i; });
48010                             indices.sort(sortByBestName);
48011                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
48012                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
48013                                 var parent = sortedParents_1[_i];
48014                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
48015                                 if (parentChain) {
48016                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
48017                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
48018                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
48019                                         // No need to lookup an alias for the symbol in itself
48020                                         accessibleSymbolChain = parentChain;
48021                                         break;
48022                                     }
48023                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
48024                                     break;
48025                                 }
48026                             }
48027                         }
48028                     }
48029                     if (accessibleSymbolChain) {
48030                         return accessibleSymbolChain;
48031                     }
48032                     if (
48033                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
48034                     endOfChain ||
48035                         // If a parent symbol is an anonymous type, don't write it.
48036                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
48037                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
48038                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
48039                             return;
48040                         }
48041                         return [symbol];
48042                     }
48043                     function sortByBestName(a, b) {
48044                         var specifierA = parentSpecifiers[a];
48045                         var specifierB = parentSpecifiers[b];
48046                         if (specifierA && specifierB) {
48047                             var isBRelative = ts.pathIsRelative(specifierB);
48048                             if (ts.pathIsRelative(specifierA) === isBRelative) {
48049                                 // Both relative or both non-relative, sort by number of parts
48050                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
48051                             }
48052                             if (isBRelative) {
48053                                 // A is non-relative, B is relative: prefer A
48054                                 return -1;
48055                             }
48056                             // A is relative, B is non-relative: prefer B
48057                             return 1;
48058                         }
48059                         return 0;
48060                     }
48061                 }
48062             }
48063             function typeParametersToTypeParameterDeclarations(symbol, context) {
48064                 var typeParameterNodes;
48065                 var targetSymbol = getTargetSymbol(symbol);
48066                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
48067                     typeParameterNodes = ts.factory.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
48068                 }
48069                 return typeParameterNodes;
48070             }
48071             function lookupTypeParameterNodes(chain, index, context) {
48072                 var _a;
48073                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
48074                 var symbol = chain[index];
48075                 var symbolId = getSymbolId(symbol);
48076                 if ((_a = context.typeParameterSymbolList) === null || _a === void 0 ? void 0 : _a.has(symbolId)) {
48077                     return undefined;
48078                 }
48079                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = new ts.Set())).add(symbolId);
48080                 var typeParameterNodes;
48081                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
48082                     var parentSymbol = symbol;
48083                     var nextSymbol_1 = chain[index + 1];
48084                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
48085                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
48086                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
48087                     }
48088                     else {
48089                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
48090                     }
48091                 }
48092                 return typeParameterNodes;
48093             }
48094             /**
48095              * Given A[B][C][D], finds A[B]
48096              */
48097             function getTopmostIndexedAccessType(top) {
48098                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
48099                     return getTopmostIndexedAccessType(top.objectType);
48100                 }
48101                 return top;
48102             }
48103             function getSpecifierForModuleSymbol(symbol, context) {
48104                 var _a;
48105                 var file = ts.getDeclarationOfKind(symbol, 297 /* SourceFile */);
48106                 if (!file) {
48107                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
48108                     if (equivalentFileSymbol) {
48109                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 297 /* SourceFile */);
48110                     }
48111                 }
48112                 if (file && file.moduleName !== undefined) {
48113                     // Use the amd name if it is available
48114                     return file.moduleName;
48115                 }
48116                 if (!file) {
48117                     if (context.tracker.trackReferencedAmbientModule) {
48118                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
48119                         if (ts.length(ambientDecls)) {
48120                             for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
48121                                 var decl = ambientDecls_1[_i];
48122                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
48123                             }
48124                         }
48125                     }
48126                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
48127                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
48128                     }
48129                 }
48130                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
48131                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
48132                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
48133                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
48134                     }
48135                     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
48136                 }
48137                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
48138                 var links = getSymbolLinks(symbol);
48139                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
48140                 if (!specifier) {
48141                     var isBundle_1 = !!ts.outFile(compilerOptions);
48142                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
48143                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
48144                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
48145                     // specifier preference
48146                     var moduleResolverHost = context.tracker.moduleResolverHost;
48147                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
48148                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined }));
48149                     (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map());
48150                     links.specifierCache.set(contextFile.path, specifier);
48151                 }
48152                 return specifier;
48153             }
48154             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
48155                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
48156                 var isTypeOf = meaning === 111551 /* Value */;
48157                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
48158                     // module is root, must use `ImportTypeNode`
48159                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
48160                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
48161                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
48162                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
48163                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
48164                         // since declaration files with these kinds of references are liable to fail when published :(
48165                         context.encounteredError = true;
48166                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
48167                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
48168                         }
48169                     }
48170                     var lit = ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(specifier));
48171                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
48172                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
48173                     context.approximateLength += specifier.length + 10; // specifier + import("")
48174                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
48175                         if (nonRootParts) {
48176                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
48177                             lastId.typeArguments = undefined;
48178                         }
48179                         return ts.factory.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
48180                     }
48181                     else {
48182                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
48183                         var qualifier = splitNode.objectType.typeName;
48184                         return ts.factory.createIndexedAccessTypeNode(ts.factory.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
48185                     }
48186                 }
48187                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
48188                 if (ts.isIndexedAccessTypeNode(entityName)) {
48189                     return entityName; // Indexed accesses can never be `typeof`
48190                 }
48191                 if (isTypeOf) {
48192                     return ts.factory.createTypeQueryNode(entityName);
48193                 }
48194                 else {
48195                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
48196                     var lastTypeArgs = lastId.typeArguments;
48197                     lastId.typeArguments = undefined;
48198                     return ts.factory.createTypeReferenceNode(entityName, lastTypeArgs);
48199                 }
48200                 function createAccessFromSymbolChain(chain, index, stopper) {
48201                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
48202                     var symbol = chain[index];
48203                     var parent = chain[index - 1];
48204                     var symbolName;
48205                     if (index === 0) {
48206                         context.flags |= 16777216 /* InInitialEntityName */;
48207                         symbolName = getNameOfSymbolAsWritten(symbol, context);
48208                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
48209                         context.flags ^= 16777216 /* InInitialEntityName */;
48210                     }
48211                     else {
48212                         if (parent && getExportsOfSymbol(parent)) {
48213                             var exports_1 = getExportsOfSymbol(parent);
48214                             ts.forEachEntry(exports_1, function (ex, name) {
48215                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
48216                                     symbolName = ts.unescapeLeadingUnderscores(name);
48217                                     return true;
48218                                 }
48219                             });
48220                         }
48221                     }
48222                     if (!symbolName) {
48223                         symbolName = getNameOfSymbolAsWritten(symbol, context);
48224                     }
48225                     context.approximateLength += symbolName.length + 1;
48226                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
48227                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
48228                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
48229                         // Should use an indexed access
48230                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
48231                         if (ts.isIndexedAccessTypeNode(LHS)) {
48232                             return ts.factory.createIndexedAccessTypeNode(LHS, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
48233                         }
48234                         else {
48235                             return ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeReferenceNode(LHS, typeParameterNodes), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
48236                         }
48237                     }
48238                     var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48239                     identifier.symbol = symbol;
48240                     if (index > stopper) {
48241                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
48242                         if (!ts.isEntityName(LHS)) {
48243                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
48244                         }
48245                         return ts.factory.createQualifiedName(LHS, identifier);
48246                     }
48247                     return identifier;
48248                 }
48249             }
48250             function typeParameterShadowsNameInScope(escapedName, context, type) {
48251                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
48252                 if (result) {
48253                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
48254                         return false;
48255                     }
48256                     return true;
48257                 }
48258                 return false;
48259             }
48260             function typeParameterToName(type, context) {
48261                 var _a;
48262                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
48263                     var cached = context.typeParameterNames.get(getTypeId(type));
48264                     if (cached) {
48265                         return cached;
48266                     }
48267                 }
48268                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
48269                 if (!(result.kind & 78 /* Identifier */)) {
48270                     return ts.factory.createIdentifier("(Missing type parameter)");
48271                 }
48272                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
48273                     var rawtext = result.escapedText;
48274                     var i = 0;
48275                     var text = rawtext;
48276                     while (((_a = context.typeParameterNamesByText) === null || _a === void 0 ? void 0 : _a.has(text)) || typeParameterShadowsNameInScope(text, context, type)) {
48277                         i++;
48278                         text = rawtext + "_" + i;
48279                     }
48280                     if (text !== rawtext) {
48281                         result = ts.factory.createIdentifier(text, result.typeArguments);
48282                     }
48283                     (context.typeParameterNames || (context.typeParameterNames = new ts.Map())).set(getTypeId(type), result);
48284                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = new ts.Set())).add(result.escapedText);
48285                 }
48286                 return result;
48287             }
48288             function symbolToName(symbol, context, meaning, expectsIdentifier) {
48289                 var chain = lookupSymbolChain(symbol, context, meaning);
48290                 if (expectsIdentifier && chain.length !== 1
48291                     && !context.encounteredError
48292                     && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
48293                     context.encounteredError = true;
48294                 }
48295                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
48296                 function createEntityNameFromSymbolChain(chain, index) {
48297                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
48298                     var symbol = chain[index];
48299                     if (index === 0) {
48300                         context.flags |= 16777216 /* InInitialEntityName */;
48301                     }
48302                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
48303                     if (index === 0) {
48304                         context.flags ^= 16777216 /* InInitialEntityName */;
48305                     }
48306                     var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48307                     identifier.symbol = symbol;
48308                     return index > 0 ? ts.factory.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
48309                 }
48310             }
48311             function symbolToExpression(symbol, context, meaning) {
48312                 var chain = lookupSymbolChain(symbol, context, meaning);
48313                 return createExpressionFromSymbolChain(chain, chain.length - 1);
48314                 function createExpressionFromSymbolChain(chain, index) {
48315                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
48316                     var symbol = chain[index];
48317                     if (index === 0) {
48318                         context.flags |= 16777216 /* InInitialEntityName */;
48319                     }
48320                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
48321                     if (index === 0) {
48322                         context.flags ^= 16777216 /* InInitialEntityName */;
48323                     }
48324                     var firstChar = symbolName.charCodeAt(0);
48325                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
48326                         return ts.factory.createStringLiteral(getSpecifierForModuleSymbol(symbol, context));
48327                     }
48328                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
48329                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
48330                         ts.isIdentifierStart(firstChar, languageVersion);
48331                     if (index === 0 || canUsePropertyAccess) {
48332                         var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48333                         identifier.symbol = symbol;
48334                         return index > 0 ? ts.factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
48335                     }
48336                     else {
48337                         if (firstChar === 91 /* openBracket */) {
48338                             symbolName = symbolName.substring(1, symbolName.length - 1);
48339                             firstChar = symbolName.charCodeAt(0);
48340                         }
48341                         var expression = void 0;
48342                         if (ts.isSingleOrDoubleQuote(firstChar)) {
48343                             expression = ts.factory.createStringLiteral(symbolName
48344                                 .substring(1, symbolName.length - 1)
48345                                 .replace(/\\./g, function (s) { return s.substring(1); }), firstChar === 39 /* singleQuote */);
48346                         }
48347                         else if (("" + +symbolName) === symbolName) {
48348                             expression = ts.factory.createNumericLiteral(+symbolName);
48349                         }
48350                         if (!expression) {
48351                             expression = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48352                             expression.symbol = symbol;
48353                         }
48354                         return ts.factory.createElementAccessExpression(createExpressionFromSymbolChain(chain, index - 1), expression);
48355                     }
48356                 }
48357             }
48358             function isStringNamed(d) {
48359                 var name = ts.getNameOfDeclaration(d);
48360                 return !!name && ts.isStringLiteral(name);
48361             }
48362             function isSingleQuotedStringNamed(d) {
48363                 var name = ts.getNameOfDeclaration(d);
48364                 return !!(name && ts.isStringLiteral(name) && (name.singleQuote || !ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")));
48365             }
48366             function getPropertyNameNodeForSymbol(symbol, context) {
48367                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
48368                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
48369                 if (fromNameType) {
48370                     return fromNameType;
48371                 }
48372                 if (ts.isKnownSymbol(symbol)) {
48373                     return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
48374                 }
48375                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
48376                 var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed);
48377                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote);
48378             }
48379             // See getNameForSymbolFromNameType for a stringy equivalent
48380             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
48381                 var nameType = getSymbolLinks(symbol).nameType;
48382                 if (nameType) {
48383                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
48384                         var name = "" + nameType.value;
48385                         if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
48386                             return ts.factory.createStringLiteral(name, !!singleQuote);
48387                         }
48388                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
48389                             return ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(+name));
48390                         }
48391                         return createPropertyNameNodeForIdentifierOrLiteral(name);
48392                     }
48393                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
48394                         return ts.factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
48395                     }
48396                 }
48397             }
48398             function createPropertyNameNodeForIdentifierOrLiteral(name, stringNamed, singleQuote) {
48399                 return ts.isIdentifierText(name, compilerOptions.target) ? ts.factory.createIdentifier(name) :
48400                     !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) :
48401                         ts.factory.createStringLiteral(name, !!singleQuote);
48402             }
48403             function cloneNodeBuilderContext(context) {
48404                 var initial = __assign({}, context);
48405                 // Make type parameters created within this context not consume the name outside this context
48406                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
48407                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
48408                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
48409                 // were multiple generic overloads with similar generated type parameter names
48410                 // The effect:
48411                 // When we write out
48412                 // export const x: <T>(x: T) => T
48413                 // export const y: <T>(x: T) => T
48414                 // we write it out like that, rather than as
48415                 // export const x: <T>(x: T) => T
48416                 // export const y: <T_1>(x: T_1) => T_1
48417                 if (initial.typeParameterNames) {
48418                     initial.typeParameterNames = new ts.Map(initial.typeParameterNames);
48419                 }
48420                 if (initial.typeParameterNamesByText) {
48421                     initial.typeParameterNamesByText = new ts.Set(initial.typeParameterNamesByText);
48422                 }
48423                 if (initial.typeParameterSymbolList) {
48424                     initial.typeParameterSymbolList = new ts.Set(initial.typeParameterSymbolList);
48425                 }
48426                 return initial;
48427             }
48428             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
48429                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
48430             }
48431             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
48432                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
48433             }
48434             /**
48435              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
48436              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
48437              */
48438             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
48439                 if (type !== errorType && enclosingDeclaration) {
48440                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
48441                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
48442                         // try to reuse the existing annotation
48443                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
48444                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
48445                             var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
48446                             if (result_5) {
48447                                 return result_5;
48448                             }
48449                         }
48450                     }
48451                 }
48452                 var oldFlags = context.flags;
48453                 if (type.flags & 8192 /* UniqueESSymbol */ &&
48454                     type.symbol === symbol && (!context.enclosingDeclaration || ts.some(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration); }))) {
48455                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
48456                 }
48457                 var result = typeToTypeNodeHelper(type, context);
48458                 context.flags = oldFlags;
48459                 return result;
48460             }
48461             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
48462                 if (type !== errorType && context.enclosingDeclaration) {
48463                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
48464                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
48465                         var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
48466                         if (result) {
48467                             return result;
48468                         }
48469                     }
48470                 }
48471                 return typeToTypeNodeHelper(type, context);
48472             }
48473             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
48474                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
48475                     cancellationToken.throwIfCancellationRequested();
48476                 }
48477                 var hadError = false;
48478                 var file = ts.getSourceFileOfNode(existing);
48479                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
48480                 if (hadError) {
48481                     return undefined;
48482                 }
48483                 return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed;
48484                 function visitExistingNodeTreeSymbols(node) {
48485                     var _a, _b;
48486                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
48487                     if (ts.isJSDocAllType(node) || node.kind === 310 /* JSDocNamepathType */) {
48488                         return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
48489                     }
48490                     if (ts.isJSDocUnknownType(node)) {
48491                         return ts.factory.createKeywordTypeNode(152 /* UnknownKeyword */);
48492                     }
48493                     if (ts.isJSDocNullableType(node)) {
48494                         return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createLiteralTypeNode(ts.factory.createNull())]);
48495                     }
48496                     if (ts.isJSDocOptionalType(node)) {
48497                         return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createKeywordTypeNode(150 /* UndefinedKeyword */)]);
48498                     }
48499                     if (ts.isJSDocNonNullableType(node)) {
48500                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
48501                     }
48502                     if (ts.isJSDocVariadicType(node)) {
48503                         return ts.factory.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
48504                     }
48505                     if (ts.isJSDocTypeLiteral(node)) {
48506                         return ts.factory.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
48507                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
48508                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
48509                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
48510                             return ts.factory.createPropertySignature(
48511                             /*modifiers*/ undefined, name, t.typeExpression && ts.isJSDocOptionalType(t.typeExpression.type) ? ts.factory.createToken(57 /* QuestionToken */) : undefined, overrideTypeNode || (t.typeExpression && ts.visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols)) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
48512                         }));
48513                     }
48514                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
48515                         return ts.setOriginalNode(ts.factory.createKeywordTypeNode(128 /* AnyKeyword */), node);
48516                     }
48517                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
48518                         return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(
48519                             /*decorators*/ undefined, 
48520                             /*modifiers*/ undefined, [ts.factory.createParameterDeclaration(
48521                                 /*decorators*/ undefined, 
48522                                 /*modifiers*/ undefined, 
48523                                 /*dotdotdotToken*/ undefined, "x", 
48524                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
48525                     }
48526                     if (ts.isJSDocFunctionType(node)) {
48527                         if (ts.isJSDocConstructSignature(node)) {
48528                             var newTypeNode_1;
48529                             return ts.factory.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration(
48530                             /*decorators*/ undefined, 
48531                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
48532                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
48533                         }
48534                         else {
48535                             return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration(
48536                             /*decorators*/ undefined, 
48537                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
48538                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
48539                         }
48540                     }
48541                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
48542                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
48543                     }
48544                     if (ts.isLiteralImportTypeNode(node)) {
48545                         return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
48546                     }
48547                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
48548                         var leftmost = ts.getFirstIdentifier(node);
48549                         if (ts.isInJSFile(node) && (ts.isExportsIdentifier(leftmost) || ts.isModuleExportsAccessExpression(leftmost.parent) || (ts.isQualifiedName(leftmost.parent) && ts.isModuleIdentifier(leftmost.parent.left) && ts.isExportsIdentifier(leftmost.parent.right)))) {
48550                             hadError = true;
48551                             return node;
48552                         }
48553                         var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
48554                         if (sym) {
48555                             if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
48556                                 hadError = true;
48557                             }
48558                             else {
48559                                 (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.trackSymbol) === null || _b === void 0 ? void 0 : _b.call(_a, sym, context.enclosingDeclaration, 67108863 /* All */);
48560                                 includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
48561                             }
48562                             if (ts.isIdentifier(node)) {
48563                                 var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.factory.cloneNode(node);
48564                                 name.symbol = sym; // for quickinfo, which uses identifier symbol information
48565                                 return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
48566                             }
48567                         }
48568                     }
48569                     if (file && ts.isTupleTypeNode(node) && (ts.getLineAndCharacterOfPosition(file, node.pos).line === ts.getLineAndCharacterOfPosition(file, node.end).line)) {
48570                         ts.setEmitFlags(node, 1 /* SingleLine */);
48571                     }
48572                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
48573                     function getEffectiveDotDotDotForParameter(p) {
48574                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined);
48575                     }
48576                     /** Note that `new:T` parameters are not handled, but should be before calling this function. */
48577                     function getNameForJSDocFunctionParameter(p, index) {
48578                         return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "this" ? "this"
48579                             : getEffectiveDotDotDotForParameter(p) ? "args"
48580                                 : "arg" + index;
48581                     }
48582                     function rewriteModuleSpecifier(parent, lit) {
48583                         if (bundled) {
48584                             if (context.tracker && context.tracker.moduleResolverHost) {
48585                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
48586                                 if (targetFile) {
48587                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
48588                                     var resolverHost = {
48589                                         getCanonicalFileName: getCanonicalFileName,
48590                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
48591                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
48592                                     };
48593                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
48594                                     return ts.factory.createStringLiteral(newName);
48595                                 }
48596                             }
48597                         }
48598                         else {
48599                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
48600                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
48601                                 if (moduleSym) {
48602                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
48603                                 }
48604                             }
48605                         }
48606                         return lit;
48607                     }
48608                 }
48609             }
48610             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
48611                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 165 /* MethodDeclaration */, /*useAcessors*/ true);
48612                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 164 /* MethodSignature */, /*useAcessors*/ false);
48613                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
48614                 // declaration mapping
48615                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
48616                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
48617                 // we're trying to emit from later on)
48618                 var enclosingDeclaration = context.enclosingDeclaration;
48619                 var results = [];
48620                 var visitedSymbols = new ts.Set();
48621                 var deferredPrivatesStack = [];
48622                 var oldcontext = context;
48623                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
48624                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
48625                             if (accessibleResult.accessibility === 0 /* Accessible */) {
48626                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
48627                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
48628                                 if (!(sym.flags & 4 /* Property */)) {
48629                                     includePrivateSymbol(chain[0]);
48630                                 }
48631                             }
48632                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
48633                                 oldcontext.tracker.trackSymbol(sym, decl, meaning);
48634                             }
48635                         } }) });
48636                 ts.forEachEntry(symbolTable, function (symbol, name) {
48637                     var baseName = ts.unescapeLeadingUnderscores(name);
48638                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
48639                 });
48640                 var addingDeclare = !bundled;
48641                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
48642                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
48643                     symbolTable = ts.createSymbolTable();
48644                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
48645                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
48646                 }
48647                 visitSymbolTable(symbolTable);
48648                 return mergeRedundantStatements(results);
48649                 function isIdentifierAndNotUndefined(node) {
48650                     return !!node && node.kind === 78 /* Identifier */;
48651                 }
48652                 function getNamesOfDeclaration(statement) {
48653                     if (ts.isVariableStatement(statement)) {
48654                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
48655                     }
48656                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
48657                 }
48658                 function flattenExportAssignedNamespace(statements) {
48659                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
48660                     var nsIndex = ts.findIndex(statements, ts.isModuleDeclaration);
48661                     var ns = nsIndex !== -1 ? statements[nsIndex] : undefined;
48662                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
48663                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
48664                         ns.body && ts.isModuleBlock(ns.body)) {
48665                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
48666                         //  the top-level exports and exporting them in the targeted ns, as can occur when a js file has both typedefs and `module.export` assignments
48667                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getEffectiveModifierFlags(s) & 1 /* Export */); });
48668                         var name_2 = ns.name;
48669                         var body = ns.body;
48670                         if (ts.length(excessExports)) {
48671                             ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArrays(ns.body.statements, [ts.factory.createExportDeclaration(
48672                                 /*decorators*/ undefined, 
48673                                 /*modifiers*/ undefined, 
48674                                 /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*alias*/ undefined, id); })), 
48675                                 /*moduleSpecifier*/ undefined)]))));
48676                             statements = __spreadArrays(statements.slice(0, nsIndex), [ns], statements.slice(nsIndex + 1));
48677                         }
48678                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
48679                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, name_2); })) {
48680                             results = [];
48681                             // If the namespace contains no export assignments or declarations, and no declarations flagged with `export`, then _everything_ is exported -
48682                             // to respect this as the top level, we need to add an `export` modifier to everything
48683                             var mixinExportFlag_1 = !ts.some(body.statements, function (s) { return ts.hasSyntacticModifier(s, 1 /* Export */) || ts.isExportAssignment(s) || ts.isExportDeclaration(s); });
48684                             ts.forEach(body.statements, function (s) {
48685                                 addResult(s, mixinExportFlag_1 ? 1 /* Export */ : 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
48686                             });
48687                             statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
48688                         }
48689                     }
48690                     return statements;
48691                 }
48692                 function mergeExportDeclarations(statements) {
48693                     // Pass 2: Combine all `export {}` declarations
48694                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
48695                     if (ts.length(exports) > 1) {
48696                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
48697                         statements = __spreadArrays(nonExports, [ts.factory.createExportDeclaration(
48698                             /*decorators*/ undefined, 
48699                             /*modifiers*/ undefined, 
48700                             /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
48701                             /*moduleSpecifier*/ undefined)]);
48702                     }
48703                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
48704                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
48705                     if (ts.length(reexports) > 1) {
48706                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
48707                         if (groups.length !== reexports.length) {
48708                             var _loop_9 = function (group_1) {
48709                                 if (group_1.length > 1) {
48710                                     // remove group members from statements and then merge group members and add back to statements
48711                                     statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
48712                                         ts.factory.createExportDeclaration(
48713                                         /*decorators*/ undefined, 
48714                                         /*modifiers*/ undefined, 
48715                                         /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
48716                                     ]);
48717                                 }
48718                             };
48719                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
48720                                 var group_1 = groups_1[_i];
48721                                 _loop_9(group_1);
48722                             }
48723                         }
48724                     }
48725                     return statements;
48726                 }
48727                 function inlineExportModifiers(statements) {
48728                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
48729                     var index = ts.findIndex(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
48730                     if (index >= 0) {
48731                         var exportDecl = statements[index];
48732                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
48733                             if (!e.propertyName) {
48734                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
48735                                 var indices = ts.indicesOf(statements);
48736                                 var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); });
48737                                 if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) {
48738                                     for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) {
48739                                         var index_1 = associatedIndices_1[_i];
48740                                         statements[index_1] = addExportModifier(statements[index_1]);
48741                                     }
48742                                     return undefined;
48743                                 }
48744                             }
48745                             return e;
48746                         });
48747                         if (!ts.length(replacements)) {
48748                             // all clauses removed, remove the export declaration
48749                             ts.orderedRemoveItemAt(statements, index);
48750                         }
48751                         else {
48752                             // some items filtered, others not - update the export declaration
48753                             statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier);
48754                         }
48755                     }
48756                     return statements;
48757                 }
48758                 function mergeRedundantStatements(statements) {
48759                     statements = flattenExportAssignedNamespace(statements);
48760                     statements = mergeExportDeclarations(statements);
48761                     statements = inlineExportModifiers(statements);
48762                     // Not a cleanup, but as a final step: If there is a mix of `export` and non-`export` declarations, but no `export =` or `export {}` add a `export {};` so
48763                     // declaration privacy is respected.
48764                     if (enclosingDeclaration &&
48765                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
48766                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
48767                         statements.push(ts.createEmptyExports(ts.factory));
48768                     }
48769                     return statements;
48770                 }
48771                 function canHaveExportModifier(node) {
48772                     return ts.isEnumDeclaration(node) ||
48773                         ts.isVariableStatement(node) ||
48774                         ts.isFunctionDeclaration(node) ||
48775                         ts.isClassDeclaration(node) ||
48776                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
48777                         ts.isInterfaceDeclaration(node) ||
48778                         isTypeDeclaration(node);
48779                 }
48780                 function addExportModifier(node) {
48781                     var flags = (ts.getEffectiveModifierFlags(node) | 1 /* Export */) & ~2 /* Ambient */;
48782                     return ts.factory.updateModifiers(node, flags);
48783                 }
48784                 function removeExportModifier(node) {
48785                     var flags = ts.getEffectiveModifierFlags(node) & ~1 /* Export */;
48786                     return ts.factory.updateModifiers(node, flags);
48787                 }
48788                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
48789                     if (!suppressNewPrivateContext) {
48790                         deferredPrivatesStack.push(new ts.Map());
48791                     }
48792                     symbolTable.forEach(function (symbol) {
48793                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
48794                     });
48795                     if (!suppressNewPrivateContext) {
48796                         // deferredPrivates will be filled up by visiting the symbol table
48797                         // And will continue to iterate as elements are added while visited `deferredPrivates`
48798                         // (As that's how a map iterator is defined to work)
48799                         deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach(function (symbol) {
48800                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
48801                         });
48802                         deferredPrivatesStack.pop();
48803                     }
48804                 }
48805                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
48806                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
48807                     // still skip reserializing it if we encounter the merged product later on
48808                     var visitedSym = getMergedSymbol(symbol);
48809                     if (visitedSymbols.has(getSymbolId(visitedSym))) {
48810                         return; // Already printed
48811                     }
48812                     visitedSymbols.add(getSymbolId(visitedSym));
48813                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
48814                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
48815                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
48816                         var oldContext = context;
48817                         context = cloneNodeBuilderContext(context);
48818                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
48819                         context = oldContext;
48820                         return result;
48821                     }
48822                 }
48823                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
48824                 // or a merge of some number of those.
48825                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
48826                 // each symbol in only one of the representations
48827                 // Also, synthesizing a default export of some kind
48828                 // If it's an alias: emit `export default ref`
48829                 // If it's a property: emit `export default _default` with a `_default` prop
48830                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
48831                 // These forms can merge, eg (`export default 12; export default interface A {}`)
48832                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
48833                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
48834                     var isDefault = symbol.escapedName === "default" /* Default */;
48835                     if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
48836                         // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :(
48837                         context.encounteredError = true;
48838                         // TODO: Issue error via symbol tracker?
48839                         return; // If we need to emit a private with a keyword name, we're done for, since something else will try to refer to it by that name
48840                     }
48841                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
48842                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
48843                     var needsExportDeclaration = !needsPostExportDefault && !isPrivate && ts.isStringANonContextualKeyword(symbolName) && !isDefault;
48844                     // `serializeVariableOrProperty` will handle adding the export declaration if it is run (since `getInternalSymbolName` will create the name mapping), so we need to ensuer we unset `needsExportDeclaration` if it is
48845                     if (needsPostExportDefault || needsExportDeclaration) {
48846                         isPrivate = true;
48847                     }
48848                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
48849                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
48850                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
48851                         symbol.escapedName !== "export=" /* ExportEquals */;
48852                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
48853                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
48854                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
48855                     }
48856                     if (symbol.flags & 524288 /* TypeAlias */) {
48857                         serializeTypeAlias(symbol, symbolName, modifierFlags);
48858                     }
48859                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
48860                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
48861                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
48862                         && symbol.escapedName !== "export=" /* ExportEquals */
48863                         && !(symbol.flags & 4194304 /* Prototype */)
48864                         && !(symbol.flags & 32 /* Class */)
48865                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
48866                         if (propertyAsAlias) {
48867                             var createdExport = serializeMaybeAliasAssignment(symbol);
48868                             if (createdExport) {
48869                                 needsExportDeclaration = false;
48870                                 needsPostExportDefault = false;
48871                             }
48872                         }
48873                         else {
48874                             var type = getTypeOfSymbol(symbol);
48875                             var localName = getInternalSymbolName(symbol, symbolName);
48876                             if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
48877                                 // If the type looks like a function declaration + ns could represent it, and it's type is sourced locally, rewrite it into a function declaration + ns
48878                                 serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
48879                             }
48880                             else {
48881                                 // A Class + Property merge is made for a `module.exports.Member = class {}`, and it doesn't serialize well as either a class _or_ a property symbol - in fact, _it behaves like an alias!_
48882                                 // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
48883                                 var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
48884                                     : isConstVariable(symbol) ? 2 /* Const */
48885                                         : 1 /* Let */;
48886                                 var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
48887                                 var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
48888                                 if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
48889                                     textRange = textRange.parent.parent;
48890                                 }
48891                                 var propertyAccessRequire = ts.find(symbol.declarations, ts.isPropertyAccessExpression);
48892                                 if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right)
48893                                     && type.symbol && ts.isSourceFile(type.symbol.valueDeclaration)) {
48894                                     var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right;
48895                                     addResult(ts.factory.createExportDeclaration(
48896                                     /*decorators*/ undefined, 
48897                                     /*modifiers*/ undefined, 
48898                                     /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(alias, localName)])), 0 /* None */);
48899                                     context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* Value */);
48900                                 }
48901                                 else {
48902                                     var statement = ts.setTextRange(ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
48903                                         ts.factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
48904                                     ], flags)), textRange);
48905                                     addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
48906                                     if (name !== localName && !isPrivate) {
48907                                         // We rename the variable declaration we generate for Property symbols since they may have a name which
48908                                         // conflicts with a local declaration. For example, given input:
48909                                         // ```
48910                                         // function g() {}
48911                                         // module.exports.g = g
48912                                         // ```
48913                                         // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
48914                                         // Naively, we would emit
48915                                         // ```
48916                                         // function g() {}
48917                                         // export const g: typeof g;
48918                                         // ```
48919                                         // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
48920                                         // the export declaration shadows it.
48921                                         // To work around that, we instead write
48922                                         // ```
48923                                         // function g() {}
48924                                         // const g_1: typeof g;
48925                                         // export { g_1 as g };
48926                                         // ```
48927                                         // To create an export named `g` that does _not_ shadow the local `g`
48928                                         addResult(ts.factory.createExportDeclaration(
48929                                         /*decorators*/ undefined, 
48930                                         /*modifiers*/ undefined, 
48931                                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(name, localName)])), 0 /* None */);
48932                                         needsExportDeclaration = false;
48933                                         needsPostExportDefault = false;
48934                                     }
48935                                 }
48936                             }
48937                         }
48938                     }
48939                     if (symbol.flags & 384 /* Enum */) {
48940                         serializeEnum(symbol, symbolName, modifierFlags);
48941                     }
48942                     if (symbol.flags & 32 /* Class */) {
48943                         if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
48944                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
48945                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
48946                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
48947                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
48948                         }
48949                         else {
48950                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
48951                         }
48952                     }
48953                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
48954                         serializeModule(symbol, symbolName, modifierFlags);
48955                     }
48956                     // The class meaning serialization should handle serializing all interface members
48957                     if (symbol.flags & 64 /* Interface */ && !(symbol.flags & 32 /* Class */)) {
48958                         serializeInterface(symbol, symbolName, modifierFlags);
48959                     }
48960                     if (symbol.flags & 2097152 /* Alias */) {
48961                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
48962                     }
48963                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
48964                         serializeMaybeAliasAssignment(symbol);
48965                     }
48966                     if (symbol.flags & 8388608 /* ExportStar */) {
48967                         // synthesize export * from "moduleReference"
48968                         // Straightforward - only one thing to do - make an export declaration
48969                         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
48970                             var node = _a[_i];
48971                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
48972                             if (!resolvedModule)
48973                                 continue;
48974                             addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
48975                         }
48976                     }
48977                     if (needsPostExportDefault) {
48978                         addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
48979                     }
48980                     else if (needsExportDeclaration) {
48981                         addResult(ts.factory.createExportDeclaration(
48982                         /*decorators*/ undefined, 
48983                         /*modifiers*/ undefined, 
48984                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* None */);
48985                     }
48986                 }
48987                 function includePrivateSymbol(symbol) {
48988                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
48989                         return;
48990                     ts.Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]);
48991                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
48992                     // Blanket moving (import) aliases into the root private context should work, since imports are not valid within namespaces
48993                     // (so they must have been in the root to begin with if they were real imports) cjs `require` aliases (an upcoming feature)
48994                     // will throw a wrench in this, since those may have been nested, but we'll need to synthesize them in the outer scope
48995                     // anyway, as that's the only place the import they translate to is valid. In such a case, we might need to use a unique name
48996                     // for the moved import; which hopefully the above `getUnusedName` call should produce.
48997                     var isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !ts.some(symbol.declarations, function (d) {
48998                         return !!ts.findAncestor(d, ts.isExportDeclaration) ||
48999                             ts.isNamespaceExport(d) ||
49000                             (ts.isImportEqualsDeclaration(d) && !ts.isExternalModuleReference(d.moduleReference));
49001                     });
49002                     deferredPrivatesStack[isExternalImportAlias ? 0 : (deferredPrivatesStack.length - 1)].set(getSymbolId(symbol), symbol);
49003                 }
49004                 function isExportingScope(enclosingDeclaration) {
49005                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
49006                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
49007                 }
49008                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
49009                 function addResult(node, additionalModifierFlags) {
49010                     if (ts.canHaveModifiers(node)) {
49011                         var newModifierFlags = 0 /* None */;
49012                         if (additionalModifierFlags & 1 /* Export */ &&
49013                             context.enclosingDeclaration &&
49014                             (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) &&
49015                             canHaveExportModifier(node)) {
49016                             // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
49017                             newModifierFlags |= 1 /* Export */;
49018                         }
49019                         if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
49020                             (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
49021                             (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
49022                             // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
49023                             newModifierFlags |= 2 /* Ambient */;
49024                         }
49025                         if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
49026                             newModifierFlags |= 512 /* Default */;
49027                         }
49028                         if (newModifierFlags) {
49029                             node = ts.factory.updateModifiers(node, newModifierFlags | ts.getEffectiveModifierFlags(node));
49030                         }
49031                     }
49032                     results.push(node);
49033                 }
49034                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
49035                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
49036                     var typeParams = getSymbolLinks(symbol).typeParameters;
49037                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
49038                     var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
49039                     var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
49040                     var oldFlags = context.flags;
49041                     context.flags |= 8388608 /* InTypeAlias */;
49042                     addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeToTypeNodeHelper(aliasType, context)), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags);
49043                     context.flags = oldFlags;
49044                 }
49045                 function serializeInterface(symbol, symbolName, modifierFlags) {
49046                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
49047                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
49048                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
49049                     var baseTypes = getBaseTypes(interfaceType);
49050                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
49051                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
49052                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 169 /* CallSignature */);
49053                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 170 /* ConstructSignature */);
49054                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
49055                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))];
49056                     addResult(ts.factory.createInterfaceDeclaration(
49057                     /*decorators*/ undefined, 
49058                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
49059                 }
49060                 function getNamespaceMembersForSerialization(symbol) {
49061                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
49062                 }
49063                 function isTypeOnlyNamespace(symbol) {
49064                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
49065                 }
49066                 function serializeModule(symbol, symbolName, modifierFlags) {
49067                     var members = getNamespaceMembersForSerialization(symbol);
49068                     // Split NS members up by declaration - members whose parent symbol is the ns symbol vs those whose is not (but were added in later via merging)
49069                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
49070                     var realMembers = locationMap.get("real") || ts.emptyArray;
49071                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
49072                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
49073                     // than whatever scope we traverse to them in. That's a bit of a complex rewrite, since we're not _actually_ tracking privates at all in advance,
49074                     // so we don't even have placeholders to fill in.
49075                     if (ts.length(realMembers)) {
49076                         var localName = getInternalSymbolName(symbol, symbolName);
49077                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
49078                     }
49079                     if (ts.length(mergedMembers)) {
49080                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
49081                         var localName = getInternalSymbolName(symbol, symbolName);
49082                         var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration(
49083                             /*decorators*/ undefined, 
49084                             /*modifiers*/ undefined, 
49085                             /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
49086                                 var _a, _b;
49087                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
49088                                 var localName = getInternalSymbolName(s, name);
49089                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
49090                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
49091                                     (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonlocalAugmentation) === null || _b === void 0 ? void 0 : _b.call(_a, containingFile_1, symbol, s);
49092                                     return undefined;
49093                                 }
49094                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
49095                                 includePrivateSymbol(target || s);
49096                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
49097                                 return ts.factory.createExportSpecifier(name === targetName ? undefined : targetName, name);
49098                             })))]);
49099                         addResult(ts.factory.createModuleDeclaration(
49100                         /*decorators*/ undefined, 
49101                         /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
49102                     }
49103                 }
49104                 function serializeEnum(symbol, symbolName, modifierFlags) {
49105                     addResult(ts.factory.createEnumDeclaration(
49106                     /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* EnumMember */); }), function (p) {
49107                         // TODO: Handle computed names
49108                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
49109                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
49110                         // _on the declaration_, not on the declaration's symbol...
49111                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : undefined;
49112                         return ts.factory.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined :
49113                             typeof initializedValue === "string" ? ts.factory.createStringLiteral(initializedValue) :
49114                                 ts.factory.createNumericLiteral(initializedValue));
49115                     })), modifierFlags);
49116                 }
49117                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
49118                     var signatures = getSignaturesOfType(type, 0 /* Call */);
49119                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
49120                         var sig = signatures_2[_i];
49121                         // Each overload becomes a separate function declaration, in order
49122                         var decl = signatureToSignatureDeclarationHelper(sig, 251 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled });
49123                         // for expressions assigned to `var`s, use the `var` as the text range
49124                         addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
49125                     }
49126                     // Module symbol emit will take care of module-y members, provided it has exports
49127                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
49128                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
49129                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
49130                     }
49131                 }
49132                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
49133                     if (ts.length(props)) {
49134                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
49135                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
49136                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
49137                             }) ? "local" : "remote";
49138                         });
49139                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
49140                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
49141                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
49142                         // Example:
49143                         // import Foo_1 = require("./exporter");
49144                         // export namespace ns {
49145                         //     import Foo = Foo_1.Foo;
49146                         //     export { Foo };
49147                         //     export const c: number;
49148                         // }
49149                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
49150                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
49151                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
49152                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
49153                         // emit akin to the above would be needed.
49154                         // Add a namespace
49155                         // Create namespace as non-synthetic so it is usable as an enclosing declaration
49156                         var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* Namespace */);
49157                         ts.setParent(fakespace, enclosingDeclaration);
49158                         fakespace.locals = ts.createSymbolTable(props);
49159                         fakespace.symbol = props[0].parent;
49160                         var oldResults = results;
49161                         results = [];
49162                         var oldAddingDeclare = addingDeclare;
49163                         addingDeclare = false;
49164                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
49165                         var oldContext = context;
49166                         context = subcontext;
49167                         // TODO: implement handling for the localVsRemoteMap.get("remote") - should be difficult to trigger (see comment above), as only interesting cross-file js merges should make this possible
49168                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
49169                         context = oldContext;
49170                         addingDeclare = oldAddingDeclare;
49171                         var declarations = results;
49172                         results = oldResults;
49173                         // replace namespace with synthetic version
49174                         var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration(
49175                         /*decorators*/ undefined, 
49176                         /*modifiers*/ undefined, 
49177                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(d.expression, ts.factory.createIdentifier("default" /* Default */))])) : d; });
49178                         var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced;
49179                         fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped));
49180                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
49181                     }
49182                 }
49183                 function isNamespaceMember(p) {
49184                     return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) ||
49185                         !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.getEffectiveModifierFlags(p.valueDeclaration) & 32 /* Static */ && ts.isClassLike(p.valueDeclaration.parent));
49186                 }
49187                 function serializeAsClass(symbol, localName, modifierFlags) {
49188                     var _a;
49189                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
49190                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
49191                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
49192                     var baseTypes = getBaseTypes(classType);
49193                     var implementsExpressions = ts.mapDefined(getImplementsTypes(classType), serializeImplementedType);
49194                     var staticType = getTypeOfSymbol(symbol);
49195                     var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration);
49196                     var staticBaseType = isClass
49197                         ? getBaseConstructorTypeOfClass(staticType)
49198                         : anyType;
49199                     var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(116 /* ImplementsKeyword */, implementsExpressions)]);
49200                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
49201                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
49202                         // `valueDeclaration` could be undefined if inherited from
49203                         // a union/intersection base type, but inherited properties
49204                         // don't matter here.
49205                         var valueDecl = s.valueDeclaration;
49206                         return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
49207                     });
49208                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
49209                         // `valueDeclaration` could be undefined if inherited from
49210                         // a union/intersection base type, but inherited properties
49211                         // don't matter here.
49212                         var valueDecl = s.valueDeclaration;
49213                         return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
49214                     });
49215                     // Boil down all private properties into a single one.
49216                     var privateProperties = hasPrivateIdentifier ?
49217                         [ts.factory.createPropertyDeclaration(
49218                             /*decorators*/ undefined, 
49219                             /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), 
49220                             /*questionOrExclamationToken*/ undefined, 
49221                             /*type*/ undefined, 
49222                             /*initializer*/ undefined)] :
49223                         ts.emptyArray;
49224                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
49225                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
49226                     var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); });
49227                     // When we encounter an `X.prototype.y` assignment in a JS file, we bind `X` as a class regardless as to whether
49228                     // the value is ever initialized with a class or function-like value. For cases where `X` could never be
49229                     // created via `new`, we will inject a `private constructor()` declaration to indicate it is not createable.
49230                     var isNonConstructableClassLikeInJsFile = !isClass &&
49231                         !!symbol.valueDeclaration &&
49232                         ts.isInJSFile(symbol.valueDeclaration) &&
49233                         !ts.some(getSignaturesOfType(staticType, 1 /* Construct */));
49234                     var constructors = isNonConstructableClassLikeInJsFile ?
49235                         [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] :
49236                         serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 166 /* Constructor */);
49237                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
49238                     addResult(ts.setTextRange(ts.factory.createClassDeclaration(
49239                     /*decorators*/ undefined, 
49240                     /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, staticMembers, constructors, publicProperties, privateProperties)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags);
49241                 }
49242                 function serializeAsAlias(symbol, localName, modifierFlags) {
49243                     var _a, _b, _c, _d, _e;
49244                     // synthesize an alias, eg `export { symbolName as Name }`
49245                     // need to mark the alias `symbol` points at
49246                     // as something we need to serialize as a private declaration as well
49247                     var node = getDeclarationOfAliasSymbol(symbol);
49248                     if (!node)
49249                         return ts.Debug.fail();
49250                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
49251                     if (!target) {
49252                         return;
49253                     }
49254                     var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
49255                     if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
49256                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
49257                         verbatimTargetName = "default" /* Default */;
49258                     }
49259                     var targetName = getInternalSymbolName(target, verbatimTargetName);
49260                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
49261                     switch (node.kind) {
49262                         case 198 /* BindingElement */:
49263                             if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 249 /* VariableDeclaration */) {
49264                                 // const { SomeClass } = require('./lib');
49265                                 var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib'
49266                                 var propertyName = node.propertyName;
49267                                 addResult(ts.factory.createImportDeclaration(
49268                                 /*decorators*/ undefined, 
49269                                 /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier(propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1)), 0 /* None */);
49270                                 break;
49271                             }
49272                             // We don't know how to serialize this (nested?) binding element
49273                             ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization");
49274                             break;
49275                         case 289 /* ShorthandPropertyAssignment */:
49276                             if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 216 /* BinaryExpression */) {
49277                                 // module.exports = { SomeClass }
49278                                 serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName);
49279                             }
49280                             break;
49281                         case 249 /* VariableDeclaration */:
49282                             // commonjs require: const x = require('y')
49283                             if (ts.isPropertyAccessExpression(node.initializer)) {
49284                                 // const x = require('y').z
49285                                 var initializer = node.initializer; // require('y').z
49286                                 var uniqueName = ts.factory.createUniqueName(localName); // _x
49287                                 var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y'
49288                                 // import _x = require('y');
49289                                 addResult(ts.factory.createImportEqualsDeclaration(
49290                                 /*decorators*/ undefined, 
49291                                 /*modifiers*/ undefined, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* None */);
49292                                 // import x = _x.z
49293                                 addResult(ts.factory.createImportEqualsDeclaration(
49294                                 /*decorators*/ undefined, 
49295                                 /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags);
49296                                 break;
49297                             }
49298                         // else fall through and treat commonjs require just like import=
49299                         case 260 /* ImportEqualsDeclaration */:
49300                             // This _specifically_ only exists to handle json declarations - where we make aliases, but since
49301                             // we emit no declarations for the json document, must not refer to it in the declarations
49302                             if (target.escapedName === "export=" /* ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) {
49303                                 serializeMaybeAliasAssignment(symbol);
49304                                 break;
49305                             }
49306                             // Could be a local `import localName = ns.member` or
49307                             // an external `import localName = require("whatever")`
49308                             var isLocalImport = !(target.flags & 512 /* ValueModule */) && !ts.isVariableDeclaration(node);
49309                             addResult(ts.factory.createImportEqualsDeclaration(
49310                             /*decorators*/ undefined, 
49311                             /*modifiers*/ undefined, ts.factory.createIdentifier(localName), isLocalImport
49312                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
49313                                 : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */);
49314                             break;
49315                         case 259 /* NamespaceExportDeclaration */:
49316                             // export as namespace foo
49317                             // TODO: Not part of a file's local or export symbol tables
49318                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
49319                             addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
49320                             break;
49321                         case 262 /* ImportClause */:
49322                             addResult(ts.factory.createImportDeclaration(
49323                             /*decorators*/ undefined, 
49324                             /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), 
49325                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
49326                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
49327                             // In such cases, the `target` refers to the module itself already
49328                             ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
49329                             break;
49330                         case 263 /* NamespaceImport */:
49331                             addResult(ts.factory.createImportDeclaration(
49332                             /*decorators*/ undefined, 
49333                             /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
49334                             break;
49335                         case 269 /* NamespaceExport */:
49336                             addResult(ts.factory.createExportDeclaration(
49337                             /*decorators*/ undefined, 
49338                             /*modifiers*/ undefined, 
49339                             /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
49340                             break;
49341                         case 265 /* ImportSpecifier */:
49342                             addResult(ts.factory.createImportDeclaration(
49343                             /*decorators*/ undefined, 
49344                             /*modifiers*/ undefined, ts.factory.createImportClause(
49345                             /*isTypeOnly*/ false, 
49346                             /*importClause*/ undefined, ts.factory.createNamedImports([
49347                                 ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName))
49348                             ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
49349                             break;
49350                         case 270 /* ExportSpecifier */:
49351                             // does not use localName because the symbol name in this case refers to the name in the exports table,
49352                             // which we must exactly preserve
49353                             var specifier = node.parent.parent.moduleSpecifier;
49354                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
49355                             // another file
49356                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined);
49357                             break;
49358                         case 266 /* ExportAssignment */:
49359                             serializeMaybeAliasAssignment(symbol);
49360                             break;
49361                         case 216 /* BinaryExpression */:
49362                         case 201 /* PropertyAccessExpression */:
49363                         case 202 /* ElementAccessExpression */:
49364                             // Could be best encoded as though an export specifier or as though an export assignment
49365                             // If name is default or export=, do an export assignment
49366                             // Otherwise do an export specifier
49367                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
49368                                 serializeMaybeAliasAssignment(symbol);
49369                             }
49370                             else {
49371                                 serializeExportSpecifier(localName, targetName);
49372                             }
49373                             break;
49374                         default:
49375                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
49376                     }
49377                 }
49378                 function serializeExportSpecifier(localName, targetName, specifier) {
49379                     addResult(ts.factory.createExportDeclaration(
49380                     /*decorators*/ undefined, 
49381                     /*modifiers*/ undefined, 
49382                     /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
49383                 }
49384                 /**
49385                  * Returns `true` if an export assignment or declaration was produced for the symbol
49386                  */
49387                 function serializeMaybeAliasAssignment(symbol) {
49388                     if (symbol.flags & 4194304 /* Prototype */) {
49389                         return false;
49390                     }
49391                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
49392                     var isExportEquals = name === "export=" /* ExportEquals */;
49393                     var isDefault = name === "default" /* Default */;
49394                     var isExportAssignmentCompatibleSymbolName = isExportEquals || isDefault;
49395                     // synthesize export = ref
49396                     // ref should refer to either be a locally scoped symbol which we need to emit, or
49397                     // a reference to another namespace/module which we may need to emit an `import` statement for
49398                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
49399                     // serialize what the alias points to, preserve the declaration's initializer
49400                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
49401                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
49402                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
49403                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
49404                         // eg, `namespace A { export class B {} }; exports = A.B;`
49405                         // Technically, this is all that's required in the case where the assignment is an entity name expression
49406                         var expr = aliasDecl && ((ts.isExportAssignment(aliasDecl) || ts.isBinaryExpression(aliasDecl)) ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl));
49407                         var first_1 = expr && ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
49408                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
49409                         if (referenced || target) {
49410                             includePrivateSymbol(referenced || target);
49411                         }
49412                         // We disable the context's symbol tracker for the duration of this name serialization
49413                         // as, by virtue of being here, the name is required to print something, and we don't want to
49414                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
49415                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
49416                         // into the containing scope anyway, so we want to skip the visibility checks.
49417                         var oldTrack = context.tracker.trackSymbol;
49418                         context.tracker.trackSymbol = ts.noop;
49419                         if (isExportAssignmentCompatibleSymbolName) {
49420                             results.push(ts.factory.createExportAssignment(
49421                             /*decorators*/ undefined, 
49422                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
49423                         }
49424                         else {
49425                             if (first_1 === expr && first_1) {
49426                                 // serialize as `export {target as name}`
49427                                 serializeExportSpecifier(name, ts.idText(first_1));
49428                             }
49429                             else if (expr && ts.isClassExpression(expr)) {
49430                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
49431                             }
49432                             else {
49433                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
49434                                 var varName = getUnusedName(name, symbol);
49435                                 addResult(ts.factory.createImportEqualsDeclaration(
49436                                 /*decorators*/ undefined, 
49437                                 /*modifiers*/ undefined, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
49438                                 serializeExportSpecifier(name, varName);
49439                             }
49440                         }
49441                         context.tracker.trackSymbol = oldTrack;
49442                         return true;
49443                     }
49444                     else {
49445                         // serialize as an anonymous property declaration
49446                         var varName = getUnusedName(name, symbol);
49447                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
49448                         // (Unwidened types can only exist in expression contexts and should never be serialized)
49449                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
49450                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
49451                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
49452                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 1 /* Export */);
49453                         }
49454                         else {
49455                             var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
49456                                 ts.factory.createVariableDeclaration(varName, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
49457                             ], 2 /* Const */));
49458                             // Inlined JSON types exported with [module.]exports= will already emit an export=, so should use `declare`.
49459                             // Otherwise, the type itself should be exported.
49460                             addResult(statement, target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 2 /* Ambient */
49461                                 : name === varName ? 1 /* Export */
49462                                     : 0 /* None */);
49463                         }
49464                         if (isExportAssignmentCompatibleSymbolName) {
49465                             results.push(ts.factory.createExportAssignment(
49466                             /*decorators*/ undefined, 
49467                             /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName)));
49468                             return true;
49469                         }
49470                         else if (name !== varName) {
49471                             serializeExportSpecifier(name, varName);
49472                             return true;
49473                         }
49474                         return false;
49475                     }
49476                 }
49477                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
49478                     // Only object types which are not constructable, or indexable, whose members all come from the
49479                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
49480                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
49481                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
49482                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
49483                         !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
49484                         !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
49485                         !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class
49486                         !!(ts.length(ts.filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
49487                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
49488                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
49489                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
49490                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
49491                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
49492                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion); });
49493                 }
49494                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
49495                     return function serializePropertySymbol(p, isStatic, baseType) {
49496                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
49497                         var isPrivate = !!(modifierFlags & 8 /* Private */);
49498                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
49499                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
49500                             // need to be merged namespace members
49501                             return [];
49502                         }
49503                         if (p.flags & 4194304 /* Prototype */ ||
49504                             (baseType && getPropertyOfType(baseType, p.escapedName)
49505                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
49506                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
49507                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
49508                             return [];
49509                         }
49510                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
49511                         var name = getPropertyNameNodeForSymbol(p, context);
49512                         var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
49513                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
49514                             var result = [];
49515                             if (p.flags & 65536 /* SetAccessor */) {
49516                                 result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(
49517                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration(
49518                                     /*decorators*/ undefined, 
49519                                     /*modifiers*/ undefined, 
49520                                     /*dotDotDotToken*/ undefined, "arg", 
49521                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
49522                                 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
49523                             }
49524                             if (p.flags & 32768 /* GetAccessor */) {
49525                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
49526                                 result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(
49527                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
49528                                 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
49529                             }
49530                             return result;
49531                         }
49532                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
49533                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
49534                         else if (p.flags & (4 /* Property */ | 3 /* Variable */ | 98304 /* Accessor */)) {
49535                             return ts.setTextRange(createProperty(
49536                             /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
49537                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
49538                             // interface members can't have initializers, however class members _can_
49539                             /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
49540                         }
49541                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
49542                             var type = getTypeOfSymbol(p);
49543                             var signatures = getSignaturesOfType(type, 0 /* Call */);
49544                             if (flag & 8 /* Private */) {
49545                                 return ts.setTextRange(createProperty(
49546                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, 
49547                                 /*type*/ undefined, 
49548                                 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
49549                             }
49550                             var results_1 = [];
49551                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
49552                                 var sig = signatures_3[_i];
49553                                 // Each overload becomes a separate method declaration, in order
49554                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context, {
49555                                     name: name,
49556                                     questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined,
49557                                     modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined
49558                                 });
49559                                 results_1.push(ts.setTextRange(decl, sig.declaration));
49560                             }
49561                             return results_1;
49562                         }
49563                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
49564                         return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
49565                     };
49566                 }
49567                 function serializePropertySymbolForInterface(p, baseType) {
49568                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
49569                 }
49570                 function serializeSignatures(kind, input, baseType, outputKind) {
49571                     var signatures = getSignaturesOfType(input, kind);
49572                     if (kind === 1 /* Construct */) {
49573                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
49574                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
49575                         }
49576                         if (baseType) {
49577                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
49578                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
49579                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
49580                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
49581                             }
49582                             if (baseSigs.length === signatures.length) {
49583                                 var failed = false;
49584                                 for (var i = 0; i < baseSigs.length; i++) {
49585                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
49586                                         failed = true;
49587                                         break;
49588                                     }
49589                                 }
49590                                 if (!failed) {
49591                                     return []; // Every signature was identical - elide constructor list as it is inherited
49592                                 }
49593                             }
49594                         }
49595                         var privateProtected = 0;
49596                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
49597                             var s = signatures_4[_i];
49598                             if (s.declaration) {
49599                                 privateProtected |= ts.getSelectedEffectiveModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
49600                             }
49601                         }
49602                         if (privateProtected) {
49603                             return [ts.setTextRange(ts.factory.createConstructorDeclaration(
49604                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), 
49605                                 /*parameters*/ [], 
49606                                 /*body*/ undefined), signatures[0].declaration)];
49607                         }
49608                     }
49609                     var results = [];
49610                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
49611                         var sig = signatures_5[_a];
49612                         // Each overload becomes a separate constructor declaration, in order
49613                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
49614                         results.push(ts.setTextRange(decl, sig.declaration));
49615                     }
49616                     return results;
49617                 }
49618                 function serializeIndexSignatures(input, baseType) {
49619                     var results = [];
49620                     for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
49621                         var type = _a[_i];
49622                         var info = getIndexInfoOfType(input, type);
49623                         if (info) {
49624                             if (baseType) {
49625                                 var baseInfo = getIndexInfoOfType(baseType, type);
49626                                 if (baseInfo) {
49627                                     if (isTypeIdenticalTo(info.type, baseInfo.type)) {
49628                                         continue; // elide identical index signatures
49629                                     }
49630                                 }
49631                             }
49632                             results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context, /*typeNode*/ undefined));
49633                         }
49634                     }
49635                     return results;
49636                 }
49637                 function serializeBaseType(t, staticType, rootName) {
49638                     var ref = trySerializeAsTypeReference(t, 111551 /* Value */);
49639                     if (ref) {
49640                         return ref;
49641                     }
49642                     var tempName = getUnusedName(rootName + "_base");
49643                     var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
49644                         ts.factory.createVariableDeclaration(tempName, /*exclamationToken*/ undefined, typeToTypeNodeHelper(staticType, context))
49645                     ], 2 /* Const */));
49646                     addResult(statement, 0 /* None */);
49647                     return ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier(tempName), /*typeArgs*/ undefined);
49648                 }
49649                 function trySerializeAsTypeReference(t, flags) {
49650                     var typeArgs;
49651                     var reference;
49652                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
49653                     // which we can't write out in a syntactically valid way as an expression
49654                     if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) {
49655                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
49656                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
49657                     }
49658                     else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) {
49659                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
49660                     }
49661                     if (reference) {
49662                         return ts.factory.createExpressionWithTypeArguments(reference, typeArgs);
49663                     }
49664                 }
49665                 function serializeImplementedType(t) {
49666                     var ref = trySerializeAsTypeReference(t, 788968 /* Type */);
49667                     if (ref) {
49668                         return ref;
49669                     }
49670                     if (t.symbol) {
49671                         return ts.factory.createExpressionWithTypeArguments(symbolToExpression(t.symbol, context, 788968 /* Type */), /*typeArgs*/ undefined);
49672                     }
49673                 }
49674                 function getUnusedName(input, symbol) {
49675                     var _a, _b;
49676                     var id = symbol ? getSymbolId(symbol) : undefined;
49677                     if (id) {
49678                         if (context.remappedSymbolNames.has(id)) {
49679                             return context.remappedSymbolNames.get(id);
49680                         }
49681                     }
49682                     if (symbol) {
49683                         input = getNameCandidateWorker(symbol, input);
49684                     }
49685                     var i = 0;
49686                     var original = input;
49687                     while ((_a = context.usedSymbolNames) === null || _a === void 0 ? void 0 : _a.has(input)) {
49688                         i++;
49689                         input = original + "_" + i;
49690                     }
49691                     (_b = context.usedSymbolNames) === null || _b === void 0 ? void 0 : _b.add(input);
49692                     if (id) {
49693                         context.remappedSymbolNames.set(id, input);
49694                     }
49695                     return input;
49696                 }
49697                 function getNameCandidateWorker(symbol, localName) {
49698                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
49699                         var flags = context.flags;
49700                         context.flags |= 16777216 /* InInitialEntityName */;
49701                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
49702                         context.flags = flags;
49703                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
49704                     }
49705                     if (localName === "default" /* Default */) {
49706                         localName = "_default";
49707                     }
49708                     else if (localName === "export=" /* ExportEquals */) {
49709                         localName = "_exports";
49710                     }
49711                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
49712                     return localName;
49713                 }
49714                 function getInternalSymbolName(symbol, localName) {
49715                     var id = getSymbolId(symbol);
49716                     if (context.remappedSymbolNames.has(id)) {
49717                         return context.remappedSymbolNames.get(id);
49718                     }
49719                     localName = getNameCandidateWorker(symbol, localName);
49720                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
49721                     context.remappedSymbolNames.set(id, localName);
49722                     return localName;
49723                 }
49724             }
49725         }
49726         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
49727             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
49728             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
49729             function typePredicateToStringWorker(writer) {
49730                 var predicate = ts.factory.createTypePredicateNode(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.factory.createToken(127 /* AssertsKeyword */) : undefined, typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.factory.createIdentifier(typePredicate.parameterName) : ts.factory.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217
49731                 );
49732                 var printer = ts.createPrinter({ removeComments: true });
49733                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
49734                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
49735                 return writer;
49736             }
49737         }
49738         function formatUnionTypes(types) {
49739             var result = [];
49740             var flags = 0;
49741             for (var i = 0; i < types.length; i++) {
49742                 var t = types[i];
49743                 flags |= t.flags;
49744                 if (!(t.flags & 98304 /* Nullable */)) {
49745                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
49746                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
49747                         if (baseType.flags & 1048576 /* Union */) {
49748                             var count = baseType.types.length;
49749                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
49750                                 result.push(baseType);
49751                                 i += count - 1;
49752                                 continue;
49753                             }
49754                         }
49755                     }
49756                     result.push(t);
49757                 }
49758             }
49759             if (flags & 65536 /* Null */)
49760                 result.push(nullType);
49761             if (flags & 32768 /* Undefined */)
49762                 result.push(undefinedType);
49763             return result || types;
49764         }
49765         function visibilityToString(flags) {
49766             if (flags === 8 /* Private */) {
49767                 return "private";
49768             }
49769             if (flags === 16 /* Protected */) {
49770                 return "protected";
49771             }
49772             return "public";
49773         }
49774         function getTypeAliasForTypeLiteral(type) {
49775             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
49776                 var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent);
49777                 if (node.kind === 254 /* TypeAliasDeclaration */) {
49778                     return getSymbolOfNode(node);
49779                 }
49780             }
49781             return undefined;
49782         }
49783         function isTopLevelInExternalModuleAugmentation(node) {
49784             return node && node.parent &&
49785                 node.parent.kind === 257 /* ModuleBlock */ &&
49786                 ts.isExternalModuleAugmentation(node.parent.parent);
49787         }
49788         function isDefaultBindingContext(location) {
49789             return location.kind === 297 /* SourceFile */ || ts.isAmbientModule(location);
49790         }
49791         function getNameOfSymbolFromNameType(symbol, context) {
49792             var nameType = getSymbolLinks(symbol).nameType;
49793             if (nameType) {
49794                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
49795                     var name = "" + nameType.value;
49796                     if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
49797                         return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
49798                     }
49799                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
49800                         return "[" + name + "]";
49801                     }
49802                     return name;
49803                 }
49804                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
49805                     return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
49806                 }
49807             }
49808         }
49809         /**
49810          * Gets a human-readable name for a symbol.
49811          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
49812          *
49813          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
49814          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
49815          */
49816         function getNameOfSymbolAsWritten(symbol, context) {
49817             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
49818                 // If it's not the first part of an entity name, it must print as `default`
49819                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
49820                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
49821                     !symbol.declarations ||
49822                     // if not in the same binding context (source file, module declaration), it must print as `default`
49823                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
49824                 return "default";
49825             }
49826             if (symbol.declarations && symbol.declarations.length) {
49827                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
49828                 var name_3 = declaration && ts.getNameOfDeclaration(declaration);
49829                 if (declaration && name_3) {
49830                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
49831                         return ts.symbolName(symbol);
49832                     }
49833                     if (ts.isComputedPropertyName(name_3) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
49834                         var nameType = getSymbolLinks(symbol).nameType;
49835                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
49836                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
49837                             var result = getNameOfSymbolFromNameType(symbol, context);
49838                             if (result !== undefined) {
49839                                 return result;
49840                             }
49841                         }
49842                     }
49843                     return ts.declarationNameToString(name_3);
49844                 }
49845                 if (!declaration) {
49846                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
49847                 }
49848                 if (declaration.parent && declaration.parent.kind === 249 /* VariableDeclaration */) {
49849                     return ts.declarationNameToString(declaration.parent.name);
49850                 }
49851                 switch (declaration.kind) {
49852                     case 221 /* ClassExpression */:
49853                     case 208 /* FunctionExpression */:
49854                     case 209 /* ArrowFunction */:
49855                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
49856                             context.encounteredError = true;
49857                         }
49858                         return declaration.kind === 221 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
49859                 }
49860             }
49861             var name = getNameOfSymbolFromNameType(symbol, context);
49862             return name !== undefined ? name : ts.symbolName(symbol);
49863         }
49864         function isDeclarationVisible(node) {
49865             if (node) {
49866                 var links = getNodeLinks(node);
49867                 if (links.isVisible === undefined) {
49868                     links.isVisible = !!determineIfDeclarationIsVisible();
49869                 }
49870                 return links.isVisible;
49871             }
49872             return false;
49873             function determineIfDeclarationIsVisible() {
49874                 switch (node.kind) {
49875                     case 324 /* JSDocCallbackTag */:
49876                     case 331 /* JSDocTypedefTag */:
49877                     case 325 /* JSDocEnumTag */:
49878                         // Top-level jsdoc type aliases are considered exported
49879                         // 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
49880                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
49881                     case 198 /* BindingElement */:
49882                         return isDeclarationVisible(node.parent.parent);
49883                     case 249 /* VariableDeclaration */:
49884                         if (ts.isBindingPattern(node.name) &&
49885                             !node.name.elements.length) {
49886                             // If the binding pattern is empty, this variable declaration is not visible
49887                             return false;
49888                         }
49889                     // falls through
49890                     case 256 /* ModuleDeclaration */:
49891                     case 252 /* ClassDeclaration */:
49892                     case 253 /* InterfaceDeclaration */:
49893                     case 254 /* TypeAliasDeclaration */:
49894                     case 251 /* FunctionDeclaration */:
49895                     case 255 /* EnumDeclaration */:
49896                     case 260 /* ImportEqualsDeclaration */:
49897                         // external module augmentation is always visible
49898                         if (ts.isExternalModuleAugmentation(node)) {
49899                             return true;
49900                         }
49901                         var parent = getDeclarationContainer(node);
49902                         // If the node is not exported or it is not ambient module element (except import declaration)
49903                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
49904                             !(node.kind !== 260 /* ImportEqualsDeclaration */ && parent.kind !== 297 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
49905                             return isGlobalSourceFile(parent);
49906                         }
49907                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
49908                         return isDeclarationVisible(parent);
49909                     case 163 /* PropertyDeclaration */:
49910                     case 162 /* PropertySignature */:
49911                     case 167 /* GetAccessor */:
49912                     case 168 /* SetAccessor */:
49913                     case 165 /* MethodDeclaration */:
49914                     case 164 /* MethodSignature */:
49915                         if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) {
49916                             // Private/protected properties/methods are not visible
49917                             return false;
49918                         }
49919                     // Public properties/methods are visible if its parents are visible, so:
49920                     // falls through
49921                     case 166 /* Constructor */:
49922                     case 170 /* ConstructSignature */:
49923                     case 169 /* CallSignature */:
49924                     case 171 /* IndexSignature */:
49925                     case 160 /* Parameter */:
49926                     case 257 /* ModuleBlock */:
49927                     case 174 /* FunctionType */:
49928                     case 175 /* ConstructorType */:
49929                     case 177 /* TypeLiteral */:
49930                     case 173 /* TypeReference */:
49931                     case 178 /* ArrayType */:
49932                     case 179 /* TupleType */:
49933                     case 182 /* UnionType */:
49934                     case 183 /* IntersectionType */:
49935                     case 186 /* ParenthesizedType */:
49936                     case 192 /* NamedTupleMember */:
49937                         return isDeclarationVisible(node.parent);
49938                     // Default binding, import specifier and namespace import is visible
49939                     // only on demand so by default it is not visible
49940                     case 262 /* ImportClause */:
49941                     case 263 /* NamespaceImport */:
49942                     case 265 /* ImportSpecifier */:
49943                         return false;
49944                     // Type parameters are always visible
49945                     case 159 /* TypeParameter */:
49946                     // Source file and namespace export are always visible
49947                     // falls through
49948                     case 297 /* SourceFile */:
49949                     case 259 /* NamespaceExportDeclaration */:
49950                         return true;
49951                     // Export assignments do not create name bindings outside the module
49952                     case 266 /* ExportAssignment */:
49953                         return false;
49954                     default:
49955                         return false;
49956                 }
49957             }
49958         }
49959         function collectLinkedAliases(node, setVisibility) {
49960             var exportSymbol;
49961             if (node.parent && node.parent.kind === 266 /* ExportAssignment */) {
49962                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
49963             }
49964             else if (node.parent.kind === 270 /* ExportSpecifier */) {
49965                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
49966             }
49967             var result;
49968             var visited;
49969             if (exportSymbol) {
49970                 visited = new ts.Set();
49971                 visited.add(getSymbolId(exportSymbol));
49972                 buildVisibleNodeList(exportSymbol.declarations);
49973             }
49974             return result;
49975             function buildVisibleNodeList(declarations) {
49976                 ts.forEach(declarations, function (declaration) {
49977                     var resultNode = getAnyImportSyntax(declaration) || declaration;
49978                     if (setVisibility) {
49979                         getNodeLinks(declaration).isVisible = true;
49980                     }
49981                     else {
49982                         result = result || [];
49983                         ts.pushIfUnique(result, resultNode);
49984                     }
49985                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
49986                         // Add the referenced top container visible
49987                         var internalModuleReference = declaration.moduleReference;
49988                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
49989                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
49990                         if (importSymbol && visited) {
49991                             if (ts.tryAddToSet(visited, getSymbolId(importSymbol))) {
49992                                 buildVisibleNodeList(importSymbol.declarations);
49993                             }
49994                         }
49995                     }
49996                 });
49997             }
49998         }
49999         /**
50000          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
50001          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
50002          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
50003          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
50004          * In order to see if the same query has already been done before, the target object and the propertyName both
50005          * must match the one passed in.
50006          *
50007          * @param target The symbol, type, or signature whose type is being queried
50008          * @param propertyName The property name that should be used to query the target for its type
50009          */
50010         function pushTypeResolution(target, propertyName) {
50011             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
50012             if (resolutionCycleStartIndex >= 0) {
50013                 // A cycle was found
50014                 var length_3 = resolutionTargets.length;
50015                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
50016                     resolutionResults[i] = false;
50017                 }
50018                 return false;
50019             }
50020             resolutionTargets.push(target);
50021             resolutionResults.push(/*items*/ true);
50022             resolutionPropertyNames.push(propertyName);
50023             return true;
50024         }
50025         function findResolutionCycleStartIndex(target, propertyName) {
50026             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
50027                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
50028                     return -1;
50029                 }
50030                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
50031                     return i;
50032                 }
50033             }
50034             return -1;
50035         }
50036         function hasType(target, propertyName) {
50037             switch (propertyName) {
50038                 case 0 /* Type */:
50039                     return !!getSymbolLinks(target).type;
50040                 case 5 /* EnumTagType */:
50041                     return !!(getNodeLinks(target).resolvedEnumType);
50042                 case 2 /* DeclaredType */:
50043                     return !!getSymbolLinks(target).declaredType;
50044                 case 1 /* ResolvedBaseConstructorType */:
50045                     return !!target.resolvedBaseConstructorType;
50046                 case 3 /* ResolvedReturnType */:
50047                     return !!target.resolvedReturnType;
50048                 case 4 /* ImmediateBaseConstraint */:
50049                     return !!target.immediateBaseConstraint;
50050                 case 6 /* ResolvedTypeArguments */:
50051                     return !!target.resolvedTypeArguments;
50052                 case 7 /* ResolvedBaseTypes */:
50053                     return !!target.baseTypesResolved;
50054             }
50055             return ts.Debug.assertNever(propertyName);
50056         }
50057         /**
50058          * Pop an entry from the type resolution stack and return its associated result value. The result value will
50059          * be true if no circularities were detected, or false if a circularity was found.
50060          */
50061         function popTypeResolution() {
50062             resolutionTargets.pop();
50063             resolutionPropertyNames.pop();
50064             return resolutionResults.pop();
50065         }
50066         function getDeclarationContainer(node) {
50067             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
50068                 switch (node.kind) {
50069                     case 249 /* VariableDeclaration */:
50070                     case 250 /* VariableDeclarationList */:
50071                     case 265 /* ImportSpecifier */:
50072                     case 264 /* NamedImports */:
50073                     case 263 /* NamespaceImport */:
50074                     case 262 /* ImportClause */:
50075                         return false;
50076                     default:
50077                         return true;
50078                 }
50079             }).parent;
50080         }
50081         function getTypeOfPrototypeProperty(prototype) {
50082             // TypeScript 1.0 spec (April 2014): 8.4
50083             // Every class automatically contains a static property member named 'prototype',
50084             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
50085             // It is an error to explicitly declare a static property member with the name 'prototype'.
50086             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
50087             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
50088         }
50089         // Return the type of the given property in the given type, or undefined if no such property exists
50090         function getTypeOfPropertyOfType(type, name) {
50091             var prop = getPropertyOfType(type, name);
50092             return prop ? getTypeOfSymbol(prop) : undefined;
50093         }
50094         function getTypeOfPropertyOrIndexSignature(type, name) {
50095             return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
50096         }
50097         function isTypeAny(type) {
50098             return type && (type.flags & 1 /* Any */) !== 0;
50099         }
50100         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
50101         // assigned by contextual typing.
50102         function getTypeForBindingElementParent(node) {
50103             var symbol = getSymbolOfNode(node);
50104             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
50105         }
50106         function getRestType(source, properties, symbol) {
50107             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
50108             if (source.flags & 131072 /* Never */) {
50109                 return emptyObjectType;
50110             }
50111             if (source.flags & 1048576 /* Union */) {
50112                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
50113             }
50114             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
50115             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
50116                 if (omitKeyType.flags & 131072 /* Never */) {
50117                     return source;
50118                 }
50119                 var omitTypeAlias = getGlobalOmitSymbol();
50120                 if (!omitTypeAlias) {
50121                     return errorType;
50122                 }
50123                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
50124             }
50125             var members = ts.createSymbolTable();
50126             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
50127                 var prop = _a[_i];
50128                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
50129                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
50130                     && isSpreadableProperty(prop)) {
50131                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
50132                 }
50133             }
50134             var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
50135             var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
50136             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
50137             result.objectFlags |= 131072 /* ObjectRestType */;
50138             return result;
50139         }
50140         // Determine the control flow type associated with a destructuring declaration or assignment. The following
50141         // forms of destructuring are possible:
50142         //   let { x } = obj;  // BindingElement
50143         //   let [ x ] = obj;  // BindingElement
50144         //   { x } = obj;      // ShorthandPropertyAssignment
50145         //   { x: v } = obj;   // PropertyAssignment
50146         //   [ x ] = obj;      // Expression
50147         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
50148         // flow analyzer doesn't have to handle all the different syntactic forms.
50149         function getFlowTypeOfDestructuring(node, declaredType) {
50150             var reference = getSyntheticElementAccess(node);
50151             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
50152         }
50153         function getSyntheticElementAccess(node) {
50154             var parentAccess = getParentElementAccess(node);
50155             if (parentAccess && parentAccess.flowNode) {
50156                 var propName = getDestructuringPropertyName(node);
50157                 if (propName) {
50158                     var literal = ts.setTextRange(ts.parseNodeFactory.createStringLiteral(propName), node);
50159                     var lhsExpr = ts.isLeftHandSideExpression(parentAccess) ? parentAccess : ts.parseNodeFactory.createParenthesizedExpression(parentAccess);
50160                     var result = ts.setTextRange(ts.parseNodeFactory.createElementAccessExpression(lhsExpr, literal), node);
50161                     ts.setParent(literal, result);
50162                     ts.setParent(result, node);
50163                     if (lhsExpr !== parentAccess) {
50164                         ts.setParent(lhsExpr, result);
50165                     }
50166                     result.flowNode = parentAccess.flowNode;
50167                     return result;
50168                 }
50169             }
50170         }
50171         function getParentElementAccess(node) {
50172             var ancestor = node.parent.parent;
50173             switch (ancestor.kind) {
50174                 case 198 /* BindingElement */:
50175                 case 288 /* PropertyAssignment */:
50176                     return getSyntheticElementAccess(ancestor);
50177                 case 199 /* ArrayLiteralExpression */:
50178                     return getSyntheticElementAccess(node.parent);
50179                 case 249 /* VariableDeclaration */:
50180                     return ancestor.initializer;
50181                 case 216 /* BinaryExpression */:
50182                     return ancestor.right;
50183             }
50184         }
50185         function getDestructuringPropertyName(node) {
50186             var parent = node.parent;
50187             if (node.kind === 198 /* BindingElement */ && parent.kind === 196 /* ObjectBindingPattern */) {
50188                 return getLiteralPropertyNameText(node.propertyName || node.name);
50189             }
50190             if (node.kind === 288 /* PropertyAssignment */ || node.kind === 289 /* ShorthandPropertyAssignment */) {
50191                 return getLiteralPropertyNameText(node.name);
50192             }
50193             return "" + parent.elements.indexOf(node);
50194         }
50195         function getLiteralPropertyNameText(name) {
50196             var type = getLiteralTypeFromPropertyName(name);
50197             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
50198         }
50199         /** Return the inferred type for a binding element */
50200         function getTypeForBindingElement(declaration) {
50201             var pattern = declaration.parent;
50202             var parentType = getTypeForBindingElementParent(pattern.parent);
50203             // If no type or an any type was inferred for parent, infer that for the binding element
50204             if (!parentType || isTypeAny(parentType)) {
50205                 return parentType;
50206             }
50207             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
50208             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
50209                 parentType = getNonNullableType(parentType);
50210             }
50211             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
50212             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
50213                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
50214             }
50215             var type;
50216             if (pattern.kind === 196 /* ObjectBindingPattern */) {
50217                 if (declaration.dotDotDotToken) {
50218                     parentType = getReducedType(parentType);
50219                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
50220                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
50221                         return errorType;
50222                     }
50223                     var literalMembers = [];
50224                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
50225                         var element = _a[_i];
50226                         if (!element.dotDotDotToken) {
50227                             literalMembers.push(element.propertyName || element.name);
50228                         }
50229                     }
50230                     type = getRestType(parentType, literalMembers, declaration.symbol);
50231                 }
50232                 else {
50233                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
50234                     var name = declaration.propertyName || declaration.name;
50235                     var indexType = getLiteralTypeFromPropertyName(name);
50236                     var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */), declaration.name);
50237                     type = getFlowTypeOfDestructuring(declaration, declaredType);
50238                 }
50239             }
50240             else {
50241                 // This elementType will be used if the specific property corresponding to this index is not
50242                 // present (aka the tuple element property). This call also checks that the parentType is in
50243                 // fact an iterable or array (depending on target language).
50244                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern);
50245                 var index_2 = pattern.elements.indexOf(declaration);
50246                 if (declaration.dotDotDotToken) {
50247                     // If the parent is a tuple type, the rest element has a tuple type of the
50248                     // remaining tuple element types. Otherwise, the rest element has an array type with same
50249                     // element type as the parent type.
50250                     type = everyType(parentType, isTupleType) ?
50251                         mapType(parentType, function (t) { return sliceTupleType(t, index_2); }) :
50252                         createArrayType(elementType);
50253                 }
50254                 else if (isArrayLikeType(parentType)) {
50255                     var indexType = getLiteralType(index_2);
50256                     var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
50257                     var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType, declaration.name);
50258                     type = getFlowTypeOfDestructuring(declaration, declaredType);
50259                 }
50260                 else {
50261                     type = elementType;
50262                 }
50263             }
50264             if (!declaration.initializer) {
50265                 return type;
50266             }
50267             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
50268                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
50269                 // undefined from the final type.
50270                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
50271                     getTypeWithFacts(type, 524288 /* NEUndefined */) :
50272                     type;
50273             }
50274             return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
50275         }
50276         function getTypeForDeclarationFromJSDocComment(declaration) {
50277             var jsdocType = ts.getJSDocType(declaration);
50278             if (jsdocType) {
50279                 return getTypeFromTypeNode(jsdocType);
50280             }
50281             return undefined;
50282         }
50283         function isNullOrUndefined(node) {
50284             var expr = ts.skipParentheses(node);
50285             return expr.kind === 103 /* NullKeyword */ || expr.kind === 78 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
50286         }
50287         function isEmptyArrayLiteral(node) {
50288             var expr = ts.skipParentheses(node);
50289             return expr.kind === 199 /* ArrayLiteralExpression */ && expr.elements.length === 0;
50290         }
50291         function addOptionality(type, optional) {
50292             if (optional === void 0) { optional = true; }
50293             return strictNullChecks && optional ? getOptionalType(type) : type;
50294         }
50295         // Return the inferred type for a variable, parameter, or property declaration
50296         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
50297             // A variable declared in a for..in statement is of type string, or of type keyof T when the
50298             // right hand expression is of a type parameter type.
50299             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 238 /* ForInStatement */) {
50300                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
50301                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
50302             }
50303             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) {
50304                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
50305                 // missing properties/signatures required to get its iteratedType (like
50306                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
50307                 // or it may have led to an error inside getElementTypeOfIterable.
50308                 var forOfStatement = declaration.parent.parent;
50309                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
50310             }
50311             if (ts.isBindingPattern(declaration.parent)) {
50312                 return getTypeForBindingElement(declaration);
50313             }
50314             var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
50315                 || isOptionalJSDocPropertyLikeTag(declaration)
50316                 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
50317             // Use type from type annotation if one is present
50318             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
50319             if (declaredType) {
50320                 return addOptionality(declaredType, isOptional);
50321             }
50322             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
50323                 ts.isVariableDeclaration(declaration) && !ts.isBindingPattern(declaration.name) &&
50324                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
50325                 // If --noImplicitAny is on or the declaration is in a Javascript file,
50326                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
50327                 // initializer or a 'null' or 'undefined' initializer.
50328                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
50329                     return autoType;
50330                 }
50331                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
50332                 // literal initializer.
50333                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
50334                     return autoArrayType;
50335                 }
50336             }
50337             if (ts.isParameter(declaration)) {
50338                 var func = declaration.parent;
50339                 // For a parameter of a set accessor, use the type of the get accessor if one is present
50340                 if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
50341                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */);
50342                     if (getter) {
50343                         var getterSignature = getSignatureFromDeclaration(getter);
50344                         var thisParameter = getAccessorThisParameter(func);
50345                         if (thisParameter && declaration === thisParameter) {
50346                             // Use the type from the *getter*
50347                             ts.Debug.assert(!thisParameter.type);
50348                             return getTypeOfSymbol(getterSignature.thisParameter);
50349                         }
50350                         return getReturnTypeOfSignature(getterSignature);
50351                     }
50352                 }
50353                 if (ts.isInJSFile(declaration)) {
50354                     var typeTag = ts.getJSDocType(func);
50355                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
50356                         var signature = getSignatureFromDeclaration(typeTag);
50357                         var pos = func.parameters.indexOf(declaration);
50358                         return declaration.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
50359                     }
50360                 }
50361                 // Use contextual parameter type if one is available
50362                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
50363                 if (type) {
50364                     return addOptionality(type, isOptional);
50365                 }
50366             }
50367             // Use the type of the initializer expression if one is present and the declaration is
50368             // not a parameter of a contextually typed function
50369             if (ts.hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) {
50370                 if (ts.isInJSFile(declaration) && !ts.isParameter(declaration)) {
50371                     var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
50372                     if (containerObjectType) {
50373                         return containerObjectType;
50374                     }
50375                 }
50376                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
50377                 return addOptionality(type, isOptional);
50378             }
50379             if (ts.isPropertyDeclaration(declaration) && !ts.hasStaticModifier(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) {
50380                 // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file.
50381                 // Use control flow analysis of this.xxx assignments in the constructor to determine the type of the property.
50382                 var constructor = findConstructorDeclaration(declaration.parent);
50383                 var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) :
50384                     ts.getEffectiveModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) :
50385                         undefined;
50386                 return type && addOptionality(type, isOptional);
50387             }
50388             if (ts.isJsxAttribute(declaration)) {
50389                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
50390                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
50391                 return trueType;
50392             }
50393             // If the declaration specifies a binding pattern and is not a parameter of a contextually
50394             // typed function, use the type implied by the binding pattern
50395             if (ts.isBindingPattern(declaration.name)) {
50396                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
50397             }
50398             // No type specified and nothing can be inferred
50399             return undefined;
50400         }
50401         function isConstructorDeclaredProperty(symbol) {
50402             // A property is considered a constructor declared property when all declaration sites are this.xxx assignments,
50403             // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of
50404             // a class constructor.
50405             if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) {
50406                 var links = getSymbolLinks(symbol);
50407                 if (links.isConstructorDeclaredProperty === undefined) {
50408                     links.isConstructorDeclaredProperty = false;
50409                     links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) {
50410                         return ts.isBinaryExpression(declaration) &&
50411                             isPossiblyAliasedThisProperty(declaration) &&
50412                             (declaration.left.kind !== 202 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) &&
50413                             !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration);
50414                     });
50415                 }
50416                 return links.isConstructorDeclaredProperty;
50417             }
50418             return false;
50419         }
50420         function isAutoTypedProperty(symbol) {
50421             // A property is auto-typed when its declaration has no type annotation or initializer and we're in
50422             // noImplicitAny mode or a .js file.
50423             var declaration = symbol.valueDeclaration;
50424             return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) &&
50425                 !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration));
50426         }
50427         function getDeclaringConstructor(symbol) {
50428             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50429                 var declaration = _a[_i];
50430                 var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false);
50431                 if (container && (container.kind === 166 /* Constructor */ || isJSConstructor(container))) {
50432                     return container;
50433                 }
50434             }
50435         }
50436         function getFlowTypeInConstructor(symbol, constructor) {
50437             var accessName = ts.startsWith(symbol.escapedName, "__#")
50438                 ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1])
50439                 : ts.unescapeLeadingUnderscores(symbol.escapedName);
50440             var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), accessName);
50441             ts.setParent(reference.expression, reference);
50442             ts.setParent(reference, constructor);
50443             reference.flowNode = constructor.returnFlowNode;
50444             var flowType = getFlowTypeOfProperty(reference, symbol);
50445             if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
50446                 error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
50447             }
50448             // We don't infer a type if assignments are only null or undefined.
50449             return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType);
50450         }
50451         function getFlowTypeOfProperty(reference, prop) {
50452             var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType;
50453             return getFlowTypeOfReference(reference, autoType, initialType);
50454         }
50455         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
50456             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
50457             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
50458             if (container) {
50459                 var tag = ts.getJSDocTypeTag(container);
50460                 if (tag && tag.typeExpression) {
50461                     return getTypeFromTypeNode(tag.typeExpression);
50462                 }
50463                 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
50464                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
50465             }
50466             var type;
50467             var definedInConstructor = false;
50468             var definedInMethod = false;
50469             // We use control flow analysis to determine the type of the property if the property qualifies as a constructor
50470             // declared property and the resulting control flow type isn't just undefined or null.
50471             if (isConstructorDeclaredProperty(symbol)) {
50472                 type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol));
50473             }
50474             if (!type) {
50475                 var jsdocType = void 0;
50476                 var types = void 0;
50477                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50478                     var declaration = _a[_i];
50479                     var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
50480                         ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
50481                             undefined;
50482                     if (!expression) {
50483                         continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere
50484                     }
50485                     var kind = ts.isAccessExpression(expression)
50486                         ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
50487                         : ts.getAssignmentDeclarationKind(expression);
50488                     if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) {
50489                         if (isDeclarationInConstructor(expression)) {
50490                             definedInConstructor = true;
50491                         }
50492                         else {
50493                             definedInMethod = true;
50494                         }
50495                     }
50496                     if (!ts.isCallExpression(expression)) {
50497                         jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
50498                     }
50499                     if (!jsdocType) {
50500                         (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
50501                     }
50502                 }
50503                 type = jsdocType;
50504                 if (!type) {
50505                     if (!ts.length(types)) {
50506                         return errorType; // No types from any declarations :(
50507                     }
50508                     var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
50509                     // use only the constructor types unless they were only assigned null | undefined (including widening variants)
50510                     if (definedInMethod) {
50511                         var propType = getTypeOfPropertyInBaseClass(symbol);
50512                         if (propType) {
50513                             (constructorTypes || (constructorTypes = [])).push(propType);
50514                             definedInConstructor = true;
50515                         }
50516                     }
50517                     var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
50518                     type = getUnionType(sourceTypes, 2 /* Subtype */);
50519                 }
50520             }
50521             var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
50522             if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
50523                 reportImplicitAny(symbol.valueDeclaration, anyType);
50524                 return anyType;
50525             }
50526             return widened;
50527         }
50528         function getJSContainerObjectType(decl, symbol, init) {
50529             var _a, _b;
50530             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
50531                 return undefined;
50532             }
50533             var exports = ts.createSymbolTable();
50534             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
50535                 var s_2 = getSymbolOfNode(decl);
50536                 if ((_a = s_2 === null || s_2 === void 0 ? void 0 : s_2.exports) === null || _a === void 0 ? void 0 : _a.size) {
50537                     mergeSymbolTable(exports, s_2.exports);
50538                 }
50539                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
50540             }
50541             var s = getSymbolOfNode(decl);
50542             if ((_b = s === null || s === void 0 ? void 0 : s.exports) === null || _b === void 0 ? void 0 : _b.size) {
50543                 mergeSymbolTable(exports, s.exports);
50544             }
50545             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
50546             type.objectFlags |= 16384 /* JSLiteral */;
50547             return type;
50548         }
50549         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
50550             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
50551             if (typeNode) {
50552                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
50553                 if (!declaredType) {
50554                     return type;
50555                 }
50556                 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
50557                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
50558                 }
50559             }
50560             if (symbol.parent) {
50561                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
50562                 if (typeNode_2) {
50563                     return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
50564                 }
50565             }
50566             return declaredType;
50567         }
50568         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
50569         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
50570             if (ts.isCallExpression(expression)) {
50571                 if (resolvedSymbol) {
50572                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
50573                 }
50574                 var objectLitType = checkExpressionCached(expression.arguments[2]);
50575                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
50576                 if (valueType) {
50577                     return valueType;
50578                 }
50579                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
50580                 if (getFunc) {
50581                     var getSig = getSingleCallSignature(getFunc);
50582                     if (getSig) {
50583                         return getReturnTypeOfSignature(getSig);
50584                     }
50585                 }
50586                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
50587                 if (setFunc) {
50588                     var setSig = getSingleCallSignature(setFunc);
50589                     if (setSig) {
50590                         return getTypeOfFirstParameterOfSignature(setSig);
50591                     }
50592                 }
50593                 return anyType;
50594             }
50595             if (containsSameNamedThisProperty(expression.left, expression.right)) {
50596                 return anyType;
50597             }
50598             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
50599             if (type.flags & 524288 /* Object */ &&
50600                 kind === 2 /* ModuleExports */ &&
50601                 symbol.escapedName === "export=" /* ExportEquals */) {
50602                 var exportedType = resolveStructuredTypeMembers(type);
50603                 var members_4 = ts.createSymbolTable();
50604                 ts.copyEntries(exportedType.members, members_4);
50605                 var initialSize = members_4.size;
50606                 if (resolvedSymbol && !resolvedSymbol.exports) {
50607                     resolvedSymbol.exports = ts.createSymbolTable();
50608                 }
50609                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
50610                     var _a;
50611                     var exportedMember = members_4.get(name);
50612                     if (exportedMember && exportedMember !== s) {
50613                         if (s.flags & 111551 /* Value */ && exportedMember.flags & 111551 /* Value */) {
50614                             // If the member has an additional value-like declaration, union the types from the two declarations,
50615                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
50616                             // a pattern like:
50617                             //
50618                             // module.exports = { a: true };
50619                             // module.exports.a = 3;
50620                             //
50621                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
50622                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
50623                             // it's unclear what that's supposed to mean, so it's probably a mistake.
50624                             if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
50625                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
50626                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
50627                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
50628                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
50629                             }
50630                             var union = createSymbol(s.flags | exportedMember.flags, name);
50631                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
50632                             union.valueDeclaration = exportedMember.valueDeclaration;
50633                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
50634                             members_4.set(name, union);
50635                         }
50636                         else {
50637                             members_4.set(name, mergeSymbol(s, exportedMember));
50638                         }
50639                     }
50640                     else {
50641                         members_4.set(name, s);
50642                     }
50643                 });
50644                 var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type
50645                 members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
50646                 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
50647                 if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) {
50648                     result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type
50649                 }
50650                 return result;
50651             }
50652             if (isEmptyArrayLiteralType(type)) {
50653                 reportImplicitAny(expression, anyArrayType);
50654                 return anyArrayType;
50655             }
50656             return type;
50657         }
50658         function containsSameNamedThisProperty(thisProperty, expression) {
50659             return ts.isPropertyAccessExpression(thisProperty)
50660                 && thisProperty.expression.kind === 107 /* ThisKeyword */
50661                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
50662         }
50663         function isDeclarationInConstructor(expression) {
50664             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
50665             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
50666             // Function expressions that are assigned to the prototype count as methods.
50667             return thisContainer.kind === 166 /* Constructor */ ||
50668                 thisContainer.kind === 251 /* FunctionDeclaration */ ||
50669                 (thisContainer.kind === 208 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
50670         }
50671         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
50672             ts.Debug.assert(types.length === declarations.length);
50673             return types.filter(function (_, i) {
50674                 var declaration = declarations[i];
50675                 var expression = ts.isBinaryExpression(declaration) ? declaration :
50676                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
50677                 return expression && isDeclarationInConstructor(expression);
50678             });
50679         }
50680         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
50681         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
50682         // pattern. Otherwise, it is the type any.
50683         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
50684             if (element.initializer) {
50685                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
50686                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
50687                 // pattern.
50688                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
50689                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
50690             }
50691             if (ts.isBindingPattern(element.name)) {
50692                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
50693             }
50694             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
50695                 reportImplicitAny(element, anyType);
50696             }
50697             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
50698             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
50699             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
50700             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
50701             return includePatternInType ? nonInferrableAnyType : anyType;
50702         }
50703         // Return the type implied by an object binding pattern
50704         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
50705             var members = ts.createSymbolTable();
50706             var stringIndexInfo;
50707             var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
50708             ts.forEach(pattern.elements, function (e) {
50709                 var name = e.propertyName || e.name;
50710                 if (e.dotDotDotToken) {
50711                     stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
50712                     return;
50713                 }
50714                 var exprType = getLiteralTypeFromPropertyName(name);
50715                 if (!isTypeUsableAsPropertyName(exprType)) {
50716                     // do not include computed properties in the implied type
50717                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
50718                     return;
50719                 }
50720                 var text = getPropertyNameFromType(exprType);
50721                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
50722                 var symbol = createSymbol(flags, text);
50723                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
50724                 symbol.bindingElement = e;
50725                 members.set(symbol.escapedName, symbol);
50726             });
50727             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
50728             result.objectFlags |= objectFlags;
50729             if (includePatternInType) {
50730                 result.pattern = pattern;
50731                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
50732             }
50733             return result;
50734         }
50735         // Return the type implied by an array binding pattern
50736         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
50737             var elements = pattern.elements;
50738             var lastElement = ts.lastOrUndefined(elements);
50739             var restElement = lastElement && lastElement.kind === 198 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined;
50740             if (elements.length === 0 || elements.length === 1 && restElement) {
50741                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
50742             }
50743             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
50744             var minLength = ts.findLastIndex(elements, function (e) { return !(e === restElement || ts.isOmittedExpression(e) || hasDefaultValue(e)); }, elements.length - 1) + 1;
50745             var elementFlags = ts.map(elements, function (e, i) { return e === restElement ? 4 /* Rest */ : i >= minLength ? 2 /* Optional */ : 1 /* Required */; });
50746             var result = createTupleType(elementTypes, elementFlags);
50747             if (includePatternInType) {
50748                 result = cloneTypeReference(result);
50749                 result.pattern = pattern;
50750                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
50751             }
50752             return result;
50753         }
50754         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
50755         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
50756         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
50757         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
50758         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
50759         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
50760         // the parameter.
50761         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
50762             if (includePatternInType === void 0) { includePatternInType = false; }
50763             if (reportErrors === void 0) { reportErrors = false; }
50764             return pattern.kind === 196 /* ObjectBindingPattern */
50765                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
50766                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
50767         }
50768         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
50769         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
50770         // is a bit more involved. For example:
50771         //
50772         //   var [x, s = ""] = [1, "one"];
50773         //
50774         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
50775         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
50776         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
50777         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
50778             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
50779         }
50780         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
50781             if (type) {
50782                 if (reportErrors) {
50783                     reportErrorsFromWidening(declaration, type);
50784                 }
50785                 // always widen a 'unique symbol' type if the type was created for a different declaration.
50786                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
50787                     type = esSymbolType;
50788                 }
50789                 return getWidenedType(type);
50790             }
50791             // Rest parameters default to type any[], other parameters default to type any
50792             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
50793             // Report implicit any errors unless this is a private property within an ambient declaration
50794             if (reportErrors) {
50795                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
50796                     reportImplicitAny(declaration, type);
50797                 }
50798             }
50799             return type;
50800         }
50801         function declarationBelongsToPrivateAmbientMember(declaration) {
50802             var root = ts.getRootDeclaration(declaration);
50803             var memberDeclaration = root.kind === 160 /* Parameter */ ? root.parent : root;
50804             return isPrivateWithinAmbient(memberDeclaration);
50805         }
50806         function tryGetTypeFromEffectiveTypeNode(declaration) {
50807             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
50808             if (typeNode) {
50809                 return getTypeFromTypeNode(typeNode);
50810             }
50811         }
50812         function getTypeOfVariableOrParameterOrProperty(symbol) {
50813             var links = getSymbolLinks(symbol);
50814             if (!links.type) {
50815                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
50816                 // For a contextually typed parameter it is possible that a type has already
50817                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
50818                 // to preserve this type.
50819                 if (!links.type) {
50820                     links.type = type;
50821                 }
50822             }
50823             return links.type;
50824         }
50825         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
50826             // Handle prototype property
50827             if (symbol.flags & 4194304 /* Prototype */) {
50828                 return getTypeOfPrototypeProperty(symbol);
50829             }
50830             // CommonsJS require and module both have type any.
50831             if (symbol === requireSymbol) {
50832                 return anyType;
50833             }
50834             if (symbol.flags & 134217728 /* ModuleExports */) {
50835                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
50836                 var members = ts.createSymbolTable();
50837                 members.set("exports", fileSymbol);
50838                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
50839             }
50840             // Handle catch clause variables
50841             var declaration = symbol.valueDeclaration;
50842             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
50843                 var decl = declaration;
50844                 if (!decl.type)
50845                     return anyType;
50846                 var type_1 = getTypeOfNode(decl.type);
50847                 // an errorType will make `checkTryStatement` issue an error
50848                 return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType;
50849             }
50850             // Handle export default expressions
50851             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
50852                 if (!declaration.statements.length) {
50853                     return emptyObjectType;
50854                 }
50855                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
50856             }
50857             // Handle variable, parameter or property
50858             if (!pushTypeResolution(symbol, 0 /* Type */)) {
50859                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
50860                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
50861                     return getTypeOfFuncClassEnumModule(symbol);
50862                 }
50863                 return reportCircularityError(symbol);
50864             }
50865             var type;
50866             if (declaration.kind === 266 /* ExportAssignment */) {
50867                 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
50868             }
50869             else if (ts.isBinaryExpression(declaration) ||
50870                 (ts.isInJSFile(declaration) &&
50871                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
50872                 type = getWidenedTypeForAssignmentDeclaration(symbol);
50873             }
50874             else if (ts.isPropertyAccessExpression(declaration)
50875                 || ts.isElementAccessExpression(declaration)
50876                 || ts.isIdentifier(declaration)
50877                 || ts.isStringLiteralLike(declaration)
50878                 || ts.isNumericLiteral(declaration)
50879                 || ts.isClassDeclaration(declaration)
50880                 || ts.isFunctionDeclaration(declaration)
50881                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
50882                 || ts.isMethodSignature(declaration)
50883                 || ts.isSourceFile(declaration)) {
50884                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
50885                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
50886                     return getTypeOfFuncClassEnumModule(symbol);
50887                 }
50888                 type = ts.isBinaryExpression(declaration.parent) ?
50889                     getWidenedTypeForAssignmentDeclaration(symbol) :
50890                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
50891             }
50892             else if (ts.isPropertyAssignment(declaration)) {
50893                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
50894             }
50895             else if (ts.isJsxAttribute(declaration)) {
50896                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
50897             }
50898             else if (ts.isShorthandPropertyAssignment(declaration)) {
50899                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
50900             }
50901             else if (ts.isObjectLiteralMethod(declaration)) {
50902                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
50903             }
50904             else if (ts.isParameter(declaration)
50905                 || ts.isPropertyDeclaration(declaration)
50906                 || ts.isPropertySignature(declaration)
50907                 || ts.isVariableDeclaration(declaration)
50908                 || ts.isBindingElement(declaration)
50909                 || ts.isJSDocPropertyLikeTag(declaration)) {
50910                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
50911             }
50912             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
50913             // Re-dispatch based on valueDeclaration.kind instead.
50914             else if (ts.isEnumDeclaration(declaration)) {
50915                 type = getTypeOfFuncClassEnumModule(symbol);
50916             }
50917             else if (ts.isEnumMember(declaration)) {
50918                 type = getTypeOfEnumMember(symbol);
50919             }
50920             else if (ts.isAccessor(declaration)) {
50921                 type = resolveTypeOfAccessors(symbol);
50922             }
50923             else {
50924                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
50925             }
50926             if (!popTypeResolution()) {
50927                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
50928                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
50929                     return getTypeOfFuncClassEnumModule(symbol);
50930                 }
50931                 return reportCircularityError(symbol);
50932             }
50933             return type;
50934         }
50935         function getAnnotatedAccessorTypeNode(accessor) {
50936             if (accessor) {
50937                 if (accessor.kind === 167 /* GetAccessor */) {
50938                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
50939                     return getterTypeAnnotation;
50940                 }
50941                 else {
50942                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
50943                     return setterTypeAnnotation;
50944                 }
50945             }
50946             return undefined;
50947         }
50948         function getAnnotatedAccessorType(accessor) {
50949             var node = getAnnotatedAccessorTypeNode(accessor);
50950             return node && getTypeFromTypeNode(node);
50951         }
50952         function getAnnotatedAccessorThisParameter(accessor) {
50953             var parameter = getAccessorThisParameter(accessor);
50954             return parameter && parameter.symbol;
50955         }
50956         function getThisTypeOfDeclaration(declaration) {
50957             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
50958         }
50959         function getTypeOfAccessors(symbol) {
50960             var links = getSymbolLinks(symbol);
50961             return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
50962         }
50963         function getTypeOfAccessorsWorker(symbol) {
50964             if (!pushTypeResolution(symbol, 0 /* Type */)) {
50965                 return errorType;
50966             }
50967             var type = resolveTypeOfAccessors(symbol);
50968             if (!popTypeResolution()) {
50969                 type = anyType;
50970                 if (noImplicitAny) {
50971                     var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */);
50972                     error(getter, 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));
50973                 }
50974             }
50975             return type;
50976         }
50977         function resolveTypeOfAccessors(symbol) {
50978             var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */);
50979             var setter = ts.getDeclarationOfKind(symbol, 168 /* SetAccessor */);
50980             if (getter && ts.isInJSFile(getter)) {
50981                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
50982                 if (jsDocType) {
50983                     return jsDocType;
50984                 }
50985             }
50986             // First try to see if the user specified a return type on the get-accessor.
50987             var getterReturnType = getAnnotatedAccessorType(getter);
50988             if (getterReturnType) {
50989                 return getterReturnType;
50990             }
50991             else {
50992                 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
50993                 var setterParameterType = getAnnotatedAccessorType(setter);
50994                 if (setterParameterType) {
50995                     return setterParameterType;
50996                 }
50997                 else {
50998                     // If there are no specified types, try to infer it from the body of the get accessor if it exists.
50999                     if (getter && getter.body) {
51000                         return getReturnTypeFromBody(getter);
51001                     }
51002                     // Otherwise, fall back to 'any'.
51003                     else {
51004                         if (setter) {
51005                             if (!isPrivateWithinAmbient(setter)) {
51006                                 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
51007                             }
51008                         }
51009                         else {
51010                             ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
51011                             if (!isPrivateWithinAmbient(getter)) {
51012                                 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
51013                             }
51014                         }
51015                         return anyType;
51016                     }
51017                 }
51018             }
51019         }
51020         function getBaseTypeVariableOfClass(symbol) {
51021             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
51022             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
51023                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
51024                     undefined;
51025         }
51026         function getTypeOfFuncClassEnumModule(symbol) {
51027             var links = getSymbolLinks(symbol);
51028             var originalLinks = links;
51029             if (!links.type) {
51030                 var expando = symbol.valueDeclaration && getSymbolOfExpando(symbol.valueDeclaration, /*allowDeclaration*/ false);
51031                 if (expando) {
51032                     var merged = mergeJSSymbols(symbol, expando);
51033                     if (merged) {
51034                         // note:we overwrite links because we just cloned the symbol
51035                         symbol = links = merged;
51036                     }
51037                 }
51038                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
51039             }
51040             return links.type;
51041         }
51042         function getTypeOfFuncClassEnumModuleWorker(symbol) {
51043             var declaration = symbol.valueDeclaration;
51044             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
51045                 return anyType;
51046             }
51047             else if (declaration && (declaration.kind === 216 /* BinaryExpression */ ||
51048                 ts.isAccessExpression(declaration) &&
51049                     declaration.parent.kind === 216 /* BinaryExpression */)) {
51050                 return getWidenedTypeForAssignmentDeclaration(symbol);
51051             }
51052             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
51053                 var resolvedModule = resolveExternalModuleSymbol(symbol);
51054                 if (resolvedModule !== symbol) {
51055                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
51056                         return errorType;
51057                     }
51058                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
51059                     var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
51060                     if (!popTypeResolution()) {
51061                         return reportCircularityError(symbol);
51062                     }
51063                     return type_2;
51064                 }
51065             }
51066             var type = createObjectType(16 /* Anonymous */, symbol);
51067             if (symbol.flags & 32 /* Class */) {
51068                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
51069                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
51070             }
51071             else {
51072                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
51073             }
51074         }
51075         function getTypeOfEnumMember(symbol) {
51076             var links = getSymbolLinks(symbol);
51077             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
51078         }
51079         function getTypeOfAlias(symbol) {
51080             var links = getSymbolLinks(symbol);
51081             if (!links.type) {
51082                 var targetSymbol = resolveAlias(symbol);
51083                 // It only makes sense to get the type of a value symbol. If the result of resolving
51084                 // the alias is not a value, then it has no type. To get the type associated with a
51085                 // type symbol, call getDeclaredTypeOfSymbol.
51086                 // This check is important because without it, a call to getTypeOfSymbol could end
51087                 // up recursively calling getTypeOfAlias, causing a stack overflow.
51088                 links.type = targetSymbol.flags & 111551 /* Value */
51089                     ? getTypeOfSymbol(targetSymbol)
51090                     : errorType;
51091             }
51092             return links.type;
51093         }
51094         function getTypeOfInstantiatedSymbol(symbol) {
51095             var links = getSymbolLinks(symbol);
51096             if (!links.type) {
51097                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
51098                     return links.type = errorType;
51099                 }
51100                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
51101                 if (!popTypeResolution()) {
51102                     type = reportCircularityError(symbol);
51103                 }
51104                 links.type = type;
51105             }
51106             return links.type;
51107         }
51108         function reportCircularityError(symbol) {
51109             var declaration = symbol.valueDeclaration;
51110             // Check if variable has type annotation that circularly references the variable itself
51111             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
51112                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
51113                 return errorType;
51114             }
51115             // Check if variable has initializer that circularly references the variable itself
51116             if (noImplicitAny && (declaration.kind !== 160 /* Parameter */ || declaration.initializer)) {
51117                 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));
51118             }
51119             // Circularities could also result from parameters in function expressions that end up
51120             // having themselves as contextual types following type argument inference. In those cases
51121             // we have already reported an implicit any error so we don't report anything here.
51122             return anyType;
51123         }
51124         function getTypeOfSymbolWithDeferredType(symbol) {
51125             var links = getSymbolLinks(symbol);
51126             if (!links.type) {
51127                 ts.Debug.assertIsDefined(links.deferralParent);
51128                 ts.Debug.assertIsDefined(links.deferralConstituents);
51129                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
51130             }
51131             return links.type;
51132         }
51133         function getTypeOfSymbol(symbol) {
51134             var checkFlags = ts.getCheckFlags(symbol);
51135             if (checkFlags & 65536 /* DeferredType */) {
51136                 return getTypeOfSymbolWithDeferredType(symbol);
51137             }
51138             if (checkFlags & 1 /* Instantiated */) {
51139                 return getTypeOfInstantiatedSymbol(symbol);
51140             }
51141             if (checkFlags & 262144 /* Mapped */) {
51142                 return getTypeOfMappedSymbol(symbol);
51143             }
51144             if (checkFlags & 8192 /* ReverseMapped */) {
51145                 return getTypeOfReverseMappedSymbol(symbol);
51146             }
51147             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
51148                 return getTypeOfVariableOrParameterOrProperty(symbol);
51149             }
51150             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
51151                 return getTypeOfFuncClassEnumModule(symbol);
51152             }
51153             if (symbol.flags & 8 /* EnumMember */) {
51154                 return getTypeOfEnumMember(symbol);
51155             }
51156             if (symbol.flags & 98304 /* Accessor */) {
51157                 return getTypeOfAccessors(symbol);
51158             }
51159             if (symbol.flags & 2097152 /* Alias */) {
51160                 return getTypeOfAlias(symbol);
51161             }
51162             return errorType;
51163         }
51164         function isReferenceToType(type, target) {
51165             return type !== undefined
51166                 && target !== undefined
51167                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
51168                 && type.target === target;
51169         }
51170         function getTargetType(type) {
51171             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
51172         }
51173         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
51174         function hasBaseType(type, checkBase) {
51175             return check(type);
51176             function check(type) {
51177                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
51178                     var target = getTargetType(type);
51179                     return target === checkBase || ts.some(getBaseTypes(target), check);
51180                 }
51181                 else if (type.flags & 2097152 /* Intersection */) {
51182                     return ts.some(type.types, check);
51183                 }
51184                 return false;
51185             }
51186         }
51187         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
51188         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
51189         // in-place and returns the same array.
51190         function appendTypeParameters(typeParameters, declarations) {
51191             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
51192                 var declaration = declarations_2[_i];
51193                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
51194             }
51195             return typeParameters;
51196         }
51197         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
51198         function getOuterTypeParameters(node, includeThisTypes) {
51199             while (true) {
51200                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
51201                 if (node && ts.isBinaryExpression(node)) {
51202                     // prototype assignments get the outer type parameters of their constructor function
51203                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
51204                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
51205                         var symbol = getSymbolOfNode(node.left);
51206                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
51207                             node = symbol.parent.valueDeclaration;
51208                         }
51209                     }
51210                 }
51211                 if (!node) {
51212                     return undefined;
51213                 }
51214                 switch (node.kind) {
51215                     case 232 /* VariableStatement */:
51216                     case 252 /* ClassDeclaration */:
51217                     case 221 /* ClassExpression */:
51218                     case 253 /* InterfaceDeclaration */:
51219                     case 169 /* CallSignature */:
51220                     case 170 /* ConstructSignature */:
51221                     case 164 /* MethodSignature */:
51222                     case 174 /* FunctionType */:
51223                     case 175 /* ConstructorType */:
51224                     case 308 /* JSDocFunctionType */:
51225                     case 251 /* FunctionDeclaration */:
51226                     case 165 /* MethodDeclaration */:
51227                     case 208 /* FunctionExpression */:
51228                     case 209 /* ArrowFunction */:
51229                     case 254 /* TypeAliasDeclaration */:
51230                     case 330 /* JSDocTemplateTag */:
51231                     case 331 /* JSDocTypedefTag */:
51232                     case 325 /* JSDocEnumTag */:
51233                     case 324 /* JSDocCallbackTag */:
51234                     case 190 /* MappedType */:
51235                     case 184 /* ConditionalType */:
51236                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
51237                         if (node.kind === 190 /* MappedType */) {
51238                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
51239                         }
51240                         else if (node.kind === 184 /* ConditionalType */) {
51241                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
51242                         }
51243                         else if (node.kind === 232 /* VariableStatement */ && !ts.isInJSFile(node)) {
51244                             break;
51245                         }
51246                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
51247                         var thisType = includeThisTypes &&
51248                             (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */ || node.kind === 253 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
51249                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
51250                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
51251                     case 326 /* JSDocParameterTag */:
51252                         var paramSymbol = ts.getParameterSymbolFromJSDoc(node);
51253                         if (paramSymbol) {
51254                             node = paramSymbol.valueDeclaration;
51255                         }
51256                         break;
51257                 }
51258             }
51259         }
51260         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
51261         function getOuterTypeParametersOfClassOrInterface(symbol) {
51262             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */);
51263             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
51264             return getOuterTypeParameters(declaration);
51265         }
51266         // The local type parameters are the combined set of type parameters from all declarations of the class,
51267         // interface, or type alias.
51268         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
51269             var result;
51270             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51271                 var node = _a[_i];
51272                 if (node.kind === 253 /* InterfaceDeclaration */ ||
51273                     node.kind === 252 /* ClassDeclaration */ ||
51274                     node.kind === 221 /* ClassExpression */ ||
51275                     isJSConstructor(node) ||
51276                     ts.isTypeAlias(node)) {
51277                     var declaration = node;
51278                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
51279                 }
51280             }
51281             return result;
51282         }
51283         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
51284         // its locally declared type parameters.
51285         function getTypeParametersOfClassOrInterface(symbol) {
51286             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
51287         }
51288         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
51289         // rest parameter of type any[].
51290         function isMixinConstructorType(type) {
51291             var signatures = getSignaturesOfType(type, 1 /* Construct */);
51292             if (signatures.length === 1) {
51293                 var s = signatures[0];
51294                 return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
51295             }
51296             return false;
51297         }
51298         function isConstructorType(type) {
51299             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
51300                 return true;
51301             }
51302             if (type.flags & 8650752 /* TypeVariable */) {
51303                 var constraint = getBaseConstraintOfType(type);
51304                 return !!constraint && isMixinConstructorType(constraint);
51305             }
51306             return false;
51307         }
51308         function getBaseTypeNodeOfClass(type) {
51309             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
51310         }
51311         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
51312             var typeArgCount = ts.length(typeArgumentNodes);
51313             var isJavascript = ts.isInJSFile(location);
51314             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
51315         }
51316         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
51317             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
51318             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
51319             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
51320         }
51321         /**
51322          * The base constructor of a class can resolve to
51323          * * undefinedType if the class has no extends clause,
51324          * * unknownType if an error occurred during resolution of the extends expression,
51325          * * nullType if the extends expression is the null value,
51326          * * anyType if the extends expression has type any, or
51327          * * an object type with at least one construct signature.
51328          */
51329         function getBaseConstructorTypeOfClass(type) {
51330             if (!type.resolvedBaseConstructorType) {
51331                 var decl = type.symbol.valueDeclaration;
51332                 var extended = ts.getEffectiveBaseTypeNode(decl);
51333                 var baseTypeNode = getBaseTypeNodeOfClass(type);
51334                 if (!baseTypeNode) {
51335                     return type.resolvedBaseConstructorType = undefinedType;
51336                 }
51337                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
51338                     return errorType;
51339                 }
51340                 var baseConstructorType = checkExpression(baseTypeNode.expression);
51341                 if (extended && baseTypeNode !== extended) {
51342                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
51343                     checkExpression(extended.expression);
51344                 }
51345                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
51346                     // Resolving the members of a class requires us to resolve the base class of that class.
51347                     // We force resolution here such that we catch circularities now.
51348                     resolveStructuredTypeMembers(baseConstructorType);
51349                 }
51350                 if (!popTypeResolution()) {
51351                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
51352                     return type.resolvedBaseConstructorType = errorType;
51353                 }
51354                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
51355                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
51356                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
51357                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
51358                         var ctorReturn = unknownType;
51359                         if (constraint) {
51360                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
51361                             if (ctorSig[0]) {
51362                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
51363                             }
51364                         }
51365                         ts.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)));
51366                     }
51367                     return type.resolvedBaseConstructorType = errorType;
51368                 }
51369                 type.resolvedBaseConstructorType = baseConstructorType;
51370             }
51371             return type.resolvedBaseConstructorType;
51372         }
51373         function getImplementsTypes(type) {
51374             var resolvedImplementsTypes = ts.emptyArray;
51375             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
51376                 var declaration = _a[_i];
51377                 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
51378                 if (!implementsTypeNodes)
51379                     continue;
51380                 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
51381                     var node = implementsTypeNodes_1[_b];
51382                     var implementsType = getTypeFromTypeNode(node);
51383                     if (implementsType !== errorType) {
51384                         if (resolvedImplementsTypes === ts.emptyArray) {
51385                             resolvedImplementsTypes = [implementsType];
51386                         }
51387                         else {
51388                             resolvedImplementsTypes.push(implementsType);
51389                         }
51390                     }
51391                 }
51392             }
51393             return resolvedImplementsTypes;
51394         }
51395         function reportCircularBaseType(node, type) {
51396             error(node, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
51397         }
51398         function getBaseTypes(type) {
51399             if (!type.baseTypesResolved) {
51400                 if (pushTypeResolution(type, 7 /* ResolvedBaseTypes */)) {
51401                     if (type.objectFlags & 8 /* Tuple */) {
51402                         type.resolvedBaseTypes = [getTupleBaseType(type)];
51403                     }
51404                     else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
51405                         if (type.symbol.flags & 32 /* Class */) {
51406                             resolveBaseTypesOfClass(type);
51407                         }
51408                         if (type.symbol.flags & 64 /* Interface */) {
51409                             resolveBaseTypesOfInterface(type);
51410                         }
51411                     }
51412                     else {
51413                         ts.Debug.fail("type must be class or interface");
51414                     }
51415                     if (!popTypeResolution()) {
51416                         for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
51417                             var declaration = _a[_i];
51418                             if (declaration.kind === 252 /* ClassDeclaration */ || declaration.kind === 253 /* InterfaceDeclaration */) {
51419                                 reportCircularBaseType(declaration, type);
51420                             }
51421                         }
51422                     }
51423                 }
51424                 type.baseTypesResolved = true;
51425             }
51426             return type.resolvedBaseTypes;
51427         }
51428         function getTupleBaseType(type) {
51429             var elementTypes = ts.sameMap(type.typeParameters, function (t, i) { return type.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t; });
51430             return createArrayType(getUnionType(elementTypes || ts.emptyArray), type.readonly);
51431         }
51432         function resolveBaseTypesOfClass(type) {
51433             type.resolvedBaseTypes = ts.resolvingEmptyArray;
51434             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
51435             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
51436                 return type.resolvedBaseTypes = ts.emptyArray;
51437             }
51438             var baseTypeNode = getBaseTypeNodeOfClass(type);
51439             var baseType;
51440             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
51441             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
51442                 areAllOuterTypeParametersApplied(originalBaseType)) {
51443                 // 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
51444                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
51445                 // type arguments in the same manner as a type reference to get the same error reporting experience.
51446                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
51447             }
51448             else if (baseConstructorType.flags & 1 /* Any */) {
51449                 baseType = baseConstructorType;
51450             }
51451             else {
51452                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
51453                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
51454                 // we check that all instantiated signatures return the same type.
51455                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
51456                 if (!constructors.length) {
51457                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
51458                     return type.resolvedBaseTypes = ts.emptyArray;
51459                 }
51460                 baseType = getReturnTypeOfSignature(constructors[0]);
51461             }
51462             if (baseType === errorType) {
51463                 return type.resolvedBaseTypes = ts.emptyArray;
51464             }
51465             var reducedBaseType = getReducedType(baseType);
51466             if (!isValidBaseType(reducedBaseType)) {
51467                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
51468                 var diagnostic = ts.chainDiagnosticMessages(elaboration, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType));
51469                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
51470                 return type.resolvedBaseTypes = ts.emptyArray;
51471             }
51472             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
51473                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
51474                 return type.resolvedBaseTypes = ts.emptyArray;
51475             }
51476             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
51477                 // Circular reference, likely through instantiation of default parameters
51478                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
51479                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
51480                 // partial instantiation of the members without the base types fully resolved
51481                 type.members = undefined;
51482             }
51483             return type.resolvedBaseTypes = [reducedBaseType];
51484         }
51485         function areAllOuterTypeParametersApplied(type) {
51486             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
51487             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
51488             var outerTypeParameters = type.outerTypeParameters;
51489             if (outerTypeParameters) {
51490                 var last_1 = outerTypeParameters.length - 1;
51491                 var typeArguments = getTypeArguments(type);
51492                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
51493             }
51494             return true;
51495         }
51496         // A valid base type is `any`, an object type or intersection of object types.
51497         function isValidBaseType(type) {
51498             if (type.flags & 262144 /* TypeParameter */) {
51499                 var constraint = getBaseConstraintOfType(type);
51500                 if (constraint) {
51501                     return isValidBaseType(constraint);
51502                 }
51503             }
51504             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
51505             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
51506             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
51507                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
51508         }
51509         function resolveBaseTypesOfInterface(type) {
51510             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
51511             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
51512                 var declaration = _a[_i];
51513                 if (declaration.kind === 253 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
51514                     for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
51515                         var node = _c[_b];
51516                         var baseType = getReducedType(getTypeFromTypeNode(node));
51517                         if (baseType !== errorType) {
51518                             if (isValidBaseType(baseType)) {
51519                                 if (type !== baseType && !hasBaseType(baseType, type)) {
51520                                     if (type.resolvedBaseTypes === ts.emptyArray) {
51521                                         type.resolvedBaseTypes = [baseType];
51522                                     }
51523                                     else {
51524                                         type.resolvedBaseTypes.push(baseType);
51525                                     }
51526                                 }
51527                                 else {
51528                                     reportCircularBaseType(declaration, type);
51529                                 }
51530                             }
51531                             else {
51532                                 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
51533                             }
51534                         }
51535                     }
51536                 }
51537             }
51538         }
51539         /**
51540          * Returns true if the interface given by the symbol is free of "this" references.
51541          *
51542          * Specifically, the result is true if the interface itself contains no references
51543          * to "this" in its body, if all base types are interfaces,
51544          * and if none of the base interfaces have a "this" type.
51545          */
51546         function isThislessInterface(symbol) {
51547             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51548                 var declaration = _a[_i];
51549                 if (declaration.kind === 253 /* InterfaceDeclaration */) {
51550                     if (declaration.flags & 128 /* ContainsThis */) {
51551                         return false;
51552                     }
51553                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
51554                     if (baseTypeNodes) {
51555                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
51556                             var node = baseTypeNodes_1[_b];
51557                             if (ts.isEntityNameExpression(node.expression)) {
51558                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
51559                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
51560                                     return false;
51561                                 }
51562                             }
51563                         }
51564                     }
51565                 }
51566             }
51567             return true;
51568         }
51569         function getDeclaredTypeOfClassOrInterface(symbol) {
51570             var links = getSymbolLinks(symbol);
51571             var originalLinks = links;
51572             if (!links.declaredType) {
51573                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
51574                 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
51575                 if (merged) {
51576                     // note:we overwrite links because we just cloned the symbol
51577                     symbol = links = merged;
51578                 }
51579                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
51580                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
51581                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
51582                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
51583                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
51584                 // property types inferred from initializers and method return types inferred from return statements are very hard
51585                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
51586                 // "this" references.
51587                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
51588                     type.objectFlags |= 4 /* Reference */;
51589                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
51590                     type.outerTypeParameters = outerTypeParameters;
51591                     type.localTypeParameters = localTypeParameters;
51592                     type.instantiations = new ts.Map();
51593                     type.instantiations.set(getTypeListId(type.typeParameters), type);
51594                     type.target = type;
51595                     type.resolvedTypeArguments = type.typeParameters;
51596                     type.thisType = createTypeParameter(symbol);
51597                     type.thisType.isThisType = true;
51598                     type.thisType.constraint = type;
51599                 }
51600             }
51601             return links.declaredType;
51602         }
51603         function getDeclaredTypeOfTypeAlias(symbol) {
51604             var links = getSymbolLinks(symbol);
51605             if (!links.declaredType) {
51606                 // Note that we use the links object as the target here because the symbol object is used as the unique
51607                 // identity for resolution of the 'type' property in SymbolLinks.
51608                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
51609                     return errorType;
51610                 }
51611                 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
51612                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
51613                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
51614                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
51615                 if (popTypeResolution()) {
51616                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
51617                     if (typeParameters) {
51618                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
51619                         // an instantiation of the type alias with the type parameters supplied as type arguments.
51620                         links.typeParameters = typeParameters;
51621                         links.instantiations = new ts.Map();
51622                         links.instantiations.set(getTypeListId(typeParameters), type);
51623                     }
51624                 }
51625                 else {
51626                     type = errorType;
51627                     error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
51628                 }
51629                 links.declaredType = type;
51630             }
51631             return links.declaredType;
51632         }
51633         function isStringConcatExpression(expr) {
51634             if (ts.isStringLiteralLike(expr)) {
51635                 return true;
51636             }
51637             else if (expr.kind === 216 /* BinaryExpression */) {
51638                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
51639             }
51640             return false;
51641         }
51642         function isLiteralEnumMember(member) {
51643             var expr = member.initializer;
51644             if (!expr) {
51645                 return !(member.flags & 8388608 /* Ambient */);
51646             }
51647             switch (expr.kind) {
51648                 case 10 /* StringLiteral */:
51649                 case 8 /* NumericLiteral */:
51650                 case 14 /* NoSubstitutionTemplateLiteral */:
51651                     return true;
51652                 case 214 /* PrefixUnaryExpression */:
51653                     return expr.operator === 40 /* MinusToken */ &&
51654                         expr.operand.kind === 8 /* NumericLiteral */;
51655                 case 78 /* Identifier */:
51656                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
51657                 case 216 /* BinaryExpression */:
51658                     return isStringConcatExpression(expr);
51659                 default:
51660                     return false;
51661             }
51662         }
51663         function getEnumKind(symbol) {
51664             var links = getSymbolLinks(symbol);
51665             if (links.enumKind !== undefined) {
51666                 return links.enumKind;
51667             }
51668             var hasNonLiteralMember = false;
51669             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51670                 var declaration = _a[_i];
51671                 if (declaration.kind === 255 /* EnumDeclaration */) {
51672                     for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
51673                         var member = _c[_b];
51674                         if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
51675                             return links.enumKind = 1 /* Literal */;
51676                         }
51677                         if (!isLiteralEnumMember(member)) {
51678                             hasNonLiteralMember = true;
51679                         }
51680                     }
51681                 }
51682             }
51683             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
51684         }
51685         function getBaseTypeOfEnumLiteralType(type) {
51686             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
51687         }
51688         function getDeclaredTypeOfEnum(symbol) {
51689             var links = getSymbolLinks(symbol);
51690             if (links.declaredType) {
51691                 return links.declaredType;
51692             }
51693             if (getEnumKind(symbol) === 1 /* Literal */) {
51694                 enumCount++;
51695                 var memberTypeList = [];
51696                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51697                     var declaration = _a[_i];
51698                     if (declaration.kind === 255 /* EnumDeclaration */) {
51699                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
51700                             var member = _c[_b];
51701                             var value = getEnumMemberValue(member);
51702                             var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
51703                             getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
51704                             memberTypeList.push(getRegularTypeOfLiteralType(memberType));
51705                         }
51706                     }
51707                 }
51708                 if (memberTypeList.length) {
51709                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
51710                     if (enumType_1.flags & 1048576 /* Union */) {
51711                         enumType_1.flags |= 1024 /* EnumLiteral */;
51712                         enumType_1.symbol = symbol;
51713                     }
51714                     return links.declaredType = enumType_1;
51715                 }
51716             }
51717             var enumType = createType(32 /* Enum */);
51718             enumType.symbol = symbol;
51719             return links.declaredType = enumType;
51720         }
51721         function getDeclaredTypeOfEnumMember(symbol) {
51722             var links = getSymbolLinks(symbol);
51723             if (!links.declaredType) {
51724                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
51725                 if (!links.declaredType) {
51726                     links.declaredType = enumType;
51727                 }
51728             }
51729             return links.declaredType;
51730         }
51731         function getDeclaredTypeOfTypeParameter(symbol) {
51732             var links = getSymbolLinks(symbol);
51733             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
51734         }
51735         function getDeclaredTypeOfAlias(symbol) {
51736             var links = getSymbolLinks(symbol);
51737             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
51738         }
51739         function getDeclaredTypeOfSymbol(symbol) {
51740             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
51741         }
51742         function tryGetDeclaredTypeOfSymbol(symbol) {
51743             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
51744                 return getDeclaredTypeOfClassOrInterface(symbol);
51745             }
51746             if (symbol.flags & 524288 /* TypeAlias */) {
51747                 return getDeclaredTypeOfTypeAlias(symbol);
51748             }
51749             if (symbol.flags & 262144 /* TypeParameter */) {
51750                 return getDeclaredTypeOfTypeParameter(symbol);
51751             }
51752             if (symbol.flags & 384 /* Enum */) {
51753                 return getDeclaredTypeOfEnum(symbol);
51754             }
51755             if (symbol.flags & 8 /* EnumMember */) {
51756                 return getDeclaredTypeOfEnumMember(symbol);
51757             }
51758             if (symbol.flags & 2097152 /* Alias */) {
51759                 return getDeclaredTypeOfAlias(symbol);
51760             }
51761             return undefined;
51762         }
51763         /**
51764          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
51765          * literal type, an array with an element type that is free of this references, or a type reference that is
51766          * free of this references.
51767          */
51768         function isThislessType(node) {
51769             switch (node.kind) {
51770                 case 128 /* AnyKeyword */:
51771                 case 152 /* UnknownKeyword */:
51772                 case 147 /* StringKeyword */:
51773                 case 144 /* NumberKeyword */:
51774                 case 155 /* BigIntKeyword */:
51775                 case 131 /* BooleanKeyword */:
51776                 case 148 /* SymbolKeyword */:
51777                 case 145 /* ObjectKeyword */:
51778                 case 113 /* VoidKeyword */:
51779                 case 150 /* UndefinedKeyword */:
51780                 case 141 /* NeverKeyword */:
51781                 case 191 /* LiteralType */:
51782                     return true;
51783                 case 178 /* ArrayType */:
51784                     return isThislessType(node.elementType);
51785                 case 173 /* TypeReference */:
51786                     return !node.typeArguments || node.typeArguments.every(isThislessType);
51787             }
51788             return false;
51789         }
51790         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
51791         function isThislessTypeParameter(node) {
51792             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
51793             return !constraint || isThislessType(constraint);
51794         }
51795         /**
51796          * A variable-like declaration is free of this references if it has a type annotation
51797          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
51798          */
51799         function isThislessVariableLikeDeclaration(node) {
51800             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
51801             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
51802         }
51803         /**
51804          * A function-like declaration is considered free of `this` references if it has a return type
51805          * annotation that is free of this references and if each parameter is thisless and if
51806          * each type parameter (if present) is thisless.
51807          */
51808         function isThislessFunctionLikeDeclaration(node) {
51809             var returnType = ts.getEffectiveReturnTypeNode(node);
51810             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
51811             return (node.kind === 166 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
51812                 node.parameters.every(isThislessVariableLikeDeclaration) &&
51813                 typeParameters.every(isThislessTypeParameter);
51814         }
51815         /**
51816          * Returns true if the class or interface member given by the symbol is free of "this" references. The
51817          * function may return false for symbols that are actually free of "this" references because it is not
51818          * feasible to perform a complete analysis in all cases. In particular, property members with types
51819          * inferred from their initializers and function members with inferred return types are conservatively
51820          * assumed not to be free of "this" references.
51821          */
51822         function isThisless(symbol) {
51823             if (symbol.declarations && symbol.declarations.length === 1) {
51824                 var declaration = symbol.declarations[0];
51825                 if (declaration) {
51826                     switch (declaration.kind) {
51827                         case 163 /* PropertyDeclaration */:
51828                         case 162 /* PropertySignature */:
51829                             return isThislessVariableLikeDeclaration(declaration);
51830                         case 165 /* MethodDeclaration */:
51831                         case 164 /* MethodSignature */:
51832                         case 166 /* Constructor */:
51833                         case 167 /* GetAccessor */:
51834                         case 168 /* SetAccessor */:
51835                             return isThislessFunctionLikeDeclaration(declaration);
51836                     }
51837                 }
51838             }
51839             return false;
51840         }
51841         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
51842         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
51843         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
51844             var result = ts.createSymbolTable();
51845             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
51846                 var symbol = symbols_2[_i];
51847                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
51848             }
51849             return result;
51850         }
51851         function addInheritedMembers(symbols, baseSymbols) {
51852             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
51853                 var s = baseSymbols_1[_i];
51854                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
51855                     symbols.set(s.escapedName, s);
51856                 }
51857             }
51858         }
51859         function isStaticPrivateIdentifierProperty(s) {
51860             return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */);
51861         }
51862         function resolveDeclaredMembers(type) {
51863             if (!type.declaredProperties) {
51864                 var symbol = type.symbol;
51865                 var members = getMembersOfSymbol(symbol);
51866                 type.declaredProperties = getNamedMembers(members);
51867                 // Start with signatures at empty array in case of recursive types
51868                 type.declaredCallSignatures = ts.emptyArray;
51869                 type.declaredConstructSignatures = ts.emptyArray;
51870                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
51871                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
51872                 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
51873                 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
51874             }
51875             return type;
51876         }
51877         /**
51878          * Indicates whether a type can be used as a property name.
51879          */
51880         function isTypeUsableAsPropertyName(type) {
51881             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
51882         }
51883         /**
51884          * Indicates whether a declaration name is definitely late-bindable.
51885          * A declaration name is only late-bindable if:
51886          * - It is a `ComputedPropertyName`.
51887          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
51888          * `ElementAccessExpression` consisting only of these same three types of nodes.
51889          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
51890          */
51891         function isLateBindableName(node) {
51892             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
51893                 return false;
51894             }
51895             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
51896             return ts.isEntityNameExpression(expr)
51897                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
51898         }
51899         function isLateBoundName(name) {
51900             return name.charCodeAt(0) === 95 /* _ */ &&
51901                 name.charCodeAt(1) === 95 /* _ */ &&
51902                 name.charCodeAt(2) === 64 /* at */;
51903         }
51904         /**
51905          * Indicates whether a declaration has a late-bindable dynamic name.
51906          */
51907         function hasLateBindableName(node) {
51908             var name = ts.getNameOfDeclaration(node);
51909             return !!name && isLateBindableName(name);
51910         }
51911         /**
51912          * Indicates whether a declaration has a dynamic name that cannot be late-bound.
51913          */
51914         function hasNonBindableDynamicName(node) {
51915             return ts.hasDynamicName(node) && !hasLateBindableName(node);
51916         }
51917         /**
51918          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
51919          */
51920         function isNonBindableDynamicName(node) {
51921             return ts.isDynamicName(node) && !isLateBindableName(node);
51922         }
51923         /**
51924          * Gets the symbolic name for a member from its type.
51925          */
51926         function getPropertyNameFromType(type) {
51927             if (type.flags & 8192 /* UniqueESSymbol */) {
51928                 return type.escapedName;
51929             }
51930             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
51931                 return ts.escapeLeadingUnderscores("" + type.value);
51932             }
51933             return ts.Debug.fail();
51934         }
51935         /**
51936          * Adds a declaration to a late-bound dynamic member. This performs the same function for
51937          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
51938          * members.
51939          */
51940         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
51941             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
51942             symbol.flags |= symbolFlags;
51943             getSymbolLinks(member.symbol).lateSymbol = symbol;
51944             if (!symbol.declarations) {
51945                 symbol.declarations = [member];
51946             }
51947             else {
51948                 symbol.declarations.push(member);
51949             }
51950             if (symbolFlags & 111551 /* Value */) {
51951                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
51952                     symbol.valueDeclaration = member;
51953                 }
51954             }
51955         }
51956         /**
51957          * Performs late-binding of a dynamic member. This performs the same function for
51958          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
51959          * members.
51960          *
51961          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
51962          * binding phase to attempt to resolve the name for the symbol from the type of the computed
51963          * property's expression. If the type of the expression is a string-literal, numeric-literal,
51964          * or unique symbol type, we can use that type as the name of the symbol.
51965          *
51966          * For example, given:
51967          *
51968          *   const x = Symbol();
51969          *
51970          *   interface I {
51971          *     [x]: number;
51972          *   }
51973          *
51974          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
51975          * In the late-binding phase we can type-check the expression `x` and see that it has a
51976          * unique symbol type which we can then use as the name of the member. This allows users
51977          * to define custom symbols that can be used in the members of an object type.
51978          *
51979          * @param parent The containing symbol for the member.
51980          * @param earlySymbols The early-bound symbols of the parent.
51981          * @param lateSymbols The late-bound symbols of the parent.
51982          * @param decl The member to bind.
51983          */
51984         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
51985             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
51986             var links = getNodeLinks(decl);
51987             if (!links.resolvedSymbol) {
51988                 // In the event we attempt to resolve the late-bound name of this member recursively,
51989                 // fall back to the early-bound name of this member.
51990                 links.resolvedSymbol = decl.symbol;
51991                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
51992                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
51993                 if (isTypeUsableAsPropertyName(type)) {
51994                     var memberName = getPropertyNameFromType(type);
51995                     var symbolFlags = decl.symbol.flags;
51996                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
51997                     var lateSymbol = lateSymbols.get(memberName);
51998                     if (!lateSymbol)
51999                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
52000                     // Report an error if a late-bound member has the same name as an early-bound member,
52001                     // or if we have another early-bound symbol declaration with the same name and
52002                     // conflicting flags.
52003                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
52004                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
52005                         // If we have an existing early-bound member, combine its declarations so that we can
52006                         // report an error at each declaration.
52007                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
52008                         var name_4 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
52009                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_4); });
52010                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_4);
52011                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
52012                     }
52013                     lateSymbol.nameType = type;
52014                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
52015                     if (lateSymbol.parent) {
52016                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
52017                     }
52018                     else {
52019                         lateSymbol.parent = parent;
52020                     }
52021                     return links.resolvedSymbol = lateSymbol;
52022                 }
52023             }
52024             return links.resolvedSymbol;
52025         }
52026         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
52027             var links = getSymbolLinks(symbol);
52028             if (!links[resolutionKind]) {
52029                 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
52030                 var earlySymbols = !isStatic ? symbol.members :
52031                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
52032                         symbol.exports;
52033                 // In the event we recursively resolve the members/exports of the symbol, we
52034                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
52035                 // members/exports of the symbol.
52036                 links[resolutionKind] = earlySymbols || emptySymbols;
52037                 // fill in any as-yet-unresolved late-bound members.
52038                 var lateSymbols = ts.createSymbolTable();
52039                 for (var _i = 0, _a = symbol.declarations || ts.emptyArray; _i < _a.length; _i++) {
52040                     var decl = _a[_i];
52041                     var members = ts.getMembersOfDeclaration(decl);
52042                     if (members) {
52043                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
52044                             var member = members_5[_b];
52045                             if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
52046                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
52047                             }
52048                         }
52049                     }
52050                 }
52051                 var assignments = symbol.assignmentDeclarationMembers;
52052                 if (assignments) {
52053                     var decls = ts.arrayFrom(assignments.values());
52054                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
52055                         var member = decls_1[_c];
52056                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
52057                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
52058                             || ts.isBinaryExpression(member) && isPossiblyAliasedThisProperty(member, assignmentKind)
52059                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
52060                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
52061                         if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
52062                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
52063                         }
52064                     }
52065                 }
52066                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
52067             }
52068             return links[resolutionKind];
52069         }
52070         /**
52071          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
52072          *
52073          * For a description of late-binding, see `lateBindMember`.
52074          */
52075         function getMembersOfSymbol(symbol) {
52076             return symbol.flags & 6256 /* LateBindingContainer */
52077                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
52078                 : symbol.members || emptySymbols;
52079         }
52080         /**
52081          * If a symbol is the dynamic name of the member of an object type, get the late-bound
52082          * symbol of the member.
52083          *
52084          * For a description of late-binding, see `lateBindMember`.
52085          */
52086         function getLateBoundSymbol(symbol) {
52087             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
52088                 var links = getSymbolLinks(symbol);
52089                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
52090                     // force late binding of members/exports. This will set the late-bound symbol
52091                     var parent = getMergedSymbol(symbol.parent);
52092                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
52093                         getExportsOfSymbol(parent);
52094                     }
52095                     else {
52096                         getMembersOfSymbol(parent);
52097                     }
52098                 }
52099                 return links.lateSymbol || (links.lateSymbol = symbol);
52100             }
52101             return symbol;
52102         }
52103         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
52104             if (ts.getObjectFlags(type) & 4 /* Reference */) {
52105                 var target = type.target;
52106                 var typeArguments = getTypeArguments(type);
52107                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
52108                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
52109                     return needApparentType ? getApparentType(ref) : ref;
52110                 }
52111             }
52112             else if (type.flags & 2097152 /* Intersection */) {
52113                 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
52114             }
52115             return needApparentType ? getApparentType(type) : type;
52116         }
52117         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
52118             var mapper;
52119             var members;
52120             var callSignatures;
52121             var constructSignatures;
52122             var stringIndexInfo;
52123             var numberIndexInfo;
52124             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
52125                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
52126                 callSignatures = source.declaredCallSignatures;
52127                 constructSignatures = source.declaredConstructSignatures;
52128                 stringIndexInfo = source.declaredStringIndexInfo;
52129                 numberIndexInfo = source.declaredNumberIndexInfo;
52130             }
52131             else {
52132                 mapper = createTypeMapper(typeParameters, typeArguments);
52133                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
52134                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
52135                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
52136                 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
52137                 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
52138             }
52139             var baseTypes = getBaseTypes(source);
52140             if (baseTypes.length) {
52141                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
52142                     members = ts.createSymbolTable(source.declaredProperties);
52143                 }
52144                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52145                 var thisArgument = ts.lastOrUndefined(typeArguments);
52146                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
52147                     var baseType = baseTypes_1[_i];
52148                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
52149                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
52150                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
52151                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
52152                     if (!stringIndexInfo) {
52153                         stringIndexInfo = instantiatedBaseType === anyType ?
52154                             createIndexInfo(anyType, /*isReadonly*/ false) :
52155                             getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
52156                     }
52157                     numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
52158                 }
52159             }
52160             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52161         }
52162         function resolveClassOrInterfaceMembers(type) {
52163             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
52164         }
52165         function resolveTypeReferenceMembers(type) {
52166             var source = resolveDeclaredMembers(type.target);
52167             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
52168             var typeArguments = getTypeArguments(type);
52169             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
52170             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
52171         }
52172         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
52173             var sig = new Signature(checker, flags);
52174             sig.declaration = declaration;
52175             sig.typeParameters = typeParameters;
52176             sig.parameters = parameters;
52177             sig.thisParameter = thisParameter;
52178             sig.resolvedReturnType = resolvedReturnType;
52179             sig.resolvedTypePredicate = resolvedTypePredicate;
52180             sig.minArgumentCount = minArgumentCount;
52181             sig.resolvedMinArgumentCount = undefined;
52182             sig.target = undefined;
52183             sig.mapper = undefined;
52184             sig.unionSignatures = undefined;
52185             return sig;
52186         }
52187         function cloneSignature(sig) {
52188             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
52189             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 19 /* PropagatingFlags */);
52190             result.target = sig.target;
52191             result.mapper = sig.mapper;
52192             result.unionSignatures = sig.unionSignatures;
52193             return result;
52194         }
52195         function createUnionSignature(signature, unionSignatures) {
52196             var result = cloneSignature(signature);
52197             result.unionSignatures = unionSignatures;
52198             result.target = undefined;
52199             result.mapper = undefined;
52200             return result;
52201         }
52202         function getOptionalCallSignature(signature, callChainFlags) {
52203             if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
52204                 return signature;
52205             }
52206             if (!signature.optionalCallSignatureCache) {
52207                 signature.optionalCallSignatureCache = {};
52208             }
52209             var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
52210             return signature.optionalCallSignatureCache[key]
52211                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
52212         }
52213         function createOptionalCallSignature(signature, callChainFlags) {
52214             ts.Debug.assert(callChainFlags === 4 /* IsInnerCallChain */ || callChainFlags === 8 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both.");
52215             var result = cloneSignature(signature);
52216             result.flags |= callChainFlags;
52217             return result;
52218         }
52219         function getExpandedParameters(sig, skipUnionExpanding) {
52220             if (signatureHasRestParameter(sig)) {
52221                 var restIndex_1 = sig.parameters.length - 1;
52222                 var restType = getTypeOfSymbol(sig.parameters[restIndex_1]);
52223                 if (isTupleType(restType)) {
52224                     return [expandSignatureParametersWithTupleMembers(restType, restIndex_1)];
52225                 }
52226                 else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && ts.every(restType.types, isTupleType)) {
52227                     return ts.map(restType.types, function (t) { return expandSignatureParametersWithTupleMembers(t, restIndex_1); });
52228                 }
52229             }
52230             return [sig.parameters];
52231             function expandSignatureParametersWithTupleMembers(restType, restIndex) {
52232                 var elementTypes = getTypeArguments(restType);
52233                 var associatedNames = restType.target.labeledElementDeclarations;
52234                 var restParams = ts.map(elementTypes, function (t, i) {
52235                     // Lookup the label from the individual tuple passed in before falling back to the signature `rest` parameter name
52236                     var tupleLabelName = !!associatedNames && getTupleElementLabel(associatedNames[i]);
52237                     var name = tupleLabelName || getParameterNameAtPosition(sig, restIndex + i, restType);
52238                     var flags = restType.target.elementFlags[i];
52239                     var checkFlags = flags & 12 /* Variable */ ? 32768 /* RestParameter */ :
52240                         flags & 2 /* Optional */ ? 16384 /* OptionalParameter */ : 0;
52241                     var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
52242                     symbol.type = flags & 4 /* Rest */ ? createArrayType(t) : t;
52243                     return symbol;
52244                 });
52245                 return ts.concatenate(sig.parameters.slice(0, restIndex), restParams);
52246             }
52247         }
52248         function getDefaultConstructSignatures(classType) {
52249             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
52250             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
52251             if (baseSignatures.length === 0) {
52252                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
52253             }
52254             var baseTypeNode = getBaseTypeNodeOfClass(classType);
52255             var isJavaScript = ts.isInJSFile(baseTypeNode);
52256             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
52257             var typeArgCount = ts.length(typeArguments);
52258             var result = [];
52259             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
52260                 var baseSig = baseSignatures_1[_i];
52261                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
52262                 var typeParamCount = ts.length(baseSig.typeParameters);
52263                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
52264                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
52265                     sig.typeParameters = classType.localTypeParameters;
52266                     sig.resolvedReturnType = classType;
52267                     result.push(sig);
52268                 }
52269             }
52270             return result;
52271         }
52272         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
52273             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
52274                 var s = signatureList_1[_i];
52275                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
52276                     return s;
52277                 }
52278             }
52279         }
52280         function findMatchingSignatures(signatureLists, signature, listIndex) {
52281             if (signature.typeParameters) {
52282                 // We require an exact match for generic signatures, so we only return signatures from the first
52283                 // signature list and only if they have exact matches in the other signature lists.
52284                 if (listIndex > 0) {
52285                     return undefined;
52286                 }
52287                 for (var i = 1; i < signatureLists.length; i++) {
52288                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
52289                         return undefined;
52290                     }
52291                 }
52292                 return [signature];
52293             }
52294             var result;
52295             for (var i = 0; i < signatureLists.length; i++) {
52296                 // Allow matching non-generic signatures to have excess parameters and different return types.
52297                 // Prefer matching this types if possible.
52298                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
52299                 if (!match) {
52300                     return undefined;
52301                 }
52302                 result = ts.appendIfUnique(result, match);
52303             }
52304             return result;
52305         }
52306         // The signatures of a union type are those signatures that are present in each of the constituent types.
52307         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
52308         // parameters and may differ in return types. When signatures differ in return types, the resulting return
52309         // type is the union of the constituent return types.
52310         function getUnionSignatures(signatureLists) {
52311             var result;
52312             var indexWithLengthOverOne;
52313             for (var i = 0; i < signatureLists.length; i++) {
52314                 if (signatureLists[i].length === 0)
52315                     return ts.emptyArray;
52316                 if (signatureLists[i].length > 1) {
52317                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
52318                 }
52319                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
52320                     var signature = _a[_i];
52321                     // Only process signatures with parameter lists that aren't already in the result list
52322                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
52323                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
52324                         if (unionSignatures) {
52325                             var s = signature;
52326                             // Union the result types when more than one signature matches
52327                             if (unionSignatures.length > 1) {
52328                                 var thisParameter = signature.thisParameter;
52329                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
52330                                 if (firstThisParameterOfUnionSignatures) {
52331                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
52332                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
52333                                 }
52334                                 s = createUnionSignature(signature, unionSignatures);
52335                                 s.thisParameter = thisParameter;
52336                             }
52337                             (result || (result = [])).push(s);
52338                         }
52339                     }
52340                 }
52341             }
52342             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
52343                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
52344                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
52345                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
52346                 // signatures from the type, whose ordering would be non-obvious)
52347                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
52348                 var results = masterList.slice();
52349                 var _loop_10 = function (signatures) {
52350                     if (signatures !== masterList) {
52351                         var signature_1 = signatures[0];
52352                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
52353                         results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
52354                         if (!results) {
52355                             return "break";
52356                         }
52357                     }
52358                 };
52359                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
52360                     var signatures = signatureLists_1[_b];
52361                     var state_3 = _loop_10(signatures);
52362                     if (state_3 === "break")
52363                         break;
52364                 }
52365                 result = results;
52366             }
52367             return result || ts.emptyArray;
52368         }
52369         function combineUnionThisParam(left, right) {
52370             if (!left || !right) {
52371                 return left || right;
52372             }
52373             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
52374             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
52375             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
52376             var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
52377             return createSymbolWithType(left, thisType);
52378         }
52379         function combineUnionParameters(left, right) {
52380             var leftCount = getParameterCount(left);
52381             var rightCount = getParameterCount(right);
52382             var longest = leftCount >= rightCount ? left : right;
52383             var shorter = longest === left ? right : left;
52384             var longestCount = longest === left ? leftCount : rightCount;
52385             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
52386             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
52387             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
52388             for (var i = 0; i < longestCount; i++) {
52389                 var longestParamType = tryGetTypeAtPosition(longest, i);
52390                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
52391                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
52392                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
52393                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
52394                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
52395                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
52396                 var paramName = leftName === rightName ? leftName :
52397                     !leftName ? rightName :
52398                         !rightName ? leftName :
52399                             undefined;
52400                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
52401                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
52402                 params[i] = paramSymbol;
52403             }
52404             if (needsExtraRestElement) {
52405                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
52406                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
52407                 params[longestCount] = restParamSymbol;
52408             }
52409             return params;
52410         }
52411         function combineSignaturesOfUnionMembers(left, right) {
52412             var declaration = left.declaration;
52413             var params = combineUnionParameters(left, right);
52414             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
52415             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
52416             var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, 
52417             /*resolvedReturnType*/ undefined, 
52418             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 19 /* PropagatingFlags */);
52419             result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
52420             return result;
52421         }
52422         function getUnionIndexInfo(types, kind) {
52423             var indexTypes = [];
52424             var isAnyReadonly = false;
52425             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
52426                 var type = types_4[_i];
52427                 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
52428                 if (!indexInfo) {
52429                     return undefined;
52430                 }
52431                 indexTypes.push(indexInfo.type);
52432                 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
52433             }
52434             return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
52435         }
52436         function resolveUnionTypeMembers(type) {
52437             // The members and properties collections are empty for union types. To get all properties of a union
52438             // type use getPropertiesOfType (only the language service uses this).
52439             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
52440             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
52441             var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
52442             var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
52443             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52444         }
52445         function intersectTypes(type1, type2) {
52446             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
52447         }
52448         function intersectIndexInfos(info1, info2) {
52449             return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
52450         }
52451         function unionSpreadIndexInfos(info1, info2) {
52452             return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
52453         }
52454         function findMixins(types) {
52455             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
52456             var mixinFlags = ts.map(types, isMixinConstructorType);
52457             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
52458                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
52459                 mixinFlags[firstMixinIndex] = false;
52460             }
52461             return mixinFlags;
52462         }
52463         function includeMixinType(type, types, mixinFlags, index) {
52464             var mixedTypes = [];
52465             for (var i = 0; i < types.length; i++) {
52466                 if (i === index) {
52467                     mixedTypes.push(type);
52468                 }
52469                 else if (mixinFlags[i]) {
52470                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
52471                 }
52472             }
52473             return getIntersectionType(mixedTypes);
52474         }
52475         function resolveIntersectionTypeMembers(type) {
52476             // The members and properties collections are empty for intersection types. To get all properties of an
52477             // intersection type use getPropertiesOfType (only the language service uses this).
52478             var callSignatures;
52479             var constructSignatures;
52480             var stringIndexInfo;
52481             var numberIndexInfo;
52482             var types = type.types;
52483             var mixinFlags = findMixins(types);
52484             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
52485             var _loop_11 = function (i) {
52486                 var t = type.types[i];
52487                 // When an intersection type contains mixin constructor types, the construct signatures from
52488                 // those types are discarded and their return types are mixed into the return types of all
52489                 // other construct signatures in the intersection type. For example, the intersection type
52490                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
52491                 // 'new(s: string) => A & B'.
52492                 if (!mixinFlags[i]) {
52493                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
52494                     if (signatures.length && mixinCount > 0) {
52495                         signatures = ts.map(signatures, function (s) {
52496                             var clone = cloneSignature(s);
52497                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
52498                             return clone;
52499                         });
52500                     }
52501                     constructSignatures = appendSignatures(constructSignatures, signatures);
52502                 }
52503                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
52504                 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
52505                 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
52506             };
52507             for (var i = 0; i < types.length; i++) {
52508                 _loop_11(i);
52509             }
52510             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
52511         }
52512         function appendSignatures(signatures, newSignatures) {
52513             var _loop_12 = function (sig) {
52514                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
52515                     signatures = ts.append(signatures, sig);
52516                 }
52517             };
52518             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
52519                 var sig = newSignatures_1[_i];
52520                 _loop_12(sig);
52521             }
52522             return signatures;
52523         }
52524         /**
52525          * Converts an AnonymousType to a ResolvedType.
52526          */
52527         function resolveAnonymousTypeMembers(type) {
52528             var symbol = getMergedSymbol(type.symbol);
52529             if (type.target) {
52530                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
52531                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
52532                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
52533                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
52534                 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
52535                 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
52536                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52537             }
52538             else if (symbol.flags & 2048 /* TypeLiteral */) {
52539                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
52540                 var members = getMembersOfSymbol(symbol);
52541                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
52542                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
52543                 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
52544                 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
52545                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52546             }
52547             else {
52548                 // Combinations of function, class, enum and module
52549                 var members = emptySymbols;
52550                 var stringIndexInfo = void 0;
52551                 if (symbol.exports) {
52552                     members = getExportsOfSymbol(symbol);
52553                     if (symbol === globalThisSymbol) {
52554                         var varsOnly_1 = new ts.Map();
52555                         members.forEach(function (p) {
52556                             if (!(p.flags & 418 /* BlockScoped */)) {
52557                                 varsOnly_1.set(p.escapedName, p);
52558                             }
52559                         });
52560                         members = varsOnly_1;
52561                     }
52562                 }
52563                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
52564                 if (symbol.flags & 32 /* Class */) {
52565                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
52566                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
52567                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
52568                         members = ts.createSymbolTable(getNamedMembers(members));
52569                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
52570                     }
52571                     else if (baseConstructorType === anyType) {
52572                         stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
52573                     }
52574                 }
52575                 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
52576                     ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
52577                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
52578                 // We resolve the members before computing the signatures because a signature may use
52579                 // typeof with a qualified name expression that circularly references the type we are
52580                 // in the process of resolving (see issue #6072). The temporarily empty signature list
52581                 // will never be observed because a qualified name can't reference signatures.
52582                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
52583                     type.callSignatures = getSignaturesOfSymbol(symbol);
52584                 }
52585                 // And likewise for construct signatures for classes
52586                 if (symbol.flags & 32 /* Class */) {
52587                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
52588                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
52589                     if (symbol.flags & 16 /* Function */) {
52590                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
52591                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 19 /* PropagatingFlags */) :
52592                             undefined; }));
52593                     }
52594                     if (!constructSignatures.length) {
52595                         constructSignatures = getDefaultConstructSignatures(classType_1);
52596                     }
52597                     type.constructSignatures = constructSignatures;
52598                 }
52599             }
52600         }
52601         function resolveReverseMappedTypeMembers(type) {
52602             var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
52603             var modifiers = getMappedTypeModifiers(type.mappedType);
52604             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
52605             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
52606             var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
52607             var members = ts.createSymbolTable();
52608             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
52609                 var prop = _a[_i];
52610                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
52611                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
52612                 inferredProp.declarations = prop.declarations;
52613                 inferredProp.nameType = getSymbolLinks(prop).nameType;
52614                 inferredProp.propertyType = getTypeOfSymbol(prop);
52615                 inferredProp.mappedType = type.mappedType;
52616                 inferredProp.constraintType = type.constraintType;
52617                 members.set(prop.escapedName, inferredProp);
52618             }
52619             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
52620         }
52621         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
52622         // bound includes those keys that are known to always be present, for example because
52623         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
52624         function getLowerBoundOfKeyType(type) {
52625             if (type.flags & 4194304 /* Index */) {
52626                 var t = getApparentType(type.type);
52627                 return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t);
52628             }
52629             if (type.flags & 16777216 /* Conditional */) {
52630                 if (type.root.isDistributive) {
52631                     var checkType = type.checkType;
52632                     var constraint = getLowerBoundOfKeyType(checkType);
52633                     if (constraint !== checkType) {
52634                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
52635                     }
52636                 }
52637                 return type;
52638             }
52639             if (type.flags & 1048576 /* Union */) {
52640                 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
52641             }
52642             if (type.flags & 2097152 /* Intersection */) {
52643                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
52644             }
52645             return type;
52646         }
52647         /** Resolve the members of a mapped type { [P in K]: T } */
52648         function resolveMappedTypeMembers(type) {
52649             var members = ts.createSymbolTable();
52650             var stringIndexInfo;
52651             var numberIndexInfo;
52652             // Resolve upfront such that recursive references see an empty object type.
52653             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
52654             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
52655             // and T as the template type.
52656             var typeParameter = getTypeParameterFromMappedType(type);
52657             var constraintType = getConstraintTypeFromMappedType(type);
52658             var nameType = getNameTypeFromMappedType(type.target || type);
52659             var templateType = getTemplateTypeFromMappedType(type.target || type);
52660             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
52661             var templateModifiers = getMappedTypeModifiers(type);
52662             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
52663             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
52664                 // We have a { [P in keyof T]: X }
52665                 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
52666                     var prop = _a[_i];
52667                     addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
52668                 }
52669                 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
52670                     addMemberForKeyType(stringType);
52671                 }
52672                 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
52673                     addMemberForKeyType(numberType);
52674                 }
52675             }
52676             else {
52677                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
52678             }
52679             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
52680             function addMemberForKeyType(keyType) {
52681                 var propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType;
52682                 forEachType(propNameType, function (t) { return addMemberForKeyTypeWorker(keyType, t); });
52683             }
52684             function addMemberForKeyTypeWorker(keyType, propNameType) {
52685                 // If the current iteration type constituent is a string literal type, create a property.
52686                 // Otherwise, for type string create a string index signature.
52687                 if (isTypeUsableAsPropertyName(propNameType)) {
52688                     var propName = getPropertyNameFromType(propNameType);
52689                     // String enum members from separate enums with identical values
52690                     // are distinct types with the same property name. Make the resulting
52691                     // property symbol's name type be the union of those enum member types.
52692                     var existingProp = members.get(propName);
52693                     if (existingProp) {
52694                         existingProp.nameType = getUnionType([existingProp.nameType, propNameType]);
52695                         existingProp.keyType = getUnionType([existingProp.keyType, keyType]);
52696                     }
52697                     else {
52698                         var modifiersProp = isTypeUsableAsPropertyName(keyType) ? getPropertyOfType(modifiersType, getPropertyNameFromType(keyType)) : undefined;
52699                         var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
52700                             !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
52701                         var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
52702                             !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
52703                         var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
52704                         var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
52705                         prop.mappedType = type;
52706                         prop.nameType = propNameType;
52707                         prop.keyType = keyType;
52708                         if (modifiersProp) {
52709                             prop.syntheticOrigin = modifiersProp;
52710                             prop.declarations = modifiersProp.declarations;
52711                         }
52712                         members.set(propName, prop);
52713                     }
52714                 }
52715                 else if (propNameType.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
52716                     var propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType));
52717                     if (propNameType.flags & (1 /* Any */ | 4 /* String */)) {
52718                         stringIndexInfo = createIndexInfo(stringIndexInfo ? getUnionType([stringIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
52719                     }
52720                     else {
52721                         numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
52722                     }
52723                 }
52724             }
52725         }
52726         function getTypeOfMappedSymbol(symbol) {
52727             if (!symbol.type) {
52728                 var mappedType = symbol.mappedType;
52729                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
52730                     mappedType.containsError = true;
52731                     return errorType;
52732                 }
52733                 var templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType);
52734                 var mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.keyType);
52735                 var propType = instantiateType(templateType, mapper);
52736                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
52737                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
52738                 // mode, if the underlying property is optional we remove 'undefined' from the type.
52739                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
52740                     symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
52741                         propType;
52742                 if (!popTypeResolution()) {
52743                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType));
52744                     type = errorType;
52745                 }
52746                 symbol.type = type;
52747             }
52748             return symbol.type;
52749         }
52750         function getTypeParameterFromMappedType(type) {
52751             return type.typeParameter ||
52752                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
52753         }
52754         function getConstraintTypeFromMappedType(type) {
52755             return type.constraintType ||
52756                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
52757         }
52758         function getNameTypeFromMappedType(type) {
52759             return type.declaration.nameType ?
52760                 type.nameType || (type.nameType = instantiateType(getTypeFromTypeNode(type.declaration.nameType), type.mapper)) :
52761                 undefined;
52762         }
52763         function getTemplateTypeFromMappedType(type) {
52764             return type.templateType ||
52765                 (type.templateType = type.declaration.type ?
52766                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
52767                     errorType);
52768         }
52769         function getConstraintDeclarationForMappedType(type) {
52770             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
52771         }
52772         function isMappedTypeWithKeyofConstraintDeclaration(type) {
52773             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
52774             return constraintDeclaration.kind === 188 /* TypeOperator */ &&
52775                 constraintDeclaration.operator === 138 /* KeyOfKeyword */;
52776         }
52777         function getModifiersTypeFromMappedType(type) {
52778             if (!type.modifiersType) {
52779                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
52780                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
52781                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
52782                     // 'keyof T' to a literal union type and we can't recover T from that type.
52783                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
52784                 }
52785                 else {
52786                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
52787                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
52788                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
52789                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
52790                     var constraint = getConstraintTypeFromMappedType(declaredType);
52791                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
52792                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
52793                 }
52794             }
52795             return type.modifiersType;
52796         }
52797         function getMappedTypeModifiers(type) {
52798             var declaration = type.declaration;
52799             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
52800                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
52801         }
52802         function getMappedTypeOptionality(type) {
52803             var modifiers = getMappedTypeModifiers(type);
52804             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
52805         }
52806         function getCombinedMappedTypeOptionality(type) {
52807             var optionality = getMappedTypeOptionality(type);
52808             var modifiersType = getModifiersTypeFromMappedType(type);
52809             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
52810         }
52811         function isPartialMappedType(type) {
52812             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
52813         }
52814         function isGenericMappedType(type) {
52815             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
52816         }
52817         function resolveStructuredTypeMembers(type) {
52818             if (!type.members) {
52819                 if (type.flags & 524288 /* Object */) {
52820                     if (type.objectFlags & 4 /* Reference */) {
52821                         resolveTypeReferenceMembers(type);
52822                     }
52823                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
52824                         resolveClassOrInterfaceMembers(type);
52825                     }
52826                     else if (type.objectFlags & 2048 /* ReverseMapped */) {
52827                         resolveReverseMappedTypeMembers(type);
52828                     }
52829                     else if (type.objectFlags & 16 /* Anonymous */) {
52830                         resolveAnonymousTypeMembers(type);
52831                     }
52832                     else if (type.objectFlags & 32 /* Mapped */) {
52833                         resolveMappedTypeMembers(type);
52834                     }
52835                 }
52836                 else if (type.flags & 1048576 /* Union */) {
52837                     resolveUnionTypeMembers(type);
52838                 }
52839                 else if (type.flags & 2097152 /* Intersection */) {
52840                     resolveIntersectionTypeMembers(type);
52841                 }
52842             }
52843             return type;
52844         }
52845         /** Return properties of an object type or an empty array for other types */
52846         function getPropertiesOfObjectType(type) {
52847             if (type.flags & 524288 /* Object */) {
52848                 return resolveStructuredTypeMembers(type).properties;
52849             }
52850             return ts.emptyArray;
52851         }
52852         /** If the given type is an object type and that type has a property by the given name,
52853          * return the symbol for that property. Otherwise return undefined.
52854          */
52855         function getPropertyOfObjectType(type, name) {
52856             if (type.flags & 524288 /* Object */) {
52857                 var resolved = resolveStructuredTypeMembers(type);
52858                 var symbol = resolved.members.get(name);
52859                 if (symbol && symbolIsValue(symbol)) {
52860                     return symbol;
52861                 }
52862             }
52863         }
52864         function getPropertiesOfUnionOrIntersectionType(type) {
52865             if (!type.resolvedProperties) {
52866                 var members = ts.createSymbolTable();
52867                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
52868                     var current = _a[_i];
52869                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
52870                         var prop = _c[_b];
52871                         if (!members.has(prop.escapedName)) {
52872                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
52873                             if (combinedProp) {
52874                                 members.set(prop.escapedName, combinedProp);
52875                             }
52876                         }
52877                     }
52878                     // The properties of a union type are those that are present in all constituent types, so
52879                     // we only need to check the properties of the first type without index signature
52880                     if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
52881                         break;
52882                     }
52883                 }
52884                 type.resolvedProperties = getNamedMembers(members);
52885             }
52886             return type.resolvedProperties;
52887         }
52888         function getPropertiesOfType(type) {
52889             type = getReducedApparentType(type);
52890             return type.flags & 3145728 /* UnionOrIntersection */ ?
52891                 getPropertiesOfUnionOrIntersectionType(type) :
52892                 getPropertiesOfObjectType(type);
52893         }
52894         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
52895             var list = obj.properties;
52896             return list.some(function (property) {
52897                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
52898                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
52899                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
52900                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
52901             });
52902         }
52903         function getAllPossiblePropertiesOfTypes(types) {
52904             var unionType = getUnionType(types);
52905             if (!(unionType.flags & 1048576 /* Union */)) {
52906                 return getAugmentedPropertiesOfType(unionType);
52907             }
52908             var props = ts.createSymbolTable();
52909             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
52910                 var memberType = types_5[_i];
52911                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
52912                     var escapedName = _b[_a].escapedName;
52913                     if (!props.has(escapedName)) {
52914                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
52915                         // May be undefined if the property is private
52916                         if (prop)
52917                             props.set(escapedName, prop);
52918                     }
52919                 }
52920             }
52921             return ts.arrayFrom(props.values());
52922         }
52923         function getConstraintOfType(type) {
52924             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
52925                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
52926                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
52927                         getBaseConstraintOfType(type);
52928         }
52929         function getConstraintOfTypeParameter(typeParameter) {
52930             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
52931         }
52932         function getConstraintOfIndexedAccess(type) {
52933             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
52934         }
52935         function getSimplifiedTypeOrConstraint(type) {
52936             var simplified = getSimplifiedType(type, /*writing*/ false);
52937             return simplified !== type ? simplified : getConstraintOfType(type);
52938         }
52939         function getConstraintFromIndexedAccess(type) {
52940             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
52941             if (indexConstraint && indexConstraint !== type.indexType) {
52942                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.noUncheckedIndexedAccessCandidate);
52943                 if (indexedAccess) {
52944                     return indexedAccess;
52945                 }
52946             }
52947             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
52948             if (objectConstraint && objectConstraint !== type.objectType) {
52949                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.noUncheckedIndexedAccessCandidate);
52950             }
52951             return undefined;
52952         }
52953         function getDefaultConstraintOfConditionalType(type) {
52954             if (!type.resolvedDefaultConstraint) {
52955                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
52956                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
52957                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
52958                 // in effect treating `any` like `never` rather than `unknown` in this location.
52959                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
52960                 var falseConstraint = getFalseTypeFromConditionalType(type);
52961                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
52962             }
52963             return type.resolvedDefaultConstraint;
52964         }
52965         function getConstraintOfDistributiveConditionalType(type) {
52966             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
52967             // type parameter. If so, create an instantiation of the conditional type where T is replaced
52968             // with its constraint. We do this because if the constraint is a union type it will be distributed
52969             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
52970             // removes 'undefined' from T.
52971             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
52972             // as the constraint for all type params (check type included) have been replace with `unknown`, which
52973             // is going to produce even more false positive/negative results than the distribute constraint already does.
52974             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
52975             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
52976             // likely doesn't need to exist.
52977             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
52978                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
52979                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
52980                 if (constraint && constraint !== type.checkType) {
52981                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
52982                     if (!(instantiated.flags & 131072 /* Never */)) {
52983                         return instantiated;
52984                     }
52985                 }
52986             }
52987             return undefined;
52988         }
52989         function getConstraintFromConditionalType(type) {
52990             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
52991         }
52992         function getConstraintOfConditionalType(type) {
52993             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
52994         }
52995         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
52996             var constraints;
52997             var hasDisjointDomainType = false;
52998             for (var _i = 0, types_6 = types; _i < types_6.length; _i++) {
52999                 var t = types_6[_i];
53000                 if (t.flags & 465829888 /* Instantiable */) {
53001                     // We keep following constraints as long as we have an instantiable type that is known
53002                     // not to be circular or infinite (hence we stop on index access types).
53003                     var constraint = getConstraintOfType(t);
53004                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
53005                         constraint = getConstraintOfType(constraint);
53006                     }
53007                     if (constraint) {
53008                         constraints = ts.append(constraints, constraint);
53009                         if (targetIsUnion) {
53010                             constraints = ts.append(constraints, t);
53011                         }
53012                     }
53013                 }
53014                 else if (t.flags & 469892092 /* DisjointDomains */) {
53015                     hasDisjointDomainType = true;
53016                 }
53017             }
53018             // If the target is a union type or if we are intersecting with types belonging to one of the
53019             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
53020             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
53021                 if (hasDisjointDomainType) {
53022                     // We add any types belong to one of the disjoint domains because they might cause the final
53023                     // intersection operation to reduce the union constraints.
53024                     for (var _a = 0, types_7 = types; _a < types_7.length; _a++) {
53025                         var t = types_7[_a];
53026                         if (t.flags & 469892092 /* DisjointDomains */) {
53027                             constraints = ts.append(constraints, t);
53028                         }
53029                     }
53030                 }
53031                 return getIntersectionType(constraints);
53032             }
53033             return undefined;
53034         }
53035         function getBaseConstraintOfType(type) {
53036             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) {
53037                 var constraint = getResolvedBaseConstraint(type);
53038                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
53039             }
53040             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
53041         }
53042         /**
53043          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
53044          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
53045          */
53046         function getBaseConstraintOrType(type) {
53047             return getBaseConstraintOfType(type) || type;
53048         }
53049         function hasNonCircularBaseConstraint(type) {
53050             return getResolvedBaseConstraint(type) !== circularConstraintType;
53051         }
53052         /**
53053          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
53054          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
53055          * circularly references the type variable.
53056          */
53057         function getResolvedBaseConstraint(type) {
53058             if (type.resolvedBaseConstraint) {
53059                 return type.resolvedBaseConstraint;
53060             }
53061             var nonTerminating = false;
53062             var stack = [];
53063             return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type);
53064             function getImmediateBaseConstraint(t) {
53065                 if (!t.immediateBaseConstraint) {
53066                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
53067                         return circularConstraintType;
53068                     }
53069                     if (constraintDepth >= 50) {
53070                         // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
53071                         // very high likelihood we're dealing with an infinite generic type that perpetually generates
53072                         // new type identities as we descend into it. We stop the recursion here and mark this type
53073                         // and the outer types as having circular constraints.
53074                         ts.tracing.instant("check" /* Check */, "getImmediateBaseConstraint_DepthLimit", { typeId: t.id, originalTypeId: type.id, depth: constraintDepth });
53075                         error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
53076                         nonTerminating = true;
53077                         return t.immediateBaseConstraint = noConstraintType;
53078                     }
53079                     var result = void 0;
53080                     if (!isDeeplyNestedType(t, stack, stack.length)) {
53081                         stack.push(t);
53082                         constraintDepth++;
53083                         result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
53084                         constraintDepth--;
53085                         stack.pop();
53086                     }
53087                     if (!popTypeResolution()) {
53088                         if (t.flags & 262144 /* TypeParameter */) {
53089                             var errorNode = getConstraintDeclaration(t);
53090                             if (errorNode) {
53091                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
53092                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
53093                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
53094                                 }
53095                             }
53096                         }
53097                         result = circularConstraintType;
53098                     }
53099                     if (nonTerminating) {
53100                         result = circularConstraintType;
53101                     }
53102                     t.immediateBaseConstraint = result || noConstraintType;
53103                 }
53104                 return t.immediateBaseConstraint;
53105             }
53106             function getBaseConstraint(t) {
53107                 var c = getImmediateBaseConstraint(t);
53108                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
53109             }
53110             function computeBaseConstraint(t) {
53111                 if (t.flags & 262144 /* TypeParameter */) {
53112                     var constraint = getConstraintFromTypeParameter(t);
53113                     return t.isThisType || !constraint ?
53114                         constraint :
53115                         getBaseConstraint(constraint);
53116                 }
53117                 if (t.flags & 3145728 /* UnionOrIntersection */) {
53118                     var types = t.types;
53119                     var baseTypes = [];
53120                     for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
53121                         var type_3 = types_8[_i];
53122                         var baseType = getBaseConstraint(type_3);
53123                         if (baseType) {
53124                             baseTypes.push(baseType);
53125                         }
53126                     }
53127                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
53128                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
53129                             undefined;
53130                 }
53131                 if (t.flags & 4194304 /* Index */) {
53132                     return keyofConstraintType;
53133                 }
53134                 if (t.flags & 134217728 /* TemplateLiteral */) {
53135                     var types = t.types;
53136                     var constraints = ts.mapDefined(types, getBaseConstraint);
53137                     return constraints.length === types.length ? getTemplateLiteralType(t.texts, constraints) : stringType;
53138                 }
53139                 if (t.flags & 268435456 /* StringMapping */) {
53140                     var constraint = getBaseConstraint(t.type);
53141                     return constraint ? getStringMappingType(t.symbol, constraint) : stringType;
53142                 }
53143                 if (t.flags & 8388608 /* IndexedAccess */) {
53144                     var baseObjectType = getBaseConstraint(t.objectType);
53145                     var baseIndexType = getBaseConstraint(t.indexType);
53146                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.noUncheckedIndexedAccessCandidate);
53147                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
53148                 }
53149                 if (t.flags & 16777216 /* Conditional */) {
53150                     var constraint = getConstraintFromConditionalType(t);
53151                     constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
53152                     var result = constraint && getBaseConstraint(constraint);
53153                     constraintDepth--;
53154                     return result;
53155                 }
53156                 if (t.flags & 33554432 /* Substitution */) {
53157                     return getBaseConstraint(t.substitute);
53158                 }
53159                 return t;
53160             }
53161         }
53162         function getApparentTypeOfIntersectionType(type) {
53163             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
53164         }
53165         function getResolvedTypeParameterDefault(typeParameter) {
53166             if (!typeParameter.default) {
53167                 if (typeParameter.target) {
53168                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
53169                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
53170                 }
53171                 else {
53172                     // To block recursion, set the initial value to the resolvingDefaultType.
53173                     typeParameter.default = resolvingDefaultType;
53174                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
53175                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
53176                     if (typeParameter.default === resolvingDefaultType) {
53177                         // If we have not been called recursively, set the correct default type.
53178                         typeParameter.default = defaultType;
53179                     }
53180                 }
53181             }
53182             else if (typeParameter.default === resolvingDefaultType) {
53183                 // If we are called recursively for this type parameter, mark the default as circular.
53184                 typeParameter.default = circularConstraintType;
53185             }
53186             return typeParameter.default;
53187         }
53188         /**
53189          * Gets the default type for a type parameter.
53190          *
53191          * If the type parameter is the result of an instantiation, this gets the instantiated
53192          * default type of its target. If the type parameter has no default type or the default is
53193          * circular, `undefined` is returned.
53194          */
53195         function getDefaultFromTypeParameter(typeParameter) {
53196             var defaultType = getResolvedTypeParameterDefault(typeParameter);
53197             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
53198         }
53199         function hasNonCircularTypeParameterDefault(typeParameter) {
53200             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
53201         }
53202         /**
53203          * Indicates whether the declaration of a typeParameter has a default type.
53204          */
53205         function hasTypeParameterDefault(typeParameter) {
53206             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
53207         }
53208         function getApparentTypeOfMappedType(type) {
53209             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
53210         }
53211         function getResolvedApparentTypeOfMappedType(type) {
53212             var typeVariable = getHomomorphicTypeVariable(type);
53213             if (typeVariable && !type.declaration.nameType) {
53214                 var constraint = getConstraintOfTypeParameter(typeVariable);
53215                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
53216                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
53217                 }
53218             }
53219             return type;
53220         }
53221         /**
53222          * For a type parameter, return the base constraint of the type parameter. For the string, number,
53223          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
53224          * type itself.
53225          */
53226         function getApparentType(type) {
53227             var t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
53228             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
53229                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
53230                     t.flags & 402653316 /* StringLike */ ? globalStringType :
53231                         t.flags & 296 /* NumberLike */ ? globalNumberType :
53232                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
53233                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
53234                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
53235                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
53236                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
53237                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
53238                                                     t;
53239         }
53240         function getReducedApparentType(type) {
53241             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
53242             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
53243             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
53244             // that type may need further reduction to remove empty intersections.
53245             return getReducedType(getApparentType(getReducedType(type)));
53246         }
53247         function createUnionOrIntersectionProperty(containingType, name) {
53248             var singleProp;
53249             var propSet;
53250             var indexTypes;
53251             var isUnion = containingType.flags & 1048576 /* Union */;
53252             // Flags we want to propagate to the result if they exist in all source symbols
53253             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
53254             var syntheticFlag = 4 /* SyntheticMethod */;
53255             var checkFlags = 0;
53256             for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
53257                 var current = _a[_i];
53258                 var type = getApparentType(current);
53259                 if (!(type === errorType || type.flags & 131072 /* Never */)) {
53260                     var prop = getPropertyOfType(type, name);
53261                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
53262                     if (prop) {
53263                         if (isUnion) {
53264                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
53265                         }
53266                         else {
53267                             optionalFlag &= prop.flags;
53268                         }
53269                         if (!singleProp) {
53270                             singleProp = prop;
53271                         }
53272                         else if (prop !== singleProp) {
53273                             if (!propSet) {
53274                                 propSet = new ts.Map();
53275                                 propSet.set(getSymbolId(singleProp), singleProp);
53276                             }
53277                             var id = getSymbolId(prop);
53278                             if (!propSet.has(id)) {
53279                                 propSet.set(id, prop);
53280                             }
53281                         }
53282                         checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
53283                             (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
53284                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
53285                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
53286                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
53287                         if (!isPrototypeProperty(prop)) {
53288                             syntheticFlag = 2 /* SyntheticProperty */;
53289                         }
53290                     }
53291                     else if (isUnion) {
53292                         var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
53293                         if (indexInfo) {
53294                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
53295                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
53296                         }
53297                         else if (isObjectLiteralType(type)) {
53298                             checkFlags |= 32 /* WritePartial */;
53299                             indexTypes = ts.append(indexTypes, undefinedType);
53300                         }
53301                         else {
53302                             checkFlags |= 16 /* ReadPartial */;
53303                         }
53304                     }
53305                 }
53306             }
53307             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
53308                 // No property was found, or, in a union, a property has a private or protected declaration in one
53309                 // constituent, but is missing or has a different declaration in another constituent.
53310                 return undefined;
53311             }
53312             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
53313                 return singleProp;
53314             }
53315             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
53316             var declarations;
53317             var firstType;
53318             var nameType;
53319             var propTypes = [];
53320             var firstValueDeclaration;
53321             var hasNonUniformValueDeclaration = false;
53322             for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
53323                 var prop = props_1[_b];
53324                 if (!firstValueDeclaration) {
53325                     firstValueDeclaration = prop.valueDeclaration;
53326                 }
53327                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
53328                     hasNonUniformValueDeclaration = true;
53329                 }
53330                 declarations = ts.addRange(declarations, prop.declarations);
53331                 var type = getTypeOfSymbol(prop);
53332                 if (!firstType) {
53333                     firstType = type;
53334                     nameType = getSymbolLinks(prop).nameType;
53335                 }
53336                 else if (type !== firstType) {
53337                     checkFlags |= 64 /* HasNonUniformType */;
53338                 }
53339                 if (isLiteralType(type)) {
53340                     checkFlags |= 128 /* HasLiteralType */;
53341                 }
53342                 if (type.flags & 131072 /* Never */) {
53343                     checkFlags |= 131072 /* HasNeverType */;
53344                 }
53345                 propTypes.push(type);
53346             }
53347             ts.addRange(propTypes, indexTypes);
53348             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
53349             result.containingType = containingType;
53350             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
53351                 result.valueDeclaration = firstValueDeclaration;
53352                 // Inherit information about parent type.
53353                 if (firstValueDeclaration.symbol.parent) {
53354                     result.parent = firstValueDeclaration.symbol.parent;
53355                 }
53356             }
53357             result.declarations = declarations;
53358             result.nameType = nameType;
53359             if (propTypes.length > 2) {
53360                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
53361                 result.checkFlags |= 65536 /* DeferredType */;
53362                 result.deferralParent = containingType;
53363                 result.deferralConstituents = propTypes;
53364             }
53365             else {
53366                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
53367             }
53368             return result;
53369         }
53370         // Return the symbol for a given property in a union or intersection type, or undefined if the property
53371         // does not exist in any constituent type. Note that the returned property may only be present in some
53372         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
53373         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
53374         // and do not appear to be present in the union type.
53375         function getUnionOrIntersectionProperty(type, name) {
53376             var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
53377             var property = properties.get(name);
53378             if (!property) {
53379                 property = createUnionOrIntersectionProperty(type, name);
53380                 if (property) {
53381                     properties.set(name, property);
53382                 }
53383             }
53384             return property;
53385         }
53386         function getPropertyOfUnionOrIntersectionType(type, name) {
53387             var property = getUnionOrIntersectionProperty(type, name);
53388             // We need to filter out partial properties in union types
53389             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
53390         }
53391         /**
53392          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
53393          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
53394          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
53395          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
53396          */
53397         function getReducedType(type) {
53398             if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
53399                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
53400             }
53401             else if (type.flags & 2097152 /* Intersection */) {
53402                 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
53403                     type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
53404                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
53405                 }
53406                 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
53407             }
53408             return type;
53409         }
53410         function getReducedUnionType(unionType) {
53411             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
53412             if (reducedTypes === unionType.types) {
53413                 return unionType;
53414             }
53415             var reduced = getUnionType(reducedTypes);
53416             if (reduced.flags & 1048576 /* Union */) {
53417                 reduced.resolvedReducedType = reduced;
53418             }
53419             return reduced;
53420         }
53421         function isNeverReducedProperty(prop) {
53422             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
53423         }
53424         function isDiscriminantWithNeverType(prop) {
53425             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
53426             // a literal type and none is never, that reduces to never.
53427             return !(prop.flags & 16777216 /* Optional */) &&
53428                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
53429                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
53430         }
53431         function isConflictingPrivateProperty(prop) {
53432             // Return true for a synthetic property with multiple declarations, at least one of which is private.
53433             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
53434         }
53435         function elaborateNeverIntersection(errorInfo, type) {
53436             if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
53437                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
53438                 if (neverProp) {
53439                     return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp));
53440                 }
53441                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
53442                 if (privateProp) {
53443                     return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(privateProp));
53444                 }
53445             }
53446             return errorInfo;
53447         }
53448         /**
53449          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
53450          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
53451          * Object and Function as appropriate.
53452          *
53453          * @param type a type to look up property from
53454          * @param name a name of property to look up in a given type
53455          */
53456         function getPropertyOfType(type, name) {
53457             type = getReducedApparentType(type);
53458             if (type.flags & 524288 /* Object */) {
53459                 var resolved = resolveStructuredTypeMembers(type);
53460                 var symbol = resolved.members.get(name);
53461                 if (symbol && symbolIsValue(symbol)) {
53462                     return symbol;
53463                 }
53464                 var functionType = resolved === anyFunctionType ? globalFunctionType :
53465                     resolved.callSignatures.length ? globalCallableFunctionType :
53466                         resolved.constructSignatures.length ? globalNewableFunctionType :
53467                             undefined;
53468                 if (functionType) {
53469                     var symbol_1 = getPropertyOfObjectType(functionType, name);
53470                     if (symbol_1) {
53471                         return symbol_1;
53472                     }
53473                 }
53474                 return getPropertyOfObjectType(globalObjectType, name);
53475             }
53476             if (type.flags & 3145728 /* UnionOrIntersection */) {
53477                 return getPropertyOfUnionOrIntersectionType(type, name);
53478             }
53479             return undefined;
53480         }
53481         function getSignaturesOfStructuredType(type, kind) {
53482             if (type.flags & 3670016 /* StructuredType */) {
53483                 var resolved = resolveStructuredTypeMembers(type);
53484                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
53485             }
53486             return ts.emptyArray;
53487         }
53488         /**
53489          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
53490          * maps primitive types and type parameters are to their apparent types.
53491          */
53492         function getSignaturesOfType(type, kind) {
53493             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
53494         }
53495         function getIndexInfoOfStructuredType(type, kind) {
53496             if (type.flags & 3670016 /* StructuredType */) {
53497                 var resolved = resolveStructuredTypeMembers(type);
53498                 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
53499             }
53500         }
53501         function getIndexTypeOfStructuredType(type, kind) {
53502             var info = getIndexInfoOfStructuredType(type, kind);
53503             return info && info.type;
53504         }
53505         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
53506         // maps primitive types and type parameters are to their apparent types.
53507         function getIndexInfoOfType(type, kind) {
53508             return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
53509         }
53510         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
53511         // maps primitive types and type parameters are to their apparent types.
53512         function getIndexTypeOfType(type, kind) {
53513             return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
53514         }
53515         function getImplicitIndexTypeOfType(type, kind) {
53516             if (isObjectTypeWithInferableIndex(type)) {
53517                 var propTypes = [];
53518                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
53519                     var prop = _a[_i];
53520                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
53521                         propTypes.push(getTypeOfSymbol(prop));
53522                     }
53523                 }
53524                 if (kind === 0 /* String */) {
53525                     ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
53526                 }
53527                 if (propTypes.length) {
53528                     return getUnionType(propTypes);
53529                 }
53530             }
53531             return undefined;
53532         }
53533         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
53534         // type checking functions).
53535         function getTypeParametersFromDeclaration(declaration) {
53536             var result;
53537             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
53538                 var node = _a[_i];
53539                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
53540             }
53541             return result;
53542         }
53543         function symbolsToArray(symbols) {
53544             var result = [];
53545             symbols.forEach(function (symbol, id) {
53546                 if (!isReservedMemberName(id)) {
53547                     result.push(symbol);
53548                 }
53549             });
53550             return result;
53551         }
53552         function isJSDocOptionalParameter(node) {
53553             return ts.isInJSFile(node) && (
53554             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
53555             node.type && node.type.kind === 307 /* JSDocOptionalType */
53556                 || ts.getJSDocParameterTags(node).some(function (_a) {
53557                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
53558                     return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */;
53559                 }));
53560         }
53561         function tryFindAmbientModule(moduleName, withAugmentations) {
53562             if (ts.isExternalModuleNameRelative(moduleName)) {
53563                 return undefined;
53564             }
53565             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
53566             // merged symbol is module declaration symbol combined with all augmentations
53567             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
53568         }
53569         function isOptionalParameter(node) {
53570             if (ts.hasQuestionToken(node) || isOptionalJSDocPropertyLikeTag(node) || isJSDocOptionalParameter(node)) {
53571                 return true;
53572             }
53573             if (node.initializer) {
53574                 var signature = getSignatureFromDeclaration(node.parent);
53575                 var parameterIndex = node.parent.parameters.indexOf(node);
53576                 ts.Debug.assert(parameterIndex >= 0);
53577                 // Only consider syntactic or instantiated parameters as optional, not `void` parameters as this function is used
53578                 // in grammar checks and checking for `void` too early results in parameter types widening too early
53579                 // and causes some noImplicitAny errors to be lost.
53580                 return parameterIndex >= getMinArgumentCount(signature, 1 /* StrongArityForUntypedJS */ | 2 /* VoidIsNonOptional */);
53581             }
53582             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
53583             if (iife) {
53584                 return !node.type &&
53585                     !node.dotDotDotToken &&
53586                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
53587             }
53588             return false;
53589         }
53590         function isOptionalJSDocPropertyLikeTag(node) {
53591             if (!ts.isJSDocPropertyLikeTag(node)) {
53592                 return false;
53593             }
53594             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
53595             return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */;
53596         }
53597         function createTypePredicate(kind, parameterName, parameterIndex, type) {
53598             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
53599         }
53600         /**
53601          * Gets the minimum number of type arguments needed to satisfy all non-optional type
53602          * parameters.
53603          */
53604         function getMinTypeArgumentCount(typeParameters) {
53605             var minTypeArgumentCount = 0;
53606             if (typeParameters) {
53607                 for (var i = 0; i < typeParameters.length; i++) {
53608                     if (!hasTypeParameterDefault(typeParameters[i])) {
53609                         minTypeArgumentCount = i + 1;
53610                     }
53611                 }
53612             }
53613             return minTypeArgumentCount;
53614         }
53615         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
53616             var numTypeParameters = ts.length(typeParameters);
53617             if (!numTypeParameters) {
53618                 return [];
53619             }
53620             var numTypeArguments = ts.length(typeArguments);
53621             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
53622                 var result = typeArguments ? typeArguments.slice() : [];
53623                 // Map invalid forward references in default types to the error type
53624                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
53625                     result[i] = errorType;
53626                 }
53627                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
53628                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
53629                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
53630                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
53631                         defaultType = anyType;
53632                     }
53633                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
53634                 }
53635                 result.length = typeParameters.length;
53636                 return result;
53637             }
53638             return typeArguments && typeArguments.slice();
53639         }
53640         function getSignatureFromDeclaration(declaration) {
53641             var links = getNodeLinks(declaration);
53642             if (!links.resolvedSignature) {
53643                 var parameters = [];
53644                 var flags = 0 /* None */;
53645                 var minArgumentCount = 0;
53646                 var thisParameter = void 0;
53647                 var hasThisParameter = false;
53648                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
53649                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
53650                 var isUntypedSignatureInJSFile = !iife &&
53651                     ts.isInJSFile(declaration) &&
53652                     ts.isValueSignatureDeclaration(declaration) &&
53653                     !ts.hasJSDocParameterTags(declaration) &&
53654                     !ts.getJSDocType(declaration);
53655                 if (isUntypedSignatureInJSFile) {
53656                     flags |= 16 /* IsUntypedSignatureInJSFile */;
53657                 }
53658                 // If this is a JSDoc construct signature, then skip the first parameter in the
53659                 // parameter list.  The first parameter represents the return type of the construct
53660                 // signature.
53661                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
53662                     var param = declaration.parameters[i];
53663                     var paramSymbol = param.symbol;
53664                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
53665                     // Include parameter symbol instead of property symbol in the signature
53666                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
53667                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
53668                         paramSymbol = resolvedSymbol;
53669                     }
53670                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
53671                         hasThisParameter = true;
53672                         thisParameter = param.symbol;
53673                     }
53674                     else {
53675                         parameters.push(paramSymbol);
53676                     }
53677                     if (type && type.kind === 191 /* LiteralType */) {
53678                         flags |= 2 /* HasLiteralTypes */;
53679                     }
53680                     // Record a new minimum argument count if this is not an optional parameter
53681                     var isOptionalParameter_1 = isOptionalJSDocPropertyLikeTag(param) ||
53682                         param.initializer || param.questionToken || param.dotDotDotToken ||
53683                         iife && parameters.length > iife.arguments.length && !type ||
53684                         isJSDocOptionalParameter(param);
53685                     if (!isOptionalParameter_1) {
53686                         minArgumentCount = parameters.length;
53687                     }
53688                 }
53689                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
53690                 if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) &&
53691                     !hasNonBindableDynamicName(declaration) &&
53692                     (!hasThisParameter || !thisParameter)) {
53693                     var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
53694                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
53695                     if (other) {
53696                         thisParameter = getAnnotatedAccessorThisParameter(other);
53697                     }
53698                 }
53699                 var classType = declaration.kind === 166 /* Constructor */ ?
53700                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
53701                     : undefined;
53702                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
53703                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
53704                     flags |= 1 /* HasRestParameter */;
53705                 }
53706                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
53707                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
53708             }
53709             return links.resolvedSignature;
53710         }
53711         /**
53712          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
53713          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
53714          * OR
53715          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
53716          */
53717         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
53718             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
53719                 return false;
53720             }
53721             var lastParam = ts.lastOrUndefined(declaration.parameters);
53722             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
53723             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
53724                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
53725             });
53726             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
53727             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
53728             if (lastParamVariadicType) {
53729                 // Replace the last parameter with a rest parameter.
53730                 parameters.pop();
53731             }
53732             parameters.push(syntheticArgsSymbol);
53733             return true;
53734         }
53735         function getSignatureOfTypeTag(node) {
53736             // should be attached to a function declaration or expression
53737             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
53738                 return undefined;
53739             var typeTag = ts.getJSDocTypeTag(node);
53740             var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
53741             return signature && getErasedSignature(signature);
53742         }
53743         function getReturnTypeOfTypeTag(node) {
53744             var signature = getSignatureOfTypeTag(node);
53745             return signature && getReturnTypeOfSignature(signature);
53746         }
53747         function containsArgumentsReference(declaration) {
53748             var links = getNodeLinks(declaration);
53749             if (links.containsArgumentsReference === undefined) {
53750                 if (links.flags & 8192 /* CaptureArguments */) {
53751                     links.containsArgumentsReference = true;
53752                 }
53753                 else {
53754                     links.containsArgumentsReference = traverse(declaration.body);
53755                 }
53756             }
53757             return links.containsArgumentsReference;
53758             function traverse(node) {
53759                 if (!node)
53760                     return false;
53761                 switch (node.kind) {
53762                     case 78 /* Identifier */:
53763                         return node.escapedText === "arguments" && ts.isExpressionNode(node);
53764                     case 163 /* PropertyDeclaration */:
53765                     case 165 /* MethodDeclaration */:
53766                     case 167 /* GetAccessor */:
53767                     case 168 /* SetAccessor */:
53768                         return node.name.kind === 158 /* ComputedPropertyName */
53769                             && traverse(node.name);
53770                     default:
53771                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
53772                 }
53773             }
53774         }
53775         function getSignaturesOfSymbol(symbol) {
53776             if (!symbol)
53777                 return ts.emptyArray;
53778             var result = [];
53779             for (var i = 0; i < symbol.declarations.length; i++) {
53780                 var decl = symbol.declarations[i];
53781                 if (!ts.isFunctionLike(decl))
53782                     continue;
53783                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
53784                 // an implementation node if it has a body and the previous node is of the same kind and immediately
53785                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
53786                 if (i > 0 && decl.body) {
53787                     var previous = symbol.declarations[i - 1];
53788                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
53789                         continue;
53790                     }
53791                 }
53792                 result.push(getSignatureFromDeclaration(decl));
53793             }
53794             return result;
53795         }
53796         function resolveExternalModuleTypeByLiteral(name) {
53797             var moduleSym = resolveExternalModuleName(name, name);
53798             if (moduleSym) {
53799                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
53800                 if (resolvedModuleSymbol) {
53801                     return getTypeOfSymbol(resolvedModuleSymbol);
53802                 }
53803             }
53804             return anyType;
53805         }
53806         function getThisTypeOfSignature(signature) {
53807             if (signature.thisParameter) {
53808                 return getTypeOfSymbol(signature.thisParameter);
53809             }
53810         }
53811         function getTypePredicateOfSignature(signature) {
53812             if (!signature.resolvedTypePredicate) {
53813                 if (signature.target) {
53814                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
53815                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
53816                 }
53817                 else if (signature.unionSignatures) {
53818                     signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
53819                 }
53820                 else {
53821                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
53822                     var jsdocPredicate = void 0;
53823                     if (!type && ts.isInJSFile(signature.declaration)) {
53824                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
53825                         if (jsdocSignature && signature !== jsdocSignature) {
53826                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
53827                         }
53828                     }
53829                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
53830                         createTypePredicateFromTypePredicateNode(type, signature) :
53831                         jsdocPredicate || noTypePredicate;
53832                 }
53833                 ts.Debug.assert(!!signature.resolvedTypePredicate);
53834             }
53835             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
53836         }
53837         function createTypePredicateFromTypePredicateNode(node, signature) {
53838             var parameterName = node.parameterName;
53839             var type = node.type && getTypeFromTypeNode(node.type);
53840             return parameterName.kind === 187 /* ThisType */ ?
53841                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
53842                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
53843         }
53844         function getReturnTypeOfSignature(signature) {
53845             if (!signature.resolvedReturnType) {
53846                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
53847                     return errorType;
53848                 }
53849                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
53850                     signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
53851                         getReturnTypeFromAnnotation(signature.declaration) ||
53852                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
53853                 if (signature.flags & 4 /* IsInnerCallChain */) {
53854                     type = addOptionalTypeMarker(type);
53855                 }
53856                 else if (signature.flags & 8 /* IsOuterCallChain */) {
53857                     type = getOptionalType(type);
53858                 }
53859                 if (!popTypeResolution()) {
53860                     if (signature.declaration) {
53861                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
53862                         if (typeNode) {
53863                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
53864                         }
53865                         else if (noImplicitAny) {
53866                             var declaration = signature.declaration;
53867                             var name = ts.getNameOfDeclaration(declaration);
53868                             if (name) {
53869                                 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));
53870                             }
53871                             else {
53872                                 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);
53873                             }
53874                         }
53875                     }
53876                     type = anyType;
53877                 }
53878                 signature.resolvedReturnType = type;
53879             }
53880             return signature.resolvedReturnType;
53881         }
53882         function getReturnTypeFromAnnotation(declaration) {
53883             if (declaration.kind === 166 /* Constructor */) {
53884                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
53885             }
53886             if (ts.isJSDocConstructSignature(declaration)) {
53887                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
53888             }
53889             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
53890             if (typeNode) {
53891                 return getTypeFromTypeNode(typeNode);
53892             }
53893             if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
53894                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
53895                 if (jsDocType) {
53896                     return jsDocType;
53897                 }
53898                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 168 /* SetAccessor */);
53899                 var setterType = getAnnotatedAccessorType(setter);
53900                 if (setterType) {
53901                     return setterType;
53902                 }
53903             }
53904             return getReturnTypeOfTypeTag(declaration);
53905         }
53906         function isResolvingReturnTypeOfSignature(signature) {
53907             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
53908         }
53909         function getRestTypeOfSignature(signature) {
53910             return tryGetRestTypeOfSignature(signature) || anyType;
53911         }
53912         function tryGetRestTypeOfSignature(signature) {
53913             if (signatureHasRestParameter(signature)) {
53914                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
53915                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
53916                 return restType && getIndexTypeOfType(restType, 1 /* Number */);
53917             }
53918             return undefined;
53919         }
53920         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
53921             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
53922             if (inferredTypeParameters) {
53923                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
53924                 if (returnSignature) {
53925                     var newReturnSignature = cloneSignature(returnSignature);
53926                     newReturnSignature.typeParameters = inferredTypeParameters;
53927                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
53928                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
53929                     return newInstantiatedSignature;
53930                 }
53931             }
53932             return instantiatedSignature;
53933         }
53934         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
53935             var instantiations = signature.instantiations || (signature.instantiations = new ts.Map());
53936             var id = getTypeListId(typeArguments);
53937             var instantiation = instantiations.get(id);
53938             if (!instantiation) {
53939                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
53940             }
53941             return instantiation;
53942         }
53943         function createSignatureInstantiation(signature, typeArguments) {
53944             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
53945         }
53946         function createSignatureTypeMapper(signature, typeArguments) {
53947             return createTypeMapper(signature.typeParameters, typeArguments);
53948         }
53949         function getErasedSignature(signature) {
53950             return signature.typeParameters ?
53951                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
53952                 signature;
53953         }
53954         function createErasedSignature(signature) {
53955             // Create an instantiation of the signature where all type arguments are the any type.
53956             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
53957         }
53958         function getCanonicalSignature(signature) {
53959             return signature.typeParameters ?
53960                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
53961                 signature;
53962         }
53963         function createCanonicalSignature(signature) {
53964             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
53965             // its original. When a generic class or interface is instantiated, each generic method in the class or
53966             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
53967             // where different generations of the same type parameter are in scope). This leads to a lot of new type
53968             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
53969             // that uses the original type identities for all unconstrained type parameters.
53970             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
53971         }
53972         function getBaseSignature(signature) {
53973             var typeParameters = signature.typeParameters;
53974             if (typeParameters) {
53975                 var typeEraser_1 = createTypeEraser(typeParameters);
53976                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
53977                 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
53978             }
53979             return signature;
53980         }
53981         function getOrCreateTypeFromSignature(signature) {
53982             // There are two ways to declare a construct signature, one is by declaring a class constructor
53983             // using the constructor keyword, and the other is declaring a bare construct signature in an
53984             // object type literal or interface (using the new keyword). Each way of declaring a constructor
53985             // will result in a different declaration kind.
53986             if (!signature.isolatedSignatureType) {
53987                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
53988                 var isConstructor = kind === 166 /* Constructor */ || kind === 170 /* ConstructSignature */ || kind === 175 /* ConstructorType */;
53989                 var type = createObjectType(16 /* Anonymous */);
53990                 type.members = emptySymbols;
53991                 type.properties = ts.emptyArray;
53992                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
53993                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
53994                 signature.isolatedSignatureType = type;
53995             }
53996             return signature.isolatedSignatureType;
53997         }
53998         function getIndexSymbol(symbol) {
53999             return symbol.members.get("__index" /* Index */);
54000         }
54001         function getIndexDeclarationOfSymbol(symbol, kind) {
54002             var syntaxKind = kind === 1 /* Number */ ? 144 /* NumberKeyword */ : 147 /* StringKeyword */;
54003             var indexSymbol = getIndexSymbol(symbol);
54004             if (indexSymbol) {
54005                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
54006                     var decl = _a[_i];
54007                     var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
54008                     if (node.parameters.length === 1) {
54009                         var parameter = node.parameters[0];
54010                         if (parameter.type && parameter.type.kind === syntaxKind) {
54011                             return node;
54012                         }
54013                     }
54014                 }
54015             }
54016             return undefined;
54017         }
54018         function createIndexInfo(type, isReadonly, declaration) {
54019             return { type: type, isReadonly: isReadonly, declaration: declaration };
54020         }
54021         function getIndexInfoOfSymbol(symbol, kind) {
54022             var declaration = getIndexDeclarationOfSymbol(symbol, kind);
54023             if (declaration) {
54024                 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration);
54025             }
54026             return undefined;
54027         }
54028         function getConstraintDeclaration(type) {
54029             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
54030         }
54031         function getInferredTypeParameterConstraint(typeParameter) {
54032             var inferences;
54033             if (typeParameter.symbol) {
54034                 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
54035                     var declaration = _a[_i];
54036                     if (declaration.parent.kind === 185 /* InferType */) {
54037                         // When an 'infer T' declaration is immediately contained in a type reference node
54038                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
54039                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
54040                         // present, we form an intersection of the inferred constraint types.
54041                         var _b = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _c = _b[0], childTypeParameter = _c === void 0 ? declaration.parent : _c, grandParent = _b[1];
54042                         if (grandParent.kind === 173 /* TypeReference */) {
54043                             var typeReference = grandParent;
54044                             var typeParameters = getTypeParametersForTypeReference(typeReference);
54045                             if (typeParameters) {
54046                                 var index = typeReference.typeArguments.indexOf(childTypeParameter);
54047                                 if (index < typeParameters.length) {
54048                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
54049                                     if (declaredConstraint) {
54050                                         // Type parameter constraints can reference other type parameters so
54051                                         // constraints need to be instantiated. If instantiation produces the
54052                                         // type parameter itself, we discard that inference. For example, in
54053                                         //   type Foo<T extends string, U extends T> = [T, U];
54054                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
54055                                         // the instantiated constraint for U is X, so we discard that inference.
54056                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
54057                                         var constraint = instantiateType(declaredConstraint, mapper);
54058                                         if (constraint !== typeParameter) {
54059                                             inferences = ts.append(inferences, constraint);
54060                                         }
54061                                     }
54062                                 }
54063                             }
54064                         }
54065                         // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type
54066                         // or a named rest tuple element, we infer an 'unknown[]' constraint.
54067                         else if (grandParent.kind === 160 /* Parameter */ && grandParent.dotDotDotToken ||
54068                             grandParent.kind === 181 /* RestType */ ||
54069                             grandParent.kind === 192 /* NamedTupleMember */ && grandParent.dotDotDotToken) {
54070                             inferences = ts.append(inferences, createArrayType(unknownType));
54071                         }
54072                         // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string'
54073                         // constraint.
54074                         else if (grandParent.kind === 194 /* TemplateLiteralTypeSpan */) {
54075                             inferences = ts.append(inferences, stringType);
54076                         }
54077                     }
54078                 }
54079             }
54080             return inferences && getIntersectionType(inferences);
54081         }
54082         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
54083         function getConstraintFromTypeParameter(typeParameter) {
54084             if (!typeParameter.constraint) {
54085                 if (typeParameter.target) {
54086                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
54087                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
54088                 }
54089                 else {
54090                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
54091                     if (!constraintDeclaration) {
54092                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
54093                     }
54094                     else {
54095                         var type = getTypeFromTypeNode(constraintDeclaration);
54096                         if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
54097                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
54098                             // use unknown otherwise
54099                             type = constraintDeclaration.parent.parent.kind === 190 /* MappedType */ ? keyofConstraintType : unknownType;
54100                         }
54101                         typeParameter.constraint = type;
54102                     }
54103                 }
54104             }
54105             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
54106         }
54107         function getParentSymbolOfTypeParameter(typeParameter) {
54108             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 159 /* TypeParameter */);
54109             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
54110             return host && getSymbolOfNode(host);
54111         }
54112         function getTypeListId(types) {
54113             var result = "";
54114             if (types) {
54115                 var length_4 = types.length;
54116                 var i = 0;
54117                 while (i < length_4) {
54118                     var startId = types[i].id;
54119                     var count = 1;
54120                     while (i + count < length_4 && types[i + count].id === startId + count) {
54121                         count++;
54122                     }
54123                     if (result.length) {
54124                         result += ",";
54125                     }
54126                     result += startId;
54127                     if (count > 1) {
54128                         result += ":" + count;
54129                     }
54130                     i += count;
54131                 }
54132             }
54133             return result;
54134         }
54135         // This function is used to propagate certain flags when creating new object type references and union types.
54136         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
54137         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
54138         // that care about the presence of such types at arbitrary depth in a containing type.
54139         function getPropagatingFlagsOfTypes(types, excludeKinds) {
54140             var result = 0;
54141             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
54142                 var type = types_9[_i];
54143                 if (!(type.flags & excludeKinds)) {
54144                     result |= ts.getObjectFlags(type);
54145                 }
54146             }
54147             return result & 3670016 /* PropagatingFlags */;
54148         }
54149         function createTypeReference(target, typeArguments) {
54150             var id = getTypeListId(typeArguments);
54151             var type = target.instantiations.get(id);
54152             if (!type) {
54153                 type = createObjectType(4 /* Reference */, target.symbol);
54154                 target.instantiations.set(id, type);
54155                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
54156                 type.target = target;
54157                 type.resolvedTypeArguments = typeArguments;
54158             }
54159             return type;
54160         }
54161         function cloneTypeReference(source) {
54162             var type = createType(source.flags);
54163             type.symbol = source.symbol;
54164             type.objectFlags = source.objectFlags;
54165             type.target = source.target;
54166             type.resolvedTypeArguments = source.resolvedTypeArguments;
54167             return type;
54168         }
54169         function createDeferredTypeReference(target, node, mapper) {
54170             var aliasSymbol = getAliasSymbolForTypeNode(node);
54171             var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
54172             var type = createObjectType(4 /* Reference */, target.symbol);
54173             type.target = target;
54174             type.node = node;
54175             type.mapper = mapper;
54176             type.aliasSymbol = aliasSymbol;
54177             type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
54178             return type;
54179         }
54180         function getTypeArguments(type) {
54181             var _a, _b;
54182             if (!type.resolvedTypeArguments) {
54183                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
54184                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
54185                 }
54186                 var node = type.node;
54187                 var typeArguments = !node ? ts.emptyArray :
54188                     node.kind === 173 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
54189                         node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
54190                             ts.map(node.elements, getTypeFromTypeNode);
54191                 if (popTypeResolution()) {
54192                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
54193                 }
54194                 else {
54195                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
54196                     error(type.node || currentNode, type.target.symbol ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol));
54197                 }
54198             }
54199             return type.resolvedTypeArguments;
54200         }
54201         function getTypeReferenceArity(type) {
54202             return ts.length(type.target.typeParameters);
54203         }
54204         /**
54205          * Get type from type-reference that reference to class or interface
54206          */
54207         function getTypeFromClassOrInterfaceReference(node, symbol) {
54208             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
54209             var typeParameters = type.localTypeParameters;
54210             if (typeParameters) {
54211                 var numTypeArguments = ts.length(node.typeArguments);
54212                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
54213                 var isJs = ts.isInJSFile(node);
54214                 var isJsImplicitAny = !noImplicitAny && isJs;
54215                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
54216                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
54217                     var diag = minTypeArgumentCount === typeParameters.length ?
54218                         missingAugmentsTag ?
54219                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
54220                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
54221                         missingAugmentsTag ?
54222                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
54223                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
54224                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
54225                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
54226                     if (!isJs) {
54227                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
54228                         return errorType;
54229                     }
54230                 }
54231                 if (node.kind === 173 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
54232                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
54233                 }
54234                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
54235                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
54236                 // of the class or interface.
54237                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
54238                 return createTypeReference(type, typeArguments);
54239             }
54240             return checkNoTypeArguments(node, symbol) ? type : errorType;
54241         }
54242         function getTypeAliasInstantiation(symbol, typeArguments) {
54243             var type = getDeclaredTypeOfSymbol(symbol);
54244             if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) {
54245                 return getStringMappingType(symbol, typeArguments[0]);
54246             }
54247             var links = getSymbolLinks(symbol);
54248             var typeParameters = links.typeParameters;
54249             var id = getTypeListId(typeArguments);
54250             var instantiation = links.instantiations.get(id);
54251             if (!instantiation) {
54252                 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
54253             }
54254             return instantiation;
54255         }
54256         /**
54257          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
54258          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
54259          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
54260          */
54261         function getTypeFromTypeAliasReference(node, symbol) {
54262             var type = getDeclaredTypeOfSymbol(symbol);
54263             var typeParameters = getSymbolLinks(symbol).typeParameters;
54264             if (typeParameters) {
54265                 var numTypeArguments = ts.length(node.typeArguments);
54266                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
54267                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
54268                     error(node, minTypeArgumentCount === typeParameters.length ?
54269                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
54270                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
54271                     return errorType;
54272                 }
54273                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
54274             }
54275             return checkNoTypeArguments(node, symbol) ? type : errorType;
54276         }
54277         function getTypeReferenceName(node) {
54278             switch (node.kind) {
54279                 case 173 /* TypeReference */:
54280                     return node.typeName;
54281                 case 223 /* ExpressionWithTypeArguments */:
54282                     // We only support expressions that are simple qualified names. For other
54283                     // expressions this produces undefined.
54284                     var expr = node.expression;
54285                     if (ts.isEntityNameExpression(expr)) {
54286                         return expr;
54287                     }
54288                 // fall through;
54289             }
54290             return undefined;
54291         }
54292         function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
54293             if (!typeReferenceName) {
54294                 return unknownSymbol;
54295             }
54296             return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
54297         }
54298         function getTypeReferenceType(node, symbol) {
54299             if (symbol === unknownSymbol) {
54300                 return errorType;
54301             }
54302             symbol = getExpandoSymbol(symbol) || symbol;
54303             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
54304                 return getTypeFromClassOrInterfaceReference(node, symbol);
54305             }
54306             if (symbol.flags & 524288 /* TypeAlias */) {
54307                 return getTypeFromTypeAliasReference(node, symbol);
54308             }
54309             // Get type from reference to named type that cannot be generic (enum or type parameter)
54310             var res = tryGetDeclaredTypeOfSymbol(symbol);
54311             if (res) {
54312                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
54313             }
54314             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
54315                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
54316                 if (jsdocType) {
54317                     return jsdocType;
54318                 }
54319                 else {
54320                     // Resolve the type reference as a Type for the purpose of reporting errors.
54321                     resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
54322                     return getTypeOfSymbol(symbol);
54323                 }
54324             }
54325             return errorType;
54326         }
54327         /**
54328          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
54329          * Example: import('./b').ConstructorFunction
54330          */
54331         function getTypeFromJSDocValueReference(node, symbol) {
54332             var links = getNodeLinks(node);
54333             if (!links.resolvedJSDocType) {
54334                 var valueType = getTypeOfSymbol(symbol);
54335                 var typeType = valueType;
54336                 if (symbol.valueDeclaration) {
54337                     var isImportTypeWithQualifier = node.kind === 195 /* ImportType */ && node.qualifier;
54338                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
54339                     if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) {
54340                         typeType = getTypeReferenceType(node, valueType.symbol);
54341                     }
54342                 }
54343                 links.resolvedJSDocType = typeType;
54344             }
54345             return links.resolvedJSDocType;
54346         }
54347         function getSubstitutionType(baseType, substitute) {
54348             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
54349                 return baseType;
54350             }
54351             var id = getTypeId(baseType) + ">" + getTypeId(substitute);
54352             var cached = substitutionTypes.get(id);
54353             if (cached) {
54354                 return cached;
54355             }
54356             var result = createType(33554432 /* Substitution */);
54357             result.baseType = baseType;
54358             result.substitute = substitute;
54359             substitutionTypes.set(id, result);
54360             return result;
54361         }
54362         function isUnaryTupleTypeNode(node) {
54363             return node.kind === 179 /* TupleType */ && node.elements.length === 1;
54364         }
54365         function getImpliedConstraint(type, checkNode, extendsNode) {
54366             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) :
54367                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
54368                     undefined;
54369         }
54370         function getConditionalFlowTypeOfType(type, node) {
54371             var constraints;
54372             while (node && !ts.isStatement(node) && node.kind !== 311 /* JSDocComment */) {
54373                 var parent = node.parent;
54374                 if (parent.kind === 184 /* ConditionalType */ && node === parent.trueType) {
54375                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
54376                     if (constraint) {
54377                         constraints = ts.append(constraints, constraint);
54378                     }
54379                 }
54380                 node = parent;
54381             }
54382             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
54383         }
54384         function isJSDocTypeReference(node) {
54385             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 173 /* TypeReference */ || node.kind === 195 /* ImportType */);
54386         }
54387         function checkNoTypeArguments(node, symbol) {
54388             if (node.typeArguments) {
54389                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
54390                 return false;
54391             }
54392             return true;
54393         }
54394         function getIntendedTypeFromJSDocTypeReference(node) {
54395             if (ts.isIdentifier(node.typeName)) {
54396                 var typeArgs = node.typeArguments;
54397                 switch (node.typeName.escapedText) {
54398                     case "String":
54399                         checkNoTypeArguments(node);
54400                         return stringType;
54401                     case "Number":
54402                         checkNoTypeArguments(node);
54403                         return numberType;
54404                     case "Boolean":
54405                         checkNoTypeArguments(node);
54406                         return booleanType;
54407                     case "Void":
54408                         checkNoTypeArguments(node);
54409                         return voidType;
54410                     case "Undefined":
54411                         checkNoTypeArguments(node);
54412                         return undefinedType;
54413                     case "Null":
54414                         checkNoTypeArguments(node);
54415                         return nullType;
54416                     case "Function":
54417                     case "function":
54418                         checkNoTypeArguments(node);
54419                         return globalFunctionType;
54420                     case "array":
54421                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
54422                     case "promise":
54423                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
54424                     case "Object":
54425                         if (typeArgs && typeArgs.length === 2) {
54426                             if (ts.isJSDocIndexSignature(node)) {
54427                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
54428                                 var target = getTypeFromTypeNode(typeArgs[1]);
54429                                 var index = createIndexInfo(target, /*isReadonly*/ false);
54430                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
54431                             }
54432                             return anyType;
54433                         }
54434                         checkNoTypeArguments(node);
54435                         return !noImplicitAny ? anyType : undefined;
54436                 }
54437             }
54438         }
54439         function getTypeFromJSDocNullableTypeNode(node) {
54440             var type = getTypeFromTypeNode(node.type);
54441             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
54442         }
54443         function getTypeFromTypeReference(node) {
54444             var links = getNodeLinks(node);
54445             if (!links.resolvedType) {
54446                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
54447                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
54448                     links.resolvedSymbol = unknownSymbol;
54449                     return links.resolvedType = checkExpressionCached(node.parent.expression);
54450                 }
54451                 var symbol = void 0;
54452                 var type = void 0;
54453                 var meaning = 788968 /* Type */;
54454                 if (isJSDocTypeReference(node)) {
54455                     type = getIntendedTypeFromJSDocTypeReference(node);
54456                     if (!type) {
54457                         symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
54458                         if (symbol === unknownSymbol) {
54459                             symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
54460                         }
54461                         else {
54462                             resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
54463                         }
54464                         type = getTypeReferenceType(node, symbol);
54465                     }
54466                 }
54467                 if (!type) {
54468                     symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
54469                     type = getTypeReferenceType(node, symbol);
54470                 }
54471                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
54472                 // type reference in checkTypeReferenceNode.
54473                 links.resolvedSymbol = symbol;
54474                 links.resolvedType = type;
54475             }
54476             return links.resolvedType;
54477         }
54478         function typeArgumentsFromTypeReferenceNode(node) {
54479             return ts.map(node.typeArguments, getTypeFromTypeNode);
54480         }
54481         function getTypeFromTypeQueryNode(node) {
54482             var links = getNodeLinks(node);
54483             if (!links.resolvedType) {
54484                 // TypeScript 1.0 spec (April 2014): 3.6.3
54485                 // The expression is processed as an identifier expression (section 4.3)
54486                 // or property access expression(section 4.10),
54487                 // the widened type(section 3.9) of which becomes the result.
54488                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
54489             }
54490             return links.resolvedType;
54491         }
54492         function getTypeOfGlobalSymbol(symbol, arity) {
54493             function getTypeDeclaration(symbol) {
54494                 var declarations = symbol.declarations;
54495                 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
54496                     var declaration = declarations_3[_i];
54497                     switch (declaration.kind) {
54498                         case 252 /* ClassDeclaration */:
54499                         case 253 /* InterfaceDeclaration */:
54500                         case 255 /* EnumDeclaration */:
54501                             return declaration;
54502                     }
54503                 }
54504             }
54505             if (!symbol) {
54506                 return arity ? emptyGenericType : emptyObjectType;
54507             }
54508             var type = getDeclaredTypeOfSymbol(symbol);
54509             if (!(type.flags & 524288 /* Object */)) {
54510                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
54511                 return arity ? emptyGenericType : emptyObjectType;
54512             }
54513             if (ts.length(type.typeParameters) !== arity) {
54514                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
54515                 return arity ? emptyGenericType : emptyObjectType;
54516             }
54517             return type;
54518         }
54519         function getGlobalValueSymbol(name, reportErrors) {
54520             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
54521         }
54522         function getGlobalTypeSymbol(name, reportErrors) {
54523             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
54524         }
54525         function getGlobalSymbol(name, meaning, diagnostic) {
54526             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
54527             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
54528         }
54529         function getGlobalType(name, arity, reportErrors) {
54530             var symbol = getGlobalTypeSymbol(name, reportErrors);
54531             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
54532         }
54533         function getGlobalTypedPropertyDescriptorType() {
54534             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
54535         }
54536         function getGlobalTemplateStringsArrayType() {
54537             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
54538         }
54539         function getGlobalImportMetaType() {
54540             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
54541         }
54542         function getGlobalESSymbolConstructorSymbol(reportErrors) {
54543             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
54544         }
54545         function getGlobalESSymbolType(reportErrors) {
54546             return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
54547         }
54548         function getGlobalPromiseType(reportErrors) {
54549             return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
54550         }
54551         function getGlobalPromiseLikeType(reportErrors) {
54552             return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
54553         }
54554         function getGlobalPromiseConstructorSymbol(reportErrors) {
54555             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
54556         }
54557         function getGlobalPromiseConstructorLikeType(reportErrors) {
54558             return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
54559         }
54560         function getGlobalAsyncIterableType(reportErrors) {
54561             return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
54562         }
54563         function getGlobalAsyncIteratorType(reportErrors) {
54564             return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
54565         }
54566         function getGlobalAsyncIterableIteratorType(reportErrors) {
54567             return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
54568         }
54569         function getGlobalAsyncGeneratorType(reportErrors) {
54570             return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
54571         }
54572         function getGlobalIterableType(reportErrors) {
54573             return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
54574         }
54575         function getGlobalIteratorType(reportErrors) {
54576             return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
54577         }
54578         function getGlobalIterableIteratorType(reportErrors) {
54579             return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
54580         }
54581         function getGlobalGeneratorType(reportErrors) {
54582             return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
54583         }
54584         function getGlobalIteratorYieldResultType(reportErrors) {
54585             return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
54586         }
54587         function getGlobalIteratorReturnResultType(reportErrors) {
54588             return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
54589         }
54590         function getGlobalTypeOrUndefined(name, arity) {
54591             if (arity === void 0) { arity = 0; }
54592             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
54593             return symbol && getTypeOfGlobalSymbol(symbol, arity);
54594         }
54595         function getGlobalExtractSymbol() {
54596             return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
54597         }
54598         function getGlobalOmitSymbol() {
54599             return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
54600         }
54601         function getGlobalBigIntType(reportErrors) {
54602             return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
54603         }
54604         /**
54605          * Instantiates a global type that is generic with some element type, and returns that instantiation.
54606          */
54607         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
54608             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
54609         }
54610         function createTypedPropertyDescriptorType(propertyType) {
54611             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
54612         }
54613         function createIterableType(iteratedType) {
54614             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
54615         }
54616         function createArrayType(elementType, readonly) {
54617             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
54618         }
54619         function getTupleElementFlags(node) {
54620             switch (node.kind) {
54621                 case 180 /* OptionalType */:
54622                     return 2 /* Optional */;
54623                 case 181 /* RestType */:
54624                     return getRestTypeElementFlags(node);
54625                 case 192 /* NamedTupleMember */:
54626                     return node.questionToken ? 2 /* Optional */ :
54627                         node.dotDotDotToken ? getRestTypeElementFlags(node) :
54628                             1 /* Required */;
54629                 default:
54630                     return 1 /* Required */;
54631             }
54632         }
54633         function getRestTypeElementFlags(node) {
54634             return getArrayElementTypeNode(node.type) ? 4 /* Rest */ : 8 /* Variadic */;
54635         }
54636         function getArrayOrTupleTargetType(node) {
54637             var readonly = isReadonlyTypeOperator(node.parent);
54638             var elementType = getArrayElementTypeNode(node);
54639             if (elementType) {
54640                 return readonly ? globalReadonlyArrayType : globalArrayType;
54641             }
54642             var elementFlags = ts.map(node.elements, getTupleElementFlags);
54643             var missingName = ts.some(node.elements, function (e) { return e.kind !== 192 /* NamedTupleMember */; });
54644             return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements);
54645         }
54646         // Return true if the given type reference node is directly aliased or if it needs to be deferred
54647         // because it is possibly contained in a circular chain of eagerly resolved types.
54648         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
54649             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 178 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
54650                 node.kind === 179 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) :
54651                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
54652         }
54653         // Return true when the given node is transitively contained in type constructs that eagerly
54654         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
54655         // of type aliases are eagerly resolved.
54656         function isResolvedByTypeAlias(node) {
54657             var parent = node.parent;
54658             switch (parent.kind) {
54659                 case 186 /* ParenthesizedType */:
54660                 case 192 /* NamedTupleMember */:
54661                 case 173 /* TypeReference */:
54662                 case 182 /* UnionType */:
54663                 case 183 /* IntersectionType */:
54664                 case 189 /* IndexedAccessType */:
54665                 case 184 /* ConditionalType */:
54666                 case 188 /* TypeOperator */:
54667                 case 178 /* ArrayType */:
54668                 case 179 /* TupleType */:
54669                     return isResolvedByTypeAlias(parent);
54670                 case 254 /* TypeAliasDeclaration */:
54671                     return true;
54672             }
54673             return false;
54674         }
54675         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
54676         // of a type alias.
54677         function mayResolveTypeAlias(node) {
54678             switch (node.kind) {
54679                 case 173 /* TypeReference */:
54680                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
54681                 case 176 /* TypeQuery */:
54682                     return true;
54683                 case 188 /* TypeOperator */:
54684                     return node.operator !== 151 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
54685                 case 186 /* ParenthesizedType */:
54686                 case 180 /* OptionalType */:
54687                 case 192 /* NamedTupleMember */:
54688                 case 307 /* JSDocOptionalType */:
54689                 case 305 /* JSDocNullableType */:
54690                 case 306 /* JSDocNonNullableType */:
54691                 case 301 /* JSDocTypeExpression */:
54692                     return mayResolveTypeAlias(node.type);
54693                 case 181 /* RestType */:
54694                     return node.type.kind !== 178 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
54695                 case 182 /* UnionType */:
54696                 case 183 /* IntersectionType */:
54697                     return ts.some(node.types, mayResolveTypeAlias);
54698                 case 189 /* IndexedAccessType */:
54699                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
54700                 case 184 /* ConditionalType */:
54701                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
54702                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
54703             }
54704             return false;
54705         }
54706         function getTypeFromArrayOrTupleTypeNode(node) {
54707             var links = getNodeLinks(node);
54708             if (!links.resolvedType) {
54709                 var target = getArrayOrTupleTargetType(node);
54710                 if (target === emptyGenericType) {
54711                     links.resolvedType = emptyObjectType;
54712                 }
54713                 else if (!(node.kind === 179 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) {
54714                     links.resolvedType = node.kind === 179 /* TupleType */ && node.elements.length === 0 ? target :
54715                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
54716                 }
54717                 else {
54718                     var elementTypes = node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode);
54719                     links.resolvedType = createNormalizedTypeReference(target, elementTypes);
54720                 }
54721             }
54722             return links.resolvedType;
54723         }
54724         function isReadonlyTypeOperator(node) {
54725             return ts.isTypeOperatorNode(node) && node.operator === 142 /* ReadonlyKeyword */;
54726         }
54727         function createTupleType(elementTypes, elementFlags, readonly, namedMemberDeclarations) {
54728             if (readonly === void 0) { readonly = false; }
54729             var tupleTarget = getTupleTargetType(elementFlags || ts.map(elementTypes, function (_) { return 1 /* Required */; }), readonly, namedMemberDeclarations);
54730             return tupleTarget === emptyGenericType ? emptyObjectType :
54731                 elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) :
54732                     tupleTarget;
54733         }
54734         function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
54735             if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */) {
54736                 // [...X[]] is equivalent to just X[]
54737                 return readonly ? globalReadonlyArrayType : globalArrayType;
54738             }
54739             var key = ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*"; }).join() +
54740                 (readonly ? "R" : "") +
54741                 (namedMemberDeclarations && namedMemberDeclarations.length ? "," + ts.map(namedMemberDeclarations, getNodeId).join(",") : "");
54742             var type = tupleTypes.get(key);
54743             if (!type) {
54744                 tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations));
54745             }
54746             return type;
54747         }
54748         // We represent tuple types as type references to synthesized generic interface types created by
54749         // this function. The types are of the form:
54750         //
54751         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
54752         //
54753         // Note that the generic type created by this function has no symbol associated with it. The same
54754         // is true for each of the synthesized type parameters.
54755         function createTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
54756             var arity = elementFlags.length;
54757             var minLength = ts.findLastIndex(elementFlags, function (f) { return !!(f & (1 /* Required */ | 8 /* Variadic */)); }) + 1;
54758             var typeParameters;
54759             var properties = [];
54760             var combinedFlags = 0;
54761             if (arity) {
54762                 typeParameters = new Array(arity);
54763                 for (var i = 0; i < arity; i++) {
54764                     var typeParameter = typeParameters[i] = createTypeParameter();
54765                     var flags = elementFlags[i];
54766                     combinedFlags |= flags;
54767                     if (!(combinedFlags & 12 /* Variable */)) {
54768                         var property = createSymbol(4 /* Property */ | (flags & 2 /* Optional */ ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
54769                         property.tupleLabelDeclaration = namedMemberDeclarations === null || namedMemberDeclarations === void 0 ? void 0 : namedMemberDeclarations[i];
54770                         property.type = typeParameter;
54771                         properties.push(property);
54772                     }
54773                 }
54774             }
54775             var fixedLength = properties.length;
54776             var lengthSymbol = createSymbol(4 /* Property */, "length");
54777             if (combinedFlags & 12 /* Variable */) {
54778                 lengthSymbol.type = numberType;
54779             }
54780             else {
54781                 var literalTypes_1 = [];
54782                 for (var i = minLength; i <= arity; i++)
54783                     literalTypes_1.push(getLiteralType(i));
54784                 lengthSymbol.type = getUnionType(literalTypes_1);
54785             }
54786             properties.push(lengthSymbol);
54787             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
54788             type.typeParameters = typeParameters;
54789             type.outerTypeParameters = undefined;
54790             type.localTypeParameters = typeParameters;
54791             type.instantiations = new ts.Map();
54792             type.instantiations.set(getTypeListId(type.typeParameters), type);
54793             type.target = type;
54794             type.resolvedTypeArguments = type.typeParameters;
54795             type.thisType = createTypeParameter();
54796             type.thisType.isThisType = true;
54797             type.thisType.constraint = type;
54798             type.declaredProperties = properties;
54799             type.declaredCallSignatures = ts.emptyArray;
54800             type.declaredConstructSignatures = ts.emptyArray;
54801             type.declaredStringIndexInfo = undefined;
54802             type.declaredNumberIndexInfo = undefined;
54803             type.elementFlags = elementFlags;
54804             type.minLength = minLength;
54805             type.fixedLength = fixedLength;
54806             type.hasRestElement = !!(combinedFlags & 12 /* Variable */);
54807             type.combinedFlags = combinedFlags;
54808             type.readonly = readonly;
54809             type.labeledElementDeclarations = namedMemberDeclarations;
54810             return type;
54811         }
54812         function createNormalizedTypeReference(target, typeArguments) {
54813             return target.objectFlags & 8 /* Tuple */ && target.combinedFlags & 8 /* Variadic */ ?
54814                 createNormalizedTupleType(target, typeArguments) :
54815                 createTypeReference(target, typeArguments);
54816         }
54817         function createNormalizedTupleType(target, elementTypes) {
54818             var _a, _b, _c;
54819             // Transform [A, ...(X | Y | Z)] into [A, ...X] | [A, ...Y] | [A, ...Z]
54820             var unionIndex = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
54821             if (unionIndex >= 0) {
54822                 return checkCrossProductUnion(ts.map(elementTypes, function (t, i) { return target.elementFlags[i] & 8 /* Variadic */ ? t : unknownType; })) ?
54823                     mapType(elementTypes[unionIndex], function (t) { return createNormalizedTupleType(target, ts.replaceElement(elementTypes, unionIndex, t)); }) :
54824                     errorType;
54825             }
54826             // If there are no variadic elements with non-generic types, just create a type reference with the same target type.
54827             var spreadIndex = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */) && !(t.flags & 58982400 /* InstantiableNonPrimitive */) && !isGenericMappedType(t); });
54828             if (spreadIndex < 0) {
54829                 return createTypeReference(target, elementTypes);
54830             }
54831             // We have non-generic variadic elements that need normalization.
54832             var expandedTypes = [];
54833             var expandedFlags = [];
54834             var expandedDeclarations = [];
54835             var optionalIndex = -1;
54836             var restTypes;
54837             var _loop_13 = function (i) {
54838                 var type = elementTypes[i];
54839                 var flags = target.elementFlags[i];
54840                 if (flags & 8 /* Variadic */) {
54841                     if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) {
54842                         // Generic variadic elements stay as they are (except following a rest element).
54843                         addElementOrRest(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]);
54844                     }
54845                     else if (isTupleType(type)) {
54846                         // Spread variadic elements with tuple types into the resulting tuple.
54847                         ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElementOrRest(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); });
54848                     }
54849                     else {
54850                         // Treat everything else as an array type and create a rest element.
54851                         addElementOrRest(isArrayLikeType(type) && getIndexTypeOfType(type, 1 /* Number */) || errorType, 4 /* Rest */, (_b = target.labeledElementDeclarations) === null || _b === void 0 ? void 0 : _b[i]);
54852                     }
54853                 }
54854                 else {
54855                     // Copy other element kinds with no change.
54856                     addElementOrRest(type, flags, (_c = target.labeledElementDeclarations) === null || _c === void 0 ? void 0 : _c[i]);
54857                 }
54858             };
54859             for (var i = 0; i < elementTypes.length; i++) {
54860                 _loop_13(i);
54861             }
54862             if (restTypes) {
54863                 // Create a union of the collected rest element types.
54864                 expandedTypes[expandedTypes.length - 1] = getUnionType(restTypes);
54865             }
54866             var tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations);
54867             return tupleTarget === emptyGenericType ? emptyObjectType :
54868                 expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) :
54869                     tupleTarget;
54870             function addElementOrRest(type, flags, declaration) {
54871                 if (restTypes) {
54872                     // A rest element was previously added, so simply collect the type of this element.
54873                     restTypes.push(flags & 8 /* Variadic */ ? getIndexedAccessType(type, numberType) : type);
54874                 }
54875                 else {
54876                     if (flags & 1 /* Required */ && optionalIndex >= 0) {
54877                         // Turn preceding optional elements into required elements
54878                         for (var i = optionalIndex; i < expandedFlags.length; i++) {
54879                             if (expandedFlags[i] & 2 /* Optional */)
54880                                 expandedFlags[i] = 1 /* Required */;
54881                         }
54882                         optionalIndex = -1;
54883                     }
54884                     else if (flags & 2 /* Optional */ && optionalIndex < 0) {
54885                         optionalIndex = expandedFlags.length;
54886                     }
54887                     else if (flags & 4 /* Rest */) {
54888                         // Start collecting element types when a rest element is added.
54889                         restTypes = [type];
54890                     }
54891                     expandedTypes.push(type);
54892                     expandedFlags.push(flags);
54893                     if (expandedDeclarations && declaration) {
54894                         expandedDeclarations.push(declaration);
54895                     }
54896                     else {
54897                         expandedDeclarations = undefined;
54898                     }
54899                 }
54900             }
54901         }
54902         function sliceTupleType(type, index, endSkipCount) {
54903             if (endSkipCount === void 0) { endSkipCount = 0; }
54904             var target = type.target;
54905             var endIndex = getTypeReferenceArity(type) - endSkipCount;
54906             return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(ts.emptyArray) :
54907                 createTupleType(getTypeArguments(type).slice(index, endIndex), target.elementFlags.slice(index, endIndex), 
54908                 /*readonly*/ false, target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex));
54909         }
54910         function getKnownKeysOfTupleType(type) {
54911             return getUnionType(ts.append(ts.arrayOf(type.target.fixedLength, function (i) { return getLiteralType("" + i); }), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType)));
54912         }
54913         function getTypeFromOptionalTypeNode(node) {
54914             var type = getTypeFromTypeNode(node.type);
54915             return strictNullChecks ? getOptionalType(type) : type;
54916         }
54917         function getTypeId(type) {
54918             return type.id;
54919         }
54920         function containsType(types, type) {
54921             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
54922         }
54923         function insertType(types, type) {
54924             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
54925             if (index < 0) {
54926                 types.splice(~index, 0, type);
54927                 return true;
54928             }
54929             return false;
54930         }
54931         function addTypeToUnion(typeSet, includes, type) {
54932             var flags = type.flags;
54933             if (flags & 1048576 /* Union */) {
54934                 return addTypesToUnion(typeSet, includes, type.types);
54935             }
54936             // We ignore 'never' types in unions
54937             if (!(flags & 131072 /* Never */)) {
54938                 includes |= flags & 205258751 /* IncludesMask */;
54939                 if (flags & 469499904 /* StructuredOrInstantiable */)
54940                     includes |= 262144 /* IncludesStructuredOrInstantiable */;
54941                 if (type === wildcardType)
54942                     includes |= 8388608 /* IncludesWildcard */;
54943                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
54944                     if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
54945                         includes |= 4194304 /* IncludesNonWideningType */;
54946                 }
54947                 else {
54948                     var len = typeSet.length;
54949                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
54950                     if (index < 0) {
54951                         typeSet.splice(~index, 0, type);
54952                     }
54953                 }
54954             }
54955             return includes;
54956         }
54957         // Add the given types to the given type set. Order is preserved, duplicates are removed,
54958         // and nested types of the given kind are flattened into the set.
54959         function addTypesToUnion(typeSet, includes, types) {
54960             for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
54961                 var type = types_10[_i];
54962                 includes = addTypeToUnion(typeSet, includes, type);
54963             }
54964             return includes;
54965         }
54966         function isSetOfLiteralsFromSameEnum(types) {
54967             var first = types[0];
54968             if (first.flags & 1024 /* EnumLiteral */) {
54969                 var firstEnum = getParentOfSymbol(first.symbol);
54970                 for (var i = 1; i < types.length; i++) {
54971                     var other = types[i];
54972                     if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
54973                         return false;
54974                     }
54975                 }
54976                 return true;
54977             }
54978             return false;
54979         }
54980         function removeSubtypes(types, primitivesOnly) {
54981             var len = types.length;
54982             if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
54983                 return true;
54984             }
54985             var i = len;
54986             var count = 0;
54987             while (i > 0) {
54988                 i--;
54989                 var source = types[i];
54990                 for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
54991                     var target = types_11[_i];
54992                     if (source !== target) {
54993                         if (count === 100000) {
54994                             // After 100000 subtype checks we estimate the remaining amount of work by assuming the
54995                             // same ratio of checks per element. If the estimated number of remaining type checks is
54996                             // greater than an upper limit we deem the union type too complex to represent. The
54997                             // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
54998                             // caps union types at 5000 unique literal types and 1000 unique object types.
54999                             var estimatedCount = (count / (len - i)) * len;
55000                             if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
55001                                 ts.tracing.instant("check" /* Check */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) });
55002                                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
55003                                 return false;
55004                             }
55005                         }
55006                         count++;
55007                         if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
55008                             !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
55009                             isTypeDerivedFrom(source, target))) {
55010                             ts.orderedRemoveItemAt(types, i);
55011                             break;
55012                         }
55013                     }
55014                 }
55015             }
55016             return true;
55017         }
55018         function removeRedundantLiteralTypes(types, includes) {
55019             var i = types.length;
55020             while (i > 0) {
55021                 i--;
55022                 var t = types[i];
55023                 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
55024                     t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
55025                     t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
55026                     t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
55027                     isFreshLiteralType(t) && containsType(types, t.regularType);
55028                 if (remove) {
55029                     ts.orderedRemoveItemAt(types, i);
55030                 }
55031             }
55032         }
55033         function removeStringLiteralsMatchedByTemplateLiterals(types) {
55034             var templates = ts.filter(types, isPatternLiteralType);
55035             if (templates.length) {
55036                 var i = types.length;
55037                 var _loop_14 = function () {
55038                     i--;
55039                     var t = types[i];
55040                     if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeSubtypeOf(t, template); })) {
55041                         ts.orderedRemoveItemAt(types, i);
55042                     }
55043                 };
55044                 while (i > 0) {
55045                     _loop_14();
55046                 }
55047             }
55048         }
55049         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
55050         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
55051         // of other types. Subtype reduction is expensive for large union types and is possible only when union
55052         // types are known not to circularly reference themselves (as is the case with union types created by
55053         // expression constructs such as array literals and the || and ?: operators). Named types can
55054         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
55055         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
55056         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
55057             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
55058             if (types.length === 0) {
55059                 return neverType;
55060             }
55061             if (types.length === 1) {
55062                 return types[0];
55063             }
55064             var typeSet = [];
55065             var includes = addTypesToUnion(typeSet, 0, types);
55066             if (unionReduction !== 0 /* None */) {
55067                 if (includes & 3 /* AnyOrUnknown */) {
55068                     return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
55069                 }
55070                 switch (unionReduction) {
55071                     case 1 /* Literal */:
55072                         if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
55073                             removeRedundantLiteralTypes(typeSet, includes);
55074                         }
55075                         if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) {
55076                             removeStringLiteralsMatchedByTemplateLiterals(typeSet);
55077                         }
55078                         break;
55079                     case 2 /* Subtype */:
55080                         if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
55081                             return errorType;
55082                         }
55083                         break;
55084                 }
55085                 if (typeSet.length === 0) {
55086                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
55087                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
55088                             neverType;
55089                 }
55090             }
55091             var objectFlags = (includes & 469647395 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
55092                 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
55093             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
55094         }
55095         function getUnionTypePredicate(signatures) {
55096             var first;
55097             var types = [];
55098             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
55099                 var sig = signatures_6[_i];
55100                 var pred = getTypePredicateOfSignature(sig);
55101                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
55102                     continue;
55103                 }
55104                 if (first) {
55105                     if (!typePredicateKindsMatch(first, pred)) {
55106                         // No common type predicate.
55107                         return undefined;
55108                     }
55109                 }
55110                 else {
55111                     first = pred;
55112                 }
55113                 types.push(pred.type);
55114             }
55115             if (!first) {
55116                 // No union signatures had a type predicate.
55117                 return undefined;
55118             }
55119             var unionType = getUnionType(types);
55120             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
55121         }
55122         function typePredicateKindsMatch(a, b) {
55123             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
55124         }
55125         // This function assumes the constituent type list is sorted and deduplicated.
55126         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
55127             if (types.length === 0) {
55128                 return neverType;
55129             }
55130             if (types.length === 1) {
55131                 return types[0];
55132             }
55133             var id = getTypeListId(types);
55134             var type = unionTypes.get(id);
55135             if (!type) {
55136                 type = createType(1048576 /* Union */);
55137                 unionTypes.set(id, type);
55138                 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
55139                 type.types = types;
55140                 /*
55141                 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
55142                 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
55143                 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
55144                 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
55145                 */
55146                 type.aliasSymbol = aliasSymbol;
55147                 type.aliasTypeArguments = aliasTypeArguments;
55148             }
55149             return type;
55150         }
55151         function getTypeFromUnionTypeNode(node) {
55152             var links = getNodeLinks(node);
55153             if (!links.resolvedType) {
55154                 var aliasSymbol = getAliasSymbolForTypeNode(node);
55155                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
55156             }
55157             return links.resolvedType;
55158         }
55159         function addTypeToIntersection(typeSet, includes, type) {
55160             var flags = type.flags;
55161             if (flags & 2097152 /* Intersection */) {
55162                 return addTypesToIntersection(typeSet, includes, type.types);
55163             }
55164             if (isEmptyAnonymousObjectType(type)) {
55165                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
55166                     includes |= 16777216 /* IncludesEmptyObject */;
55167                     typeSet.set(type.id.toString(), type);
55168                 }
55169             }
55170             else {
55171                 if (flags & 3 /* AnyOrUnknown */) {
55172                     if (type === wildcardType)
55173                         includes |= 8388608 /* IncludesWildcard */;
55174                 }
55175                 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
55176                     if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
55177                         // We have seen two distinct unit types which means we should reduce to an
55178                         // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
55179                         includes |= 67108864 /* NonPrimitive */;
55180                     }
55181                     typeSet.set(type.id.toString(), type);
55182                 }
55183                 includes |= flags & 205258751 /* IncludesMask */;
55184             }
55185             return includes;
55186         }
55187         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
55188         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
55189         function addTypesToIntersection(typeSet, includes, types) {
55190             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
55191                 var type = types_12[_i];
55192                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
55193             }
55194             return includes;
55195         }
55196         function removeRedundantPrimitiveTypes(types, includes) {
55197             var i = types.length;
55198             while (i > 0) {
55199                 i--;
55200                 var t = types[i];
55201                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
55202                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
55203                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
55204                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
55205                 if (remove) {
55206                     ts.orderedRemoveItemAt(types, i);
55207                 }
55208             }
55209         }
55210         // Check that the given type has a match in every union. A given type is matched by
55211         // an identical type, and a literal type is additionally matched by its corresponding
55212         // primitive type.
55213         function eachUnionContains(unionTypes, type) {
55214             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
55215                 var u = unionTypes_1[_i];
55216                 if (!containsType(u.types, type)) {
55217                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
55218                         type.flags & 256 /* NumberLiteral */ ? numberType :
55219                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
55220                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
55221                                     undefined;
55222                     if (!primitive || !containsType(u.types, primitive)) {
55223                         return false;
55224                     }
55225                 }
55226             }
55227             return true;
55228         }
55229         /**
55230          * Returns `true` if the intersection of the template literals and string literals is the empty set, eg `get${string}` & "setX", and should reduce to `never`
55231          */
55232         function extractRedundantTemplateLiterals(types) {
55233             var i = types.length;
55234             var literals = ts.filter(types, function (t) { return !!(t.flags & 128 /* StringLiteral */); });
55235             while (i > 0) {
55236                 i--;
55237                 var t = types[i];
55238                 if (!(t.flags & 134217728 /* TemplateLiteral */))
55239                     continue;
55240                 for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) {
55241                     var t2 = literals_1[_i];
55242                     if (isTypeSubtypeOf(t2, t)) {
55243                         // eg, ``get${T}` & "getX"` is just `"getX"`
55244                         ts.orderedRemoveItemAt(types, i);
55245                         break;
55246                     }
55247                     else if (isPatternLiteralType(t)) {
55248                         return true;
55249                     }
55250                 }
55251             }
55252             return false;
55253         }
55254         function extractIrreducible(types, flag) {
55255             if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
55256                 for (var i = 0; i < types.length; i++) {
55257                     types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
55258                 }
55259                 return true;
55260             }
55261             return false;
55262         }
55263         // If the given list of types contains more than one union of primitive types, replace the
55264         // first with a union containing an intersection of those primitive types, then remove the
55265         // other unions and return true. Otherwise, do nothing and return false.
55266         function intersectUnionsOfPrimitiveTypes(types) {
55267             var unionTypes;
55268             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
55269             if (index < 0) {
55270                 return false;
55271             }
55272             var i = index + 1;
55273             // Remove all but the first union of primitive types and collect them in
55274             // the unionTypes array.
55275             while (i < types.length) {
55276                 var t = types[i];
55277                 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
55278                     (unionTypes || (unionTypes = [types[index]])).push(t);
55279                     ts.orderedRemoveItemAt(types, i);
55280                 }
55281                 else {
55282                     i++;
55283                 }
55284             }
55285             // Return false if there was only one union of primitive types
55286             if (!unionTypes) {
55287                 return false;
55288             }
55289             // We have more than one union of primitive types, now intersect them. For each
55290             // type in each union we check if the type is matched in every union and if so
55291             // we include it in the result.
55292             var checked = [];
55293             var result = [];
55294             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
55295                 var u = unionTypes_2[_i];
55296                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
55297                     var t = _b[_a];
55298                     if (insertType(checked, t)) {
55299                         if (eachUnionContains(unionTypes, t)) {
55300                             insertType(result, t);
55301                         }
55302                     }
55303                 }
55304             }
55305             // Finally replace the first union with the result
55306             types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
55307             return true;
55308         }
55309         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
55310             var result = createType(2097152 /* Intersection */);
55311             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
55312             result.types = types;
55313             result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
55314             result.aliasTypeArguments = aliasTypeArguments;
55315             return result;
55316         }
55317         // We normalize combinations of intersection and union types based on the distributive property of the '&'
55318         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
55319         // types with union type constituents into equivalent union types with intersection type constituents and
55320         // effectively ensure that union types are always at the top level in type representations.
55321         //
55322         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
55323         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
55324         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
55325         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
55326         // for intersections of types with signatures can be deterministic.
55327         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
55328             var typeMembershipMap = new ts.Map();
55329             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
55330             var typeSet = ts.arrayFrom(typeMembershipMap.values());
55331             // An intersection type is considered empty if it contains
55332             // the type never, or
55333             // more than one unit type or,
55334             // an object type and a nullable type (null or undefined), or
55335             // a string-like type and a type known to be non-string-like, or
55336             // a number-like type and a type known to be non-number-like, or
55337             // a symbol-like type and a type known to be non-symbol-like, or
55338             // a void-like type and a type known to be non-void-like, or
55339             // a non-primitive type and a type known to be primitive.
55340             if (includes & 131072 /* Never */ ||
55341                 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
55342                 includes & 67108864 /* NonPrimitive */ && includes & (469892092 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
55343                 includes & 402653316 /* StringLike */ && includes & (469892092 /* DisjointDomains */ & ~402653316 /* StringLike */) ||
55344                 includes & 296 /* NumberLike */ && includes & (469892092 /* DisjointDomains */ & ~296 /* NumberLike */) ||
55345                 includes & 2112 /* BigIntLike */ && includes & (469892092 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
55346                 includes & 12288 /* ESSymbolLike */ && includes & (469892092 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
55347                 includes & 49152 /* VoidLike */ && includes & (469892092 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
55348                 return neverType;
55349             }
55350             if (includes & 134217728 /* TemplateLiteral */ && includes & 128 /* StringLiteral */ && extractRedundantTemplateLiterals(typeSet)) {
55351                 return neverType;
55352             }
55353             if (includes & 1 /* Any */) {
55354                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
55355             }
55356             if (!strictNullChecks && includes & 98304 /* Nullable */) {
55357                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
55358             }
55359             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
55360                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
55361                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
55362                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
55363                 removeRedundantPrimitiveTypes(typeSet, includes);
55364             }
55365             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
55366                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
55367             }
55368             if (typeSet.length === 0) {
55369                 return unknownType;
55370             }
55371             if (typeSet.length === 1) {
55372                 return typeSet[0];
55373             }
55374             var id = getTypeListId(typeSet);
55375             var result = intersectionTypes.get(id);
55376             if (!result) {
55377                 if (includes & 1048576 /* Union */) {
55378                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
55379                         // When the intersection creates a reduced set (which might mean that *all* union types have
55380                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
55381                         // reduced we'll never reduce again, so this occurs at most once.
55382                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
55383                     }
55384                     else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
55385                         result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
55386                     }
55387                     else if (extractIrreducible(typeSet, 65536 /* Null */)) {
55388                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
55389                     }
55390                     else {
55391                         // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
55392                         // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
55393                         // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
55394                         if (!checkCrossProductUnion(typeSet)) {
55395                             return errorType;
55396                         }
55397                         var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
55398                         var unionType = typeSet[unionIndex_1];
55399                         result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
55400                     }
55401                 }
55402                 else {
55403                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
55404                 }
55405                 intersectionTypes.set(id, result);
55406             }
55407             return result;
55408         }
55409         function checkCrossProductUnion(types) {
55410             var size = ts.reduceLeft(types, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : t.flags & 131072 /* Never */ ? 0 : 1); }, 1);
55411             if (size >= 100000) {
55412                 ts.tracing.instant("check" /* Check */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size });
55413                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
55414                 return false;
55415             }
55416             return true;
55417         }
55418         function getTypeFromIntersectionTypeNode(node) {
55419             var links = getNodeLinks(node);
55420             if (!links.resolvedType) {
55421                 var aliasSymbol = getAliasSymbolForTypeNode(node);
55422                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
55423             }
55424             return links.resolvedType;
55425         }
55426         function createIndexType(type, stringsOnly) {
55427             var result = createType(4194304 /* Index */);
55428             result.type = type;
55429             result.stringsOnly = stringsOnly;
55430             return result;
55431         }
55432         function getIndexTypeForGenericType(type, stringsOnly) {
55433             return stringsOnly ?
55434                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
55435                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
55436         }
55437         function getIndexTypeForMappedType(type, noIndexSignatures) {
55438             var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); });
55439             var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType);
55440             return nameType ?
55441                 mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) :
55442                 constraint;
55443         }
55444         // Ordinarily we reduce a keyof M where M is a mapped type { [P in K as N<P>]: X } to simply N<K>. This however presumes
55445         // that N distributes over union types, i.e. that N<A | B | C> is equivalent to N<A> | N<B> | N<C>. That presumption is
55446         // generally true, except when N is a non-distributive conditional type or an instantiable type with non-distributive
55447         // conditional type as a constituent. In those cases, we cannot reduce keyof M and need to preserve it as is.
55448         function isNonDistributiveNameType(type) {
55449             return !!(type && (type.flags & 16777216 /* Conditional */ && !type.root.isDistributive ||
55450                 type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */) && ts.some(type.types, isNonDistributiveNameType) ||
55451                 type.flags & (4194304 /* Index */ | 268435456 /* StringMapping */) && isNonDistributiveNameType(type.type) ||
55452                 type.flags & 8388608 /* IndexedAccess */ && isNonDistributiveNameType(type.indexType) ||
55453                 type.flags & 33554432 /* Substitution */ && isNonDistributiveNameType(type.substitute)));
55454         }
55455         function getLiteralTypeFromPropertyName(name) {
55456             if (ts.isPrivateIdentifier(name)) {
55457                 return neverType;
55458             }
55459             return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
55460                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
55461         }
55462         function getBigIntLiteralType(node) {
55463             return getLiteralType({
55464                 negative: false,
55465                 base10Value: ts.parsePseudoBigInt(node.text)
55466             });
55467         }
55468         function getLiteralTypeFromProperty(prop, include) {
55469             if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
55470                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
55471                 if (!type && !ts.isKnownSymbol(prop)) {
55472                     if (prop.escapedName === "default" /* Default */) {
55473                         type = getLiteralType("default");
55474                     }
55475                     else {
55476                         var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
55477                         type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
55478                     }
55479                 }
55480                 if (type && type.flags & include) {
55481                     return type;
55482                 }
55483             }
55484             return neverType;
55485         }
55486         function getLiteralTypeFromProperties(type, include) {
55487             return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
55488         }
55489         function getNonEnumNumberIndexInfo(type) {
55490             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
55491             return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
55492         }
55493         function getIndexType(type, stringsOnly, noIndexSignatures) {
55494             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
55495             type = getReducedType(type);
55496             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
55497                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
55498                     type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && isNonDistributiveNameType(getNameTypeFromMappedType(type)) ? getIndexTypeForGenericType(type, stringsOnly) :
55499                         ts.getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, noIndexSignatures) :
55500                             type === wildcardType ? wildcardType :
55501                                 type.flags & 2 /* Unknown */ ? neverType :
55502                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
55503                                         stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
55504                                             !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
55505                                                 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
55506                                                     getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
55507         }
55508         function getExtractStringType(type) {
55509             if (keyofStringsOnly) {
55510                 return type;
55511             }
55512             var extractTypeAlias = getGlobalExtractSymbol();
55513             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
55514         }
55515         function getIndexTypeOrString(type) {
55516             var indexType = getExtractStringType(getIndexType(type));
55517             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
55518         }
55519         function getTypeFromTypeOperatorNode(node) {
55520             var links = getNodeLinks(node);
55521             if (!links.resolvedType) {
55522                 switch (node.operator) {
55523                     case 138 /* KeyOfKeyword */:
55524                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
55525                         break;
55526                     case 151 /* UniqueKeyword */:
55527                         links.resolvedType = node.type.kind === 148 /* SymbolKeyword */
55528                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
55529                             : errorType;
55530                         break;
55531                     case 142 /* ReadonlyKeyword */:
55532                         links.resolvedType = getTypeFromTypeNode(node.type);
55533                         break;
55534                     default:
55535                         throw ts.Debug.assertNever(node.operator);
55536                 }
55537             }
55538             return links.resolvedType;
55539         }
55540         function getTypeFromTemplateTypeNode(node) {
55541             var links = getNodeLinks(node);
55542             if (!links.resolvedType) {
55543                 links.resolvedType = getTemplateLiteralType(__spreadArrays([node.head.text], ts.map(node.templateSpans, function (span) { return span.literal.text; })), ts.map(node.templateSpans, function (span) { return getTypeFromTypeNode(span.type); }));
55544             }
55545             return links.resolvedType;
55546         }
55547         function getTemplateLiteralType(texts, types) {
55548             var unionIndex = ts.findIndex(types, function (t) { return !!(t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
55549             if (unionIndex >= 0) {
55550                 return checkCrossProductUnion(types) ?
55551                     mapType(types[unionIndex], function (t) { return getTemplateLiteralType(texts, ts.replaceElement(types, unionIndex, t)); }) :
55552                     errorType;
55553             }
55554             if (ts.contains(types, wildcardType)) {
55555                 return wildcardType;
55556             }
55557             var newTypes = [];
55558             var newTexts = [];
55559             var text = texts[0];
55560             if (!addSpans(texts, types)) {
55561                 return stringType;
55562             }
55563             if (newTypes.length === 0) {
55564                 return getLiteralType(text);
55565             }
55566             newTexts.push(text);
55567             var id = getTypeListId(newTypes) + "|" + ts.map(newTexts, function (t) { return t.length; }).join(",") + "|" + newTexts.join("");
55568             var type = templateLiteralTypes.get(id);
55569             if (!type) {
55570                 templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes));
55571             }
55572             return type;
55573             function addSpans(texts, types) {
55574                 for (var i = 0; i < types.length; i++) {
55575                     var t = types[i];
55576                     if (t.flags & (2944 /* Literal */ | 65536 /* Null */ | 32768 /* Undefined */)) {
55577                         text += getTemplateStringForType(t) || "";
55578                         text += texts[i + 1];
55579                     }
55580                     else if (t.flags & 134217728 /* TemplateLiteral */) {
55581                         text += t.texts[0];
55582                         if (!addSpans(t.texts, t.types))
55583                             return false;
55584                         text += texts[i + 1];
55585                     }
55586                     else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) {
55587                         newTypes.push(t);
55588                         newTexts.push(text);
55589                         text = texts[i + 1];
55590                     }
55591                     else {
55592                         return false;
55593                     }
55594                 }
55595                 return true;
55596             }
55597         }
55598         function getTemplateStringForType(type) {
55599             return type.flags & 128 /* StringLiteral */ ? type.value :
55600                 type.flags & 256 /* NumberLiteral */ ? "" + type.value :
55601                     type.flags & 2048 /* BigIntLiteral */ ? ts.pseudoBigIntToString(type.value) :
55602                         type.flags & 512 /* BooleanLiteral */ ? type.intrinsicName :
55603                             type.flags & 65536 /* Null */ ? "null" :
55604                                 type.flags & 32768 /* Undefined */ ? "undefined" :
55605                                     undefined;
55606         }
55607         function createTemplateLiteralType(texts, types) {
55608             var type = createType(134217728 /* TemplateLiteral */);
55609             type.texts = texts;
55610             type.types = types;
55611             return type;
55612         }
55613         function getStringMappingType(symbol, type) {
55614             return type.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) :
55615                 isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) :
55616                     type.flags & 128 /* StringLiteral */ ? getLiteralType(applyStringMapping(symbol, type.value)) :
55617                         type;
55618         }
55619         function applyStringMapping(symbol, str) {
55620             switch (intrinsicTypeKinds.get(symbol.escapedName)) {
55621                 case 0 /* Uppercase */: return str.toUpperCase();
55622                 case 1 /* Lowercase */: return str.toLowerCase();
55623                 case 2 /* Capitalize */: return str.charAt(0).toUpperCase() + str.slice(1);
55624                 case 3 /* Uncapitalize */: return str.charAt(0).toLowerCase() + str.slice(1);
55625             }
55626             return str;
55627         }
55628         function getStringMappingTypeForGenericType(symbol, type) {
55629             var id = getSymbolId(symbol) + "," + getTypeId(type);
55630             var result = stringMappingTypes.get(id);
55631             if (!result) {
55632                 stringMappingTypes.set(id, result = createStringMappingType(symbol, type));
55633             }
55634             return result;
55635         }
55636         function createStringMappingType(symbol, type) {
55637             var result = createType(268435456 /* StringMapping */);
55638             result.symbol = symbol;
55639             result.type = type;
55640             return result;
55641         }
55642         function createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined) {
55643             var type = createType(8388608 /* IndexedAccess */);
55644             type.objectType = objectType;
55645             type.indexType = indexType;
55646             type.aliasSymbol = aliasSymbol;
55647             type.aliasTypeArguments = aliasTypeArguments;
55648             type.noUncheckedIndexedAccessCandidate = shouldIncludeUndefined;
55649             return type;
55650         }
55651         /**
55652          * Returns if a type is or consists of a JSLiteral object type
55653          * In addition to objects which are directly literals,
55654          * * unions where every element is a jsliteral
55655          * * intersections where at least one element is a jsliteral
55656          * * and instantiable types constrained to a jsliteral
55657          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
55658          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
55659          */
55660         function isJSLiteralType(type) {
55661             if (noImplicitAny) {
55662                 return false; // Flag is meaningless under `noImplicitAny` mode
55663             }
55664             if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
55665                 return true;
55666             }
55667             if (type.flags & 1048576 /* Union */) {
55668                 return ts.every(type.types, isJSLiteralType);
55669             }
55670             if (type.flags & 2097152 /* Intersection */) {
55671                 return ts.some(type.types, isJSLiteralType);
55672             }
55673             if (type.flags & 465829888 /* Instantiable */) {
55674                 return isJSLiteralType(getResolvedBaseConstraint(type));
55675             }
55676             return false;
55677         }
55678         function getPropertyNameFromIndex(indexType, accessNode) {
55679             var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined;
55680             return isTypeUsableAsPropertyName(indexType) ?
55681                 getPropertyNameFromType(indexType) :
55682                 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
55683                     ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
55684                     accessNode && ts.isPropertyName(accessNode) ?
55685                         // late bound names are handled in the first branch, so here we only need to handle normal names
55686                         ts.getPropertyNameForPropertyNameNode(accessNode) :
55687                         undefined;
55688         }
55689         function isUncalledFunctionReference(node, symbol) {
55690             return !(symbol.flags & (16 /* Function */ | 8192 /* Method */))
55691                 || !ts.isCallLikeExpression(ts.findAncestor(node, function (n) { return !ts.isAccessExpression(n); }) || node.parent)
55692                     && ts.every(symbol.declarations, function (d) { return !ts.isFunctionLike(d) || !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); });
55693         }
55694         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) {
55695             var _a;
55696             var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined;
55697             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
55698             if (propName !== undefined) {
55699                 var prop = getPropertyOfType(objectType, propName);
55700                 if (prop) {
55701                     if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) {
55702                         var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode);
55703                         errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName);
55704                     }
55705                     if (accessExpression) {
55706                         markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */);
55707                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
55708                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
55709                             return undefined;
55710                         }
55711                         if (accessFlags & 4 /* CacheSymbol */) {
55712                             getNodeLinks(accessNode).resolvedSymbol = prop;
55713                         }
55714                         if (isThisPropertyAccessInConstructor(accessExpression, prop)) {
55715                             return autoType;
55716                         }
55717                     }
55718                     var propType = getTypeOfSymbol(prop);
55719                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
55720                         getFlowTypeOfReference(accessExpression, propType) :
55721                         propType;
55722                 }
55723                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
55724                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
55725                         var indexNode = getIndexNodeForAccessExpression(accessNode);
55726                         if (isTupleType(objectType)) {
55727                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
55728                         }
55729                         else {
55730                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
55731                         }
55732                     }
55733                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
55734                     return mapType(objectType, function (t) {
55735                         var restType = getRestTypeOfTupleType(t) || undefinedType;
55736                         return noUncheckedIndexedAccessCandidate ? getUnionType([restType, undefinedType]) : restType;
55737                     });
55738                 }
55739             }
55740             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
55741                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
55742                     return objectType;
55743                 }
55744                 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
55745                 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
55746                 if (indexInfo) {
55747                     if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
55748                         if (accessExpression) {
55749                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
55750                         }
55751                         return undefined;
55752                     }
55753                     if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
55754                         var indexNode = getIndexNodeForAccessExpression(accessNode);
55755                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
55756                         return noUncheckedIndexedAccessCandidate ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
55757                     }
55758                     errorIfWritingToReadonlyIndex(indexInfo);
55759                     return noUncheckedIndexedAccessCandidate ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
55760                 }
55761                 if (indexType.flags & 131072 /* Never */) {
55762                     return neverType;
55763                 }
55764                 if (isJSLiteralType(objectType)) {
55765                     return anyType;
55766                 }
55767                 if (accessExpression && !isConstEnumObjectType(objectType)) {
55768                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
55769                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
55770                     }
55771                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
55772                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
55773                             error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
55774                         }
55775                         else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
55776                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
55777                         }
55778                         else {
55779                             var suggestion = void 0;
55780                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
55781                                 if (suggestion !== undefined) {
55782                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
55783                                 }
55784                             }
55785                             else {
55786                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
55787                                 if (suggestion_1 !== undefined) {
55788                                     error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1, typeToString(objectType), suggestion_1);
55789                                 }
55790                                 else {
55791                                     var errorInfo = void 0;
55792                                     if (indexType.flags & 1024 /* EnumLiteral */) {
55793                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
55794                                     }
55795                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
55796                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
55797                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
55798                                     }
55799                                     else if (indexType.flags & 128 /* StringLiteral */) {
55800                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
55801                                     }
55802                                     else if (indexType.flags & 256 /* NumberLiteral */) {
55803                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
55804                                     }
55805                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
55806                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1, typeToString(indexType), typeToString(objectType));
55807                                     }
55808                                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, typeToString(fullIndexType), typeToString(objectType));
55809                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
55810                                 }
55811                             }
55812                         }
55813                     }
55814                     return undefined;
55815                 }
55816             }
55817             if (isJSLiteralType(objectType)) {
55818                 return anyType;
55819             }
55820             if (accessNode) {
55821                 var indexNode = getIndexNodeForAccessExpression(accessNode);
55822                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
55823                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
55824                 }
55825                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
55826                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
55827                 }
55828                 else {
55829                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
55830                 }
55831             }
55832             if (isTypeAny(indexType)) {
55833                 return indexType;
55834             }
55835             return undefined;
55836             function errorIfWritingToReadonlyIndex(indexInfo) {
55837                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
55838                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
55839                 }
55840             }
55841         }
55842         function getIndexNodeForAccessExpression(accessNode) {
55843             return accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode.argumentExpression :
55844                 accessNode.kind === 189 /* IndexedAccessType */ ? accessNode.indexType :
55845                     accessNode.kind === 158 /* ComputedPropertyName */ ? accessNode.expression :
55846                         accessNode;
55847         }
55848         function isPatternLiteralPlaceholderType(type) {
55849             return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & 1 /* Any */);
55850         }
55851         function isPatternLiteralType(type) {
55852             return !!(type.flags & 134217728 /* TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType);
55853         }
55854         function isGenericObjectType(type) {
55855             if (type.flags & 3145728 /* UnionOrIntersection */) {
55856                 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
55857                     type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
55858                         (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
55859                 }
55860                 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
55861             }
55862             return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type);
55863         }
55864         function isGenericIndexType(type) {
55865             if (type.flags & 3145728 /* UnionOrIntersection */) {
55866                 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
55867                     type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
55868                         (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
55869                 }
55870                 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
55871             }
55872             return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type);
55873         }
55874         function isThisTypeParameter(type) {
55875             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
55876         }
55877         function getSimplifiedType(type, writing) {
55878             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
55879                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
55880                     type;
55881         }
55882         function distributeIndexOverObjectType(objectType, indexType, writing) {
55883             // (T | U)[K] -> T[K] | U[K] (reading)
55884             // (T | U)[K] -> T[K] & U[K] (writing)
55885             // (T & U)[K] -> T[K] & U[K]
55886             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
55887                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
55888                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
55889             }
55890         }
55891         function distributeObjectOverIndexType(objectType, indexType, writing) {
55892             // T[A | B] -> T[A] | T[B] (reading)
55893             // T[A | B] -> T[A] & T[B] (writing)
55894             if (indexType.flags & 1048576 /* Union */) {
55895                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
55896                 return writing ? getIntersectionType(types) : getUnionType(types);
55897             }
55898         }
55899         function unwrapSubstitution(type) {
55900             if (type.flags & 33554432 /* Substitution */) {
55901                 return type.substitute;
55902             }
55903             return type;
55904         }
55905         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
55906         // the type itself if no transformation is possible. The writing flag indicates that the type is
55907         // the target of an assignment.
55908         function getSimplifiedIndexedAccessType(type, writing) {
55909             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
55910             if (type[cache]) {
55911                 return type[cache] === circularConstraintType ? type : type[cache];
55912             }
55913             type[cache] = circularConstraintType;
55914             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
55915             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
55916             var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
55917             var indexType = getSimplifiedType(type.indexType, writing);
55918             // T[A | B] -> T[A] | T[B] (reading)
55919             // T[A | B] -> T[A] & T[B] (writing)
55920             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
55921             if (distributedOverIndex) {
55922                 return type[cache] = distributedOverIndex;
55923             }
55924             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
55925             if (!(indexType.flags & 465829888 /* Instantiable */)) {
55926                 // (T | U)[K] -> T[K] | U[K] (reading)
55927                 // (T | U)[K] -> T[K] & U[K] (writing)
55928                 // (T & U)[K] -> T[K] & U[K]
55929                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
55930                 if (distributedOverObject) {
55931                     return type[cache] = distributedOverObject;
55932                 }
55933             }
55934             // So ultimately (reading):
55935             // ((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]
55936             // A generic tuple type indexed by a number exists only when the index type doesn't select a
55937             // fixed element. We simplify to either the combined type of all elements (when the index type
55938             // the actual number type) or to the combined type of all non-fixed elements.
55939             if (isGenericTupleType(objectType) && indexType.flags & 296 /* NumberLike */) {
55940                 var elementType = getElementTypeOfSliceOfTupleType(objectType, indexType.flags & 8 /* Number */ ? 0 : objectType.target.fixedLength, /*endSkipCount*/ 0, writing);
55941                 if (elementType) {
55942                     return type[cache] = elementType;
55943                 }
55944             }
55945             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
55946             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
55947             // construct the type Box<T[X]>.
55948             if (isGenericMappedType(objectType)) {
55949                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
55950             }
55951             return type[cache] = type;
55952         }
55953         function getSimplifiedConditionalType(type, writing) {
55954             var checkType = type.checkType;
55955             var extendsType = type.extendsType;
55956             var trueType = getTrueTypeFromConditionalType(type);
55957             var falseType = getFalseTypeFromConditionalType(type);
55958             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
55959             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
55960                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
55961                     return getSimplifiedType(trueType, writing);
55962                 }
55963                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
55964                     return neverType;
55965                 }
55966             }
55967             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
55968                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
55969                     return neverType;
55970                 }
55971                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
55972                     return getSimplifiedType(falseType, writing);
55973                 }
55974             }
55975             return type;
55976         }
55977         /**
55978          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
55979          */
55980         function isIntersectionEmpty(type1, type2) {
55981             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
55982         }
55983         function substituteIndexedMappedType(objectType, index) {
55984             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
55985             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
55986             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
55987         }
55988         function getIndexedAccessType(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, aliasSymbol, aliasTypeArguments, accessFlags) {
55989             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
55990             return getIndexedAccessTypeOrUndefined(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
55991         }
55992         function indexTypeLessThan(indexType, limit) {
55993             return everyType(indexType, function (t) {
55994                 if (t.flags & 384 /* StringOrNumberLiteral */) {
55995                     var propName = getPropertyNameFromType(t);
55996                     if (isNumericLiteralName(propName)) {
55997                         var index = +propName;
55998                         return index >= 0 && index < limit;
55999                     }
56000                 }
56001                 return false;
56002             });
56003         }
56004         function getIndexedAccessTypeOrUndefined(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) {
56005             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
56006             if (objectType === wildcardType || indexType === wildcardType) {
56007                 return wildcardType;
56008             }
56009             var shouldIncludeUndefined = noUncheckedIndexedAccessCandidate ||
56010                 (!!compilerOptions.noUncheckedIndexedAccess &&
56011                     (accessFlags & (2 /* Writing */ | 16 /* ExpressionPosition */)) === 16 /* ExpressionPosition */);
56012             // If the object type has a string index signature and no other members we know that the result will
56013             // always be the type of that index signature and we can simplify accordingly.
56014             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
56015                 indexType = stringType;
56016             }
56017             // If the index type is generic, or if the object type is generic and doesn't originate in an expression and
56018             // the operation isn't exclusively indexing the fixed (non-variadic) portion of a tuple type, we are performing
56019             // a higher-order index access where we cannot meaningfully access the properties of the object type. Note that
56020             // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to
56021             // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved
56022             // eagerly using the constraint type of 'this' at the given location.
56023             if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 189 /* IndexedAccessType */ ?
56024                 isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) :
56025                 isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) {
56026                 if (objectType.flags & 3 /* AnyOrUnknown */) {
56027                     return objectType;
56028                 }
56029                 // Defer the operation by creating an indexed access type.
56030                 var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "");
56031                 var type = indexedAccessTypes.get(id);
56032                 if (!type) {
56033                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined));
56034                 }
56035                 return type;
56036             }
56037             // In the following we resolve T[K] to the type of the property in T selected by K.
56038             // We treat boolean as different from other unions to improve errors;
56039             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
56040             var apparentObjectType = getReducedApparentType(objectType);
56041             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
56042                 var propTypes = [];
56043                 var wasMissingProp = false;
56044                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
56045                     var t = _a[_i];
56046                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags, shouldIncludeUndefined);
56047                     if (propType) {
56048                         propTypes.push(propType);
56049                     }
56050                     else if (!accessNode) {
56051                         // If there's no error node, we can immeditely stop, since error reporting is off
56052                         return undefined;
56053                     }
56054                     else {
56055                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
56056                         wasMissingProp = true;
56057                     }
56058                 }
56059                 if (wasMissingProp) {
56060                     return undefined;
56061                 }
56062                 return accessFlags & 2 /* Writing */
56063                     ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments)
56064                     : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
56065             }
56066             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */, shouldIncludeUndefined, /* reportDeprecated */ true);
56067         }
56068         function getTypeFromIndexedAccessTypeNode(node) {
56069             var links = getNodeLinks(node);
56070             if (!links.resolvedType) {
56071                 var objectType = getTypeFromTypeNode(node.objectType);
56072                 var indexType = getTypeFromTypeNode(node.indexType);
56073                 var potentialAlias = getAliasSymbolForTypeNode(node);
56074                 var resolved = getIndexedAccessType(objectType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
56075                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
56076                     resolved.objectType === objectType &&
56077                     resolved.indexType === indexType ?
56078                     getConditionalFlowTypeOfType(resolved, node) : resolved;
56079             }
56080             return links.resolvedType;
56081         }
56082         function getTypeFromMappedTypeNode(node) {
56083             var links = getNodeLinks(node);
56084             if (!links.resolvedType) {
56085                 var type = createObjectType(32 /* Mapped */, node.symbol);
56086                 type.declaration = node;
56087                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
56088                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
56089                 links.resolvedType = type;
56090                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
56091                 // references itself through one or more type aliases.
56092                 getConstraintTypeFromMappedType(type);
56093             }
56094             return links.resolvedType;
56095         }
56096         function getActualTypeVariable(type) {
56097             if (type.flags & 33554432 /* Substitution */) {
56098                 return type.baseType;
56099             }
56100             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
56101                 type.indexType.flags & 33554432 /* Substitution */)) {
56102                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
56103             }
56104             return type;
56105         }
56106         function getConditionalType(root, mapper) {
56107             var result;
56108             var extraTypes;
56109             var _loop_15 = function () {
56110                 var checkType = instantiateType(root.checkType, mapper);
56111                 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
56112                 var extendsType = instantiateType(root.extendsType, mapper);
56113                 if (checkType === wildcardType || extendsType === wildcardType) {
56114                     return { value: wildcardType };
56115                 }
56116                 var combinedMapper = void 0;
56117                 if (root.inferTypeParameters) {
56118                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
56119                     // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
56120                     // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
56121                     // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
56122                     // so in those cases we refain from performing inference and retain the uninfered type parameter
56123                     if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
56124                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
56125                         // conditional type instead of deferring resolution. Also, we always want strict function
56126                         // types rules (i.e. proper contravariance) for inferences.
56127                         inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */);
56128                     }
56129                     combinedMapper = mergeTypeMappers(mapper, context.mapper);
56130                 }
56131                 // Instantiate the extends type including inferences for 'infer T' type parameters
56132                 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
56133                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
56134                 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
56135                     // Return falseType for a definitely false extends check. We check an instantiations of the two
56136                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
56137                     // possible (the wildcard type is assignable to and from all types). If those are not related,
56138                     // then no instantiations will be and we can just return the false branch type.
56139                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
56140                         // Return union of trueType and falseType for 'any' since it matches anything
56141                         if (checkType.flags & 1 /* Any */) {
56142                             (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper));
56143                         }
56144                         // If falseType is an immediately nested conditional type that isn't distributive or has an
56145                         // identical checkType, switch to that type and loop.
56146                         var falseType_1 = getTypeFromTypeNode(root.node.falseType);
56147                         if (falseType_1.flags & 16777216 /* Conditional */) {
56148                             var newRoot = falseType_1.root;
56149                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
56150                                 root = newRoot;
56151                                 return "continue";
56152                             }
56153                         }
56154                         result = instantiateType(falseType_1, mapper);
56155                         return "break";
56156                     }
56157                     // Return trueType for a definitely true extends check. We check instantiations of the two
56158                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
56159                     // that has no constraint. This ensures that, for example, the type
56160                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
56161                     // doesn't immediately resolve to 'string' instead of being deferred.
56162                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
56163                         result = instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper);
56164                         return "break";
56165                     }
56166                 }
56167                 // Return a deferred type for a check that is neither definitely true nor definitely false
56168                 var erasedCheckType = getActualTypeVariable(checkType);
56169                 result = createType(16777216 /* Conditional */);
56170                 result.root = root;
56171                 result.checkType = erasedCheckType;
56172                 result.extendsType = extendsType;
56173                 result.mapper = mapper;
56174                 result.combinedMapper = combinedMapper;
56175                 result.aliasSymbol = root.aliasSymbol;
56176                 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
56177                 return "break";
56178             };
56179             // We loop here for an immediately nested conditional type in the false position, effectively treating
56180             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
56181             // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
56182             while (true) {
56183                 var state_4 = _loop_15();
56184                 if (typeof state_4 === "object")
56185                     return state_4.value;
56186                 if (state_4 === "break")
56187                     break;
56188             }
56189             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
56190         }
56191         function getTrueTypeFromConditionalType(type) {
56192             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.mapper));
56193         }
56194         function getFalseTypeFromConditionalType(type) {
56195             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(getTypeFromTypeNode(type.root.node.falseType), type.mapper));
56196         }
56197         function getInferredTrueTypeFromConditionalType(type) {
56198             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.combinedMapper) : getTrueTypeFromConditionalType(type));
56199         }
56200         function getInferTypeParameters(node) {
56201             var result;
56202             if (node.locals) {
56203                 node.locals.forEach(function (symbol) {
56204                     if (symbol.flags & 262144 /* TypeParameter */) {
56205                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
56206                     }
56207                 });
56208             }
56209             return result;
56210         }
56211         function getTypeFromConditionalTypeNode(node) {
56212             var links = getNodeLinks(node);
56213             if (!links.resolvedType) {
56214                 var checkType = getTypeFromTypeNode(node.checkType);
56215                 var aliasSymbol = getAliasSymbolForTypeNode(node);
56216                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
56217                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
56218                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
56219                 var root = {
56220                     node: node,
56221                     checkType: checkType,
56222                     extendsType: getTypeFromTypeNode(node.extendsType),
56223                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
56224                     inferTypeParameters: getInferTypeParameters(node),
56225                     outerTypeParameters: outerTypeParameters,
56226                     instantiations: undefined,
56227                     aliasSymbol: aliasSymbol,
56228                     aliasTypeArguments: aliasTypeArguments
56229                 };
56230                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
56231                 if (outerTypeParameters) {
56232                     root.instantiations = new ts.Map();
56233                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
56234                 }
56235             }
56236             return links.resolvedType;
56237         }
56238         function getTypeFromInferTypeNode(node) {
56239             var links = getNodeLinks(node);
56240             if (!links.resolvedType) {
56241                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
56242             }
56243             return links.resolvedType;
56244         }
56245         function getIdentifierChain(node) {
56246             if (ts.isIdentifier(node)) {
56247                 return [node];
56248             }
56249             else {
56250                 return ts.append(getIdentifierChain(node.left), node.right);
56251             }
56252         }
56253         function getTypeFromImportTypeNode(node) {
56254             var links = getNodeLinks(node);
56255             if (!links.resolvedType) {
56256                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
56257                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
56258                     links.resolvedSymbol = unknownSymbol;
56259                     return links.resolvedType = errorType;
56260                 }
56261                 if (!ts.isLiteralImportTypeNode(node)) {
56262                     error(node.argument, ts.Diagnostics.String_literal_expected);
56263                     links.resolvedSymbol = unknownSymbol;
56264                     return links.resolvedType = errorType;
56265                 }
56266                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
56267                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
56268                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
56269                 if (!innerModuleSymbol) {
56270                     links.resolvedSymbol = unknownSymbol;
56271                     return links.resolvedType = errorType;
56272                 }
56273                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
56274                 if (!ts.nodeIsMissing(node.qualifier)) {
56275                     var nameStack = getIdentifierChain(node.qualifier);
56276                     var currentNamespace = moduleSymbol;
56277                     var current = void 0;
56278                     while (current = nameStack.shift()) {
56279                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
56280                         // typeof a.b.c is normally resolved using `checkExpression` which in turn defers to `checkQualifiedName`
56281                         // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from
56282                         // the `exports` lookup process that only looks up namespace members which is used for most type references
56283                         var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace));
56284                         var next = node.isTypeOf
56285                             ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText)
56286                             : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning);
56287                         if (!next) {
56288                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
56289                             return links.resolvedType = errorType;
56290                         }
56291                         getNodeLinks(current).resolvedSymbol = next;
56292                         getNodeLinks(current.parent).resolvedSymbol = next;
56293                         currentNamespace = next;
56294                     }
56295                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
56296                 }
56297                 else {
56298                     if (moduleSymbol.flags & targetMeaning) {
56299                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
56300                     }
56301                     else {
56302                         var errorMessage = targetMeaning === 111551 /* Value */
56303                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
56304                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
56305                         error(node, errorMessage, node.argument.literal.text);
56306                         links.resolvedSymbol = unknownSymbol;
56307                         links.resolvedType = errorType;
56308                     }
56309                 }
56310             }
56311             return links.resolvedType;
56312         }
56313         function resolveImportSymbolType(node, links, symbol, meaning) {
56314             var resolvedSymbol = resolveSymbol(symbol);
56315             links.resolvedSymbol = resolvedSymbol;
56316             if (meaning === 111551 /* Value */) {
56317                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
56318             }
56319             else {
56320                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
56321             }
56322         }
56323         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
56324             var links = getNodeLinks(node);
56325             if (!links.resolvedType) {
56326                 // Deferred resolution of members is handled by resolveObjectTypeMembers
56327                 var aliasSymbol = getAliasSymbolForTypeNode(node);
56328                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
56329                     links.resolvedType = emptyTypeLiteralType;
56330                 }
56331                 else {
56332                     var type = createObjectType(16 /* Anonymous */, node.symbol);
56333                     type.aliasSymbol = aliasSymbol;
56334                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
56335                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
56336                         type = createArrayType(type);
56337                     }
56338                     links.resolvedType = type;
56339                 }
56340             }
56341             return links.resolvedType;
56342         }
56343         function getAliasSymbolForTypeNode(node) {
56344             var host = node.parent;
56345             while (ts.isParenthesizedTypeNode(host) || ts.isJSDocTypeExpression(host) || ts.isTypeOperatorNode(host) && host.operator === 142 /* ReadonlyKeyword */) {
56346                 host = host.parent;
56347             }
56348             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
56349         }
56350         function getTypeArgumentsForAliasSymbol(symbol) {
56351             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
56352         }
56353         function isNonGenericObjectType(type) {
56354             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
56355         }
56356         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
56357             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
56358         }
56359         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
56360             if (type.types.length === 2) {
56361                 var firstType = type.types[0];
56362                 var secondType = type.types[1];
56363                 if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
56364                     return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
56365                 }
56366                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType)) {
56367                     return getAnonymousPartialType(secondType);
56368                 }
56369                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType)) {
56370                     return getAnonymousPartialType(firstType);
56371                 }
56372             }
56373             function getAnonymousPartialType(type) {
56374                 // gets the type as if it had been spread, but where everything in the spread is made optional
56375                 var members = ts.createSymbolTable();
56376                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
56377                     var prop = _a[_i];
56378                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
56379                         // do nothing, skip privates
56380                     }
56381                     else if (isSpreadableProperty(prop)) {
56382                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
56383                         var flags = 4 /* Property */ | 16777216 /* Optional */;
56384                         var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
56385                         result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
56386                         result.declarations = prop.declarations;
56387                         result.nameType = getSymbolLinks(prop).nameType;
56388                         result.syntheticOrigin = prop;
56389                         members.set(prop.escapedName, result);
56390                     }
56391                 }
56392                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
56393                 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56394                 return spread;
56395             }
56396         }
56397         /**
56398          * Since the source of spread types are object literals, which are not binary,
56399          * this function should be called in a left folding style, with left = previous result of getSpreadType
56400          * and right = the new element to be spread.
56401          */
56402         function getSpreadType(left, right, symbol, objectFlags, readonly) {
56403             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
56404                 return anyType;
56405             }
56406             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
56407                 return unknownType;
56408             }
56409             if (left.flags & 131072 /* Never */) {
56410                 return right;
56411             }
56412             if (right.flags & 131072 /* Never */) {
56413                 return left;
56414             }
56415             if (left.flags & 1048576 /* Union */) {
56416                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
56417                 if (merged) {
56418                     return getSpreadType(merged, right, symbol, objectFlags, readonly);
56419                 }
56420                 return checkCrossProductUnion([left, right])
56421                     ? mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); })
56422                     : errorType;
56423             }
56424             if (right.flags & 1048576 /* Union */) {
56425                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
56426                 if (merged) {
56427                     return getSpreadType(left, merged, symbol, objectFlags, readonly);
56428                 }
56429                 return checkCrossProductUnion([left, right])
56430                     ? mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); })
56431                     : errorType;
56432             }
56433             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
56434                 return left;
56435             }
56436             if (isGenericObjectType(left) || isGenericObjectType(right)) {
56437                 if (isEmptyObjectType(left)) {
56438                     return right;
56439                 }
56440                 // When the left type is an intersection, we may need to merge the last constituent of the
56441                 // intersection with the right type. For example when the left type is 'T & { a: string }'
56442                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
56443                 if (left.flags & 2097152 /* Intersection */) {
56444                     var types = left.types;
56445                     var lastLeft = types[types.length - 1];
56446                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
56447                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
56448                     }
56449                 }
56450                 return getIntersectionType([left, right]);
56451             }
56452             var members = ts.createSymbolTable();
56453             var skippedPrivateMembers = new ts.Set();
56454             var stringIndexInfo;
56455             var numberIndexInfo;
56456             if (left === emptyObjectType) {
56457                 // for the first spread element, left === emptyObjectType, so take the right's string indexer
56458                 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
56459                 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
56460             }
56461             else {
56462                 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
56463                 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
56464             }
56465             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
56466                 var rightProp = _a[_i];
56467                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
56468                     skippedPrivateMembers.add(rightProp.escapedName);
56469                 }
56470                 else if (isSpreadableProperty(rightProp)) {
56471                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
56472                 }
56473             }
56474             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
56475                 var leftProp = _c[_b];
56476                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
56477                     continue;
56478                 }
56479                 if (members.has(leftProp.escapedName)) {
56480                     var rightProp = members.get(leftProp.escapedName);
56481                     var rightType = getTypeOfSymbol(rightProp);
56482                     if (rightProp.flags & 16777216 /* Optional */) {
56483                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
56484                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
56485                         var result = createSymbol(flags, leftProp.escapedName);
56486                         result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
56487                         result.leftSpread = leftProp;
56488                         result.rightSpread = rightProp;
56489                         result.declarations = declarations;
56490                         result.nameType = getSymbolLinks(leftProp).nameType;
56491                         members.set(leftProp.escapedName, result);
56492                     }
56493                 }
56494                 else {
56495                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
56496                 }
56497             }
56498             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
56499             spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
56500             return spread;
56501         }
56502         /** We approximate own properties as non-methods plus methods that are inside the object literal */
56503         function isSpreadableProperty(prop) {
56504             return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
56505                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
56506                     !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
56507         }
56508         function getSpreadSymbol(prop, readonly) {
56509             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
56510             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
56511                 return prop;
56512             }
56513             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
56514             var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
56515             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
56516             result.declarations = prop.declarations;
56517             result.nameType = getSymbolLinks(prop).nameType;
56518             result.syntheticOrigin = prop;
56519             return result;
56520         }
56521         function getIndexInfoWithReadonly(info, readonly) {
56522             return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
56523         }
56524         function createLiteralType(flags, value, symbol) {
56525             var type = createType(flags);
56526             type.symbol = symbol;
56527             type.value = value;
56528             return type;
56529         }
56530         function getFreshTypeOfLiteralType(type) {
56531             if (type.flags & 2944 /* Literal */) {
56532                 if (!type.freshType) {
56533                     var freshType = createLiteralType(type.flags, type.value, type.symbol);
56534                     freshType.regularType = type;
56535                     freshType.freshType = freshType;
56536                     type.freshType = freshType;
56537                 }
56538                 return type.freshType;
56539             }
56540             return type;
56541         }
56542         function getRegularTypeOfLiteralType(type) {
56543             return type.flags & 2944 /* Literal */ ? type.regularType :
56544                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
56545                     type;
56546         }
56547         function isFreshLiteralType(type) {
56548             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
56549         }
56550         function getLiteralType(value, enumId, symbol) {
56551             // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
56552             // where NNN is the text representation of a numeric literal and SSS are the characters
56553             // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
56554             // EEE is a unique id for the containing enum type.
56555             var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
56556             var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
56557             var type = literalTypes.get(key);
56558             if (!type) {
56559                 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
56560                     typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
56561                     (enumId ? 1024 /* EnumLiteral */ : 0);
56562                 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
56563                 type.regularType = type;
56564             }
56565             return type;
56566         }
56567         function getTypeFromLiteralTypeNode(node) {
56568             if (node.literal.kind === 103 /* NullKeyword */) {
56569                 return nullType;
56570             }
56571             var links = getNodeLinks(node);
56572             if (!links.resolvedType) {
56573                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
56574             }
56575             return links.resolvedType;
56576         }
56577         function createUniqueESSymbolType(symbol) {
56578             var type = createType(8192 /* UniqueESSymbol */);
56579             type.symbol = symbol;
56580             type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
56581             return type;
56582         }
56583         function getESSymbolLikeTypeForNode(node) {
56584             if (ts.isValidESSymbolDeclaration(node)) {
56585                 var symbol = getSymbolOfNode(node);
56586                 var links = getSymbolLinks(symbol);
56587                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
56588             }
56589             return esSymbolType;
56590         }
56591         function getThisType(node) {
56592             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
56593             var parent = container && container.parent;
56594             if (parent && (ts.isClassLike(parent) || parent.kind === 253 /* InterfaceDeclaration */)) {
56595                 if (!ts.hasSyntacticModifier(container, 32 /* Static */) &&
56596                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
56597                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
56598                 }
56599             }
56600             // inside x.prototype = { ... }
56601             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
56602                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
56603             }
56604             // /** @return {this} */
56605             // x.prototype.m = function() { ... }
56606             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
56607             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
56608                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
56609             }
56610             // inside constructor function C() { ... }
56611             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
56612                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
56613             }
56614             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
56615             return errorType;
56616         }
56617         function getTypeFromThisTypeNode(node) {
56618             var links = getNodeLinks(node);
56619             if (!links.resolvedType) {
56620                 links.resolvedType = getThisType(node);
56621             }
56622             return links.resolvedType;
56623         }
56624         function getTypeFromRestTypeNode(node) {
56625             return getTypeFromTypeNode(getArrayElementTypeNode(node.type) || node.type);
56626         }
56627         function getArrayElementTypeNode(node) {
56628             switch (node.kind) {
56629                 case 186 /* ParenthesizedType */:
56630                     return getArrayElementTypeNode(node.type);
56631                 case 179 /* TupleType */:
56632                     if (node.elements.length === 1) {
56633                         node = node.elements[0];
56634                         if (node.kind === 181 /* RestType */ || node.kind === 192 /* NamedTupleMember */ && node.dotDotDotToken) {
56635                             return getArrayElementTypeNode(node.type);
56636                         }
56637                     }
56638                     break;
56639                 case 178 /* ArrayType */:
56640                     return node.elementType;
56641             }
56642             return undefined;
56643         }
56644         function getTypeFromNamedTupleTypeNode(node) {
56645             var links = getNodeLinks(node);
56646             return links.resolvedType || (links.resolvedType =
56647                 node.dotDotDotToken ? getTypeFromRestTypeNode(node) :
56648                     node.questionToken && strictNullChecks ? getOptionalType(getTypeFromTypeNode(node.type)) :
56649                         getTypeFromTypeNode(node.type));
56650         }
56651         function getTypeFromTypeNode(node) {
56652             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
56653         }
56654         function getTypeFromTypeNodeWorker(node) {
56655             switch (node.kind) {
56656                 case 128 /* AnyKeyword */:
56657                 case 303 /* JSDocAllType */:
56658                 case 304 /* JSDocUnknownType */:
56659                     return anyType;
56660                 case 152 /* UnknownKeyword */:
56661                     return unknownType;
56662                 case 147 /* StringKeyword */:
56663                     return stringType;
56664                 case 144 /* NumberKeyword */:
56665                     return numberType;
56666                 case 155 /* BigIntKeyword */:
56667                     return bigintType;
56668                 case 131 /* BooleanKeyword */:
56669                     return booleanType;
56670                 case 148 /* SymbolKeyword */:
56671                     return esSymbolType;
56672                 case 113 /* VoidKeyword */:
56673                     return voidType;
56674                 case 150 /* UndefinedKeyword */:
56675                     return undefinedType;
56676                 case 103 /* NullKeyword */:
56677                     // TODO(rbuckton): `NullKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service.
56678                     return nullType;
56679                 case 141 /* NeverKeyword */:
56680                     return neverType;
56681                 case 145 /* ObjectKeyword */:
56682                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
56683                 case 136 /* IntrinsicKeyword */:
56684                     return intrinsicMarkerType;
56685                 case 187 /* ThisType */:
56686                 case 107 /* ThisKeyword */:
56687                     // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`.
56688                     return getTypeFromThisTypeNode(node);
56689                 case 191 /* LiteralType */:
56690                     return getTypeFromLiteralTypeNode(node);
56691                 case 173 /* TypeReference */:
56692                     return getTypeFromTypeReference(node);
56693                 case 172 /* TypePredicate */:
56694                     return node.assertsModifier ? voidType : booleanType;
56695                 case 223 /* ExpressionWithTypeArguments */:
56696                     return getTypeFromTypeReference(node);
56697                 case 176 /* TypeQuery */:
56698                     return getTypeFromTypeQueryNode(node);
56699                 case 178 /* ArrayType */:
56700                 case 179 /* TupleType */:
56701                     return getTypeFromArrayOrTupleTypeNode(node);
56702                 case 180 /* OptionalType */:
56703                     return getTypeFromOptionalTypeNode(node);
56704                 case 182 /* UnionType */:
56705                     return getTypeFromUnionTypeNode(node);
56706                 case 183 /* IntersectionType */:
56707                     return getTypeFromIntersectionTypeNode(node);
56708                 case 305 /* JSDocNullableType */:
56709                     return getTypeFromJSDocNullableTypeNode(node);
56710                 case 307 /* JSDocOptionalType */:
56711                     return addOptionality(getTypeFromTypeNode(node.type));
56712                 case 192 /* NamedTupleMember */:
56713                     return getTypeFromNamedTupleTypeNode(node);
56714                 case 186 /* ParenthesizedType */:
56715                 case 306 /* JSDocNonNullableType */:
56716                 case 301 /* JSDocTypeExpression */:
56717                     return getTypeFromTypeNode(node.type);
56718                 case 181 /* RestType */:
56719                     return getTypeFromRestTypeNode(node);
56720                 case 309 /* JSDocVariadicType */:
56721                     return getTypeFromJSDocVariadicType(node);
56722                 case 174 /* FunctionType */:
56723                 case 175 /* ConstructorType */:
56724                 case 177 /* TypeLiteral */:
56725                 case 312 /* JSDocTypeLiteral */:
56726                 case 308 /* JSDocFunctionType */:
56727                 case 313 /* JSDocSignature */:
56728                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
56729                 case 188 /* TypeOperator */:
56730                     return getTypeFromTypeOperatorNode(node);
56731                 case 189 /* IndexedAccessType */:
56732                     return getTypeFromIndexedAccessTypeNode(node);
56733                 case 190 /* MappedType */:
56734                     return getTypeFromMappedTypeNode(node);
56735                 case 184 /* ConditionalType */:
56736                     return getTypeFromConditionalTypeNode(node);
56737                 case 185 /* InferType */:
56738                     return getTypeFromInferTypeNode(node);
56739                 case 193 /* TemplateLiteralType */:
56740                     return getTypeFromTemplateTypeNode(node);
56741                 case 195 /* ImportType */:
56742                     return getTypeFromImportTypeNode(node);
56743                 // This function assumes that an identifier, qualified name, or property access expression is a type expression
56744                 // Callers should first ensure this by calling `isPartOfTypeNode`
56745                 // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s.
56746                 case 78 /* Identifier */:
56747                 case 157 /* QualifiedName */:
56748                 case 201 /* PropertyAccessExpression */:
56749                     var symbol = getSymbolAtLocation(node);
56750                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
56751                 default:
56752                     return errorType;
56753             }
56754         }
56755         function instantiateList(items, mapper, instantiator) {
56756             if (items && items.length) {
56757                 for (var i = 0; i < items.length; i++) {
56758                     var item = items[i];
56759                     var mapped = instantiator(item, mapper);
56760                     if (item !== mapped) {
56761                         var result = i === 0 ? [] : items.slice(0, i);
56762                         result.push(mapped);
56763                         for (i++; i < items.length; i++) {
56764                             result.push(instantiator(items[i], mapper));
56765                         }
56766                         return result;
56767                     }
56768                 }
56769             }
56770             return items;
56771         }
56772         function instantiateTypes(types, mapper) {
56773             return instantiateList(types, mapper, instantiateType);
56774         }
56775         function instantiateSignatures(signatures, mapper) {
56776             return instantiateList(signatures, mapper, instantiateSignature);
56777         }
56778         function createTypeMapper(sources, targets) {
56779             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
56780         }
56781         function getMappedType(type, mapper) {
56782             switch (mapper.kind) {
56783                 case 0 /* Simple */:
56784                     return type === mapper.source ? mapper.target : type;
56785                 case 1 /* Array */:
56786                     var sources = mapper.sources;
56787                     var targets = mapper.targets;
56788                     for (var i = 0; i < sources.length; i++) {
56789                         if (type === sources[i]) {
56790                             return targets ? targets[i] : anyType;
56791                         }
56792                     }
56793                     return type;
56794                 case 2 /* Function */:
56795                     return mapper.func(type);
56796                 case 3 /* Composite */:
56797                 case 4 /* Merged */:
56798                     var t1 = getMappedType(type, mapper.mapper1);
56799                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
56800             }
56801         }
56802         function makeUnaryTypeMapper(source, target) {
56803             return { kind: 0 /* Simple */, source: source, target: target };
56804         }
56805         function makeArrayTypeMapper(sources, targets) {
56806             return { kind: 1 /* Array */, sources: sources, targets: targets };
56807         }
56808         function makeFunctionTypeMapper(func) {
56809             return { kind: 2 /* Function */, func: func };
56810         }
56811         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
56812             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
56813         }
56814         function createTypeEraser(sources) {
56815             return createTypeMapper(sources, /*targets*/ undefined);
56816         }
56817         /**
56818          * Maps forward-references to later types parameters to the empty object type.
56819          * This is used during inference when instantiating type parameter defaults.
56820          */
56821         function createBackreferenceMapper(context, index) {
56822             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
56823         }
56824         function combineTypeMappers(mapper1, mapper2) {
56825             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
56826         }
56827         function mergeTypeMappers(mapper1, mapper2) {
56828             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
56829         }
56830         function prependTypeMapping(source, target, mapper) {
56831             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
56832         }
56833         function appendTypeMapping(mapper, source, target) {
56834             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
56835         }
56836         function getRestrictiveTypeParameter(tp) {
56837             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
56838                 tp.restrictiveInstantiation.constraint = unknownType,
56839                 tp.restrictiveInstantiation);
56840         }
56841         function cloneTypeParameter(typeParameter) {
56842             var result = createTypeParameter(typeParameter.symbol);
56843             result.target = typeParameter;
56844             return result;
56845         }
56846         function instantiateTypePredicate(predicate, mapper) {
56847             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
56848         }
56849         function instantiateSignature(signature, mapper, eraseTypeParameters) {
56850             var freshTypeParameters;
56851             if (signature.typeParameters && !eraseTypeParameters) {
56852                 // First create a fresh set of type parameters, then include a mapping from the old to the
56853                 // new type parameters in the mapper function. Finally store this mapper in the new type
56854                 // parameters such that we can use it when instantiating constraints.
56855                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
56856                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
56857                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
56858                     var tp = freshTypeParameters_1[_i];
56859                     tp.mapper = mapper;
56860                 }
56861             }
56862             // Don't compute resolvedReturnType and resolvedTypePredicate now,
56863             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
56864             // See GH#17600.
56865             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
56866             /*resolvedReturnType*/ undefined, 
56867             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 19 /* PropagatingFlags */);
56868             result.target = signature;
56869             result.mapper = mapper;
56870             return result;
56871         }
56872         function instantiateSymbol(symbol, mapper) {
56873             var links = getSymbolLinks(symbol);
56874             if (links.type && !couldContainTypeVariables(links.type)) {
56875                 // If the type of the symbol is already resolved, and if that type could not possibly
56876                 // be affected by instantiation, simply return the symbol itself.
56877                 return symbol;
56878             }
56879             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
56880                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
56881                 // type mappers. This ensures that original type identities are properly preserved and that aliases
56882                 // always reference a non-aliases.
56883                 symbol = links.target;
56884                 mapper = combineTypeMappers(links.mapper, mapper);
56885             }
56886             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
56887             // also transient so that we can just store data on it directly.
56888             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
56889             result.declarations = symbol.declarations;
56890             result.parent = symbol.parent;
56891             result.target = symbol;
56892             result.mapper = mapper;
56893             if (symbol.valueDeclaration) {
56894                 result.valueDeclaration = symbol.valueDeclaration;
56895             }
56896             if (links.nameType) {
56897                 result.nameType = links.nameType;
56898             }
56899             return result;
56900         }
56901         function getObjectTypeInstantiation(type, mapper) {
56902             var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
56903             var links = getNodeLinks(declaration);
56904             var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType :
56905                 type.objectFlags & 64 /* Instantiated */ ? type.target : type;
56906             var typeParameters = links.outerTypeParameters;
56907             if (!typeParameters) {
56908                 // The first time an anonymous type is instantiated we compute and store a list of the type
56909                 // parameters that are in scope (and therefore potentially referenced). For type literals that
56910                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
56911                 // set of type parameters to those that are possibly referenced in the literal.
56912                 var outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ true);
56913                 if (isJSConstructor(declaration)) {
56914                     var templateTagParameters = getTypeParametersFromDeclaration(declaration);
56915                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
56916                 }
56917                 typeParameters = outerTypeParameters || ts.emptyArray;
56918                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
56919                     ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) :
56920                     typeParameters;
56921                 links.outerTypeParameters = typeParameters;
56922             }
56923             if (typeParameters.length) {
56924                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
56925                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
56926                 // instantiation cache key from the type IDs of the type arguments.
56927                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
56928                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
56929                 var id = getTypeListId(typeArguments);
56930                 if (!target.instantiations) {
56931                     target.instantiations = new ts.Map();
56932                     target.instantiations.set(getTypeListId(typeParameters), target);
56933                 }
56934                 var result = target.instantiations.get(id);
56935                 if (!result) {
56936                     var newMapper = createTypeMapper(typeParameters, typeArguments);
56937                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
56938                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
56939                             instantiateAnonymousType(target, newMapper);
56940                     target.instantiations.set(id, result);
56941                 }
56942                 return result;
56943             }
56944             return type;
56945         }
56946         function maybeTypeParameterReference(node) {
56947             return !(node.kind === 157 /* QualifiedName */ ||
56948                 node.parent.kind === 173 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
56949                 node.parent.kind === 195 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
56950         }
56951         function isTypeParameterPossiblyReferenced(tp, node) {
56952             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
56953             // between the node and the type parameter declaration, if the node contains actual references to the
56954             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
56955             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
56956                 var container = tp.symbol.declarations[0].parent;
56957                 for (var n = node; n !== container; n = n.parent) {
56958                     if (!n || n.kind === 230 /* Block */ || n.kind === 184 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
56959                         return true;
56960                     }
56961                 }
56962                 return !!ts.forEachChild(node, containsReference);
56963             }
56964             return true;
56965             function containsReference(node) {
56966                 switch (node.kind) {
56967                     case 187 /* ThisType */:
56968                         return !!tp.isThisType;
56969                     case 78 /* Identifier */:
56970                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
56971                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
56972                     case 176 /* TypeQuery */:
56973                         return true;
56974                 }
56975                 return !!ts.forEachChild(node, containsReference);
56976             }
56977         }
56978         function getHomomorphicTypeVariable(type) {
56979             var constraintType = getConstraintTypeFromMappedType(type);
56980             if (constraintType.flags & 4194304 /* Index */) {
56981                 var typeVariable = getActualTypeVariable(constraintType.type);
56982                 if (typeVariable.flags & 262144 /* TypeParameter */) {
56983                     return typeVariable;
56984                 }
56985             }
56986             return undefined;
56987         }
56988         function instantiateMappedType(type, mapper) {
56989             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
56990             // operation depends on T as follows:
56991             // * If T is a primitive type no mapping is performed and the result is simply T.
56992             // * If T is a union type we distribute the mapped type over the union.
56993             // * If T is an array we map to an array where the element type has been transformed.
56994             // * If T is a tuple we map to a tuple where the element types have been transformed.
56995             // * Otherwise we map to an object type where the type of each property has been transformed.
56996             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
56997             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
56998             // { [P in keyof A]: X } | undefined.
56999             var typeVariable = getHomomorphicTypeVariable(type);
57000             if (typeVariable) {
57001                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
57002                 if (typeVariable !== mappedTypeVariable) {
57003                     return mapType(getReducedType(mappedTypeVariable), function (t) {
57004                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
57005                             if (!type.declaration.nameType) {
57006                                 if (isArrayType(t)) {
57007                                     return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper));
57008                                 }
57009                                 if (isGenericTupleType(t)) {
57010                                     return instantiateMappedGenericTupleType(t, type, typeVariable, mapper);
57011                                 }
57012                                 if (isTupleType(t)) {
57013                                     return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper));
57014                                 }
57015                             }
57016                             return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper));
57017                         }
57018                         return t;
57019                     });
57020                 }
57021             }
57022             return instantiateAnonymousType(type, mapper);
57023         }
57024         function getModifiedReadonlyState(state, modifiers) {
57025             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
57026         }
57027         function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) {
57028             // When a tuple type is generic (i.e. when it contains variadic elements), we want to eagerly map the
57029             // non-generic elements and defer mapping the generic elements. In order to facilitate this, we transform
57030             // M<[A, B?, ...T, ...C[]] into [...M<[A]>, ...M<[B?]>, ...M<T>, ...M<C[]>] and then rely on tuple type
57031             // normalization to resolve the non-generic parts of the resulting tuple.
57032             var elementFlags = tupleType.target.elementFlags;
57033             var elementTypes = ts.map(getTypeArguments(tupleType), function (t, i) {
57034                 var singleton = elementFlags[i] & 8 /* Variadic */ ? t :
57035                     elementFlags[i] & 4 /* Rest */ ? createArrayType(t) :
57036                         createTupleType([t], [elementFlags[i]]);
57037                 // The singleton is never a generic tuple type, so it is safe to recurse here.
57038                 return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper));
57039             });
57040             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, getMappedTypeModifiers(mappedType));
57041             return createTupleType(elementTypes, ts.map(elementTypes, function (_) { return 8 /* Variadic */; }), newReadonly);
57042         }
57043         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
57044             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
57045             return elementType === errorType ? errorType :
57046                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
57047         }
57048         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
57049             var elementFlags = tupleType.target.elementFlags;
57050             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
57051                 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper);
57052             });
57053             var modifiers = getMappedTypeModifiers(mappedType);
57054             var newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? 2 /* Optional */ : f; }) :
57055                 modifiers & 8 /* ExcludeOptional */ ? ts.map(elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
57056                     elementFlags;
57057             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
57058             return ts.contains(elementTypes, errorType) ? errorType :
57059                 createTupleType(elementTypes, newTupleModifiers, newReadonly, tupleType.target.labeledElementDeclarations);
57060         }
57061         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
57062             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
57063             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
57064             var modifiers = getMappedTypeModifiers(type);
57065             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
57066                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
57067                     propType;
57068         }
57069         function instantiateAnonymousType(type, mapper) {
57070             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
57071             if (type.objectFlags & 32 /* Mapped */) {
57072                 result.declaration = type.declaration;
57073                 // C.f. instantiateSignature
57074                 var origTypeParameter = getTypeParameterFromMappedType(type);
57075                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
57076                 result.typeParameter = freshTypeParameter;
57077                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
57078                 freshTypeParameter.mapper = mapper;
57079             }
57080             result.target = type;
57081             result.mapper = mapper;
57082             result.aliasSymbol = type.aliasSymbol;
57083             result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
57084             return result;
57085         }
57086         function getConditionalTypeInstantiation(type, mapper) {
57087             var root = type.root;
57088             if (root.outerTypeParameters) {
57089                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
57090                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
57091                 // instantiation cache key from the type IDs of the type arguments.
57092                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
57093                 var id = getTypeListId(typeArguments);
57094                 var result = root.instantiations.get(id);
57095                 if (!result) {
57096                     var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
57097                     result = instantiateConditionalType(root, newMapper);
57098                     root.instantiations.set(id, result);
57099                 }
57100                 return result;
57101             }
57102             return type;
57103         }
57104         function instantiateConditionalType(root, mapper) {
57105             // Check if we have a conditional type where the check type is a naked type parameter. If so,
57106             // the conditional type is distributive over union types and when T is instantiated to a union
57107             // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
57108             if (root.isDistributive) {
57109                 var checkType_1 = root.checkType;
57110                 var instantiatedType = getMappedType(checkType_1, mapper);
57111                 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
57112                     return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
57113                 }
57114             }
57115             return getConditionalType(root, mapper);
57116         }
57117         function instantiateType(type, mapper) {
57118             if (!(type && mapper && couldContainTypeVariables(type))) {
57119                 return type;
57120             }
57121             if (instantiationDepth === 50 || instantiationCount >= 5000000) {
57122                 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
57123                 // with a combination of infinite generic types that perpetually generate new type identities. We stop
57124                 // the recursion here by yielding the error type.
57125                 ts.tracing.instant("check" /* Check */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount });
57126                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
57127                 return errorType;
57128             }
57129             totalInstantiationCount++;
57130             instantiationCount++;
57131             instantiationDepth++;
57132             var result = instantiateTypeWorker(type, mapper);
57133             instantiationDepth--;
57134             return result;
57135         }
57136         function instantiateTypeWorker(type, mapper) {
57137             var flags = type.flags;
57138             if (flags & 262144 /* TypeParameter */) {
57139                 return getMappedType(type, mapper);
57140             }
57141             if (flags & 524288 /* Object */) {
57142                 var objectFlags = type.objectFlags;
57143                 if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) {
57144                     if (objectFlags & 4 /* Reference */ && !(type.node)) {
57145                         var resolvedTypeArguments = type.resolvedTypeArguments;
57146                         var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
57147                         return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type;
57148                     }
57149                     return getObjectTypeInstantiation(type, mapper);
57150                 }
57151                 return type;
57152             }
57153             if (flags & 3145728 /* UnionOrIntersection */) {
57154                 var types = type.types;
57155                 var newTypes = instantiateTypes(types, mapper);
57156                 return newTypes === types ? type :
57157                     flags & 2097152 /* Intersection */ ?
57158                         getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) :
57159                         getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
57160             }
57161             if (flags & 4194304 /* Index */) {
57162                 return getIndexType(instantiateType(type.type, mapper));
57163             }
57164             if (flags & 134217728 /* TemplateLiteral */) {
57165                 return getTemplateLiteralType(type.texts, instantiateTypes(type.types, mapper));
57166             }
57167             if (flags & 268435456 /* StringMapping */) {
57168                 return getStringMappingType(type.symbol, instantiateType(type.type, mapper));
57169             }
57170             if (flags & 8388608 /* IndexedAccess */) {
57171                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
57172             }
57173             if (flags & 16777216 /* Conditional */) {
57174                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
57175             }
57176             if (flags & 33554432 /* Substitution */) {
57177                 var maybeVariable = instantiateType(type.baseType, mapper);
57178                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
57179                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
57180                 }
57181                 else {
57182                     var sub = instantiateType(type.substitute, mapper);
57183                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
57184                         return maybeVariable;
57185                     }
57186                     return sub;
57187                 }
57188             }
57189             return type;
57190         }
57191         function getPermissiveInstantiation(type) {
57192             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
57193                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
57194         }
57195         function getRestrictiveInstantiation(type) {
57196             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
57197                 return type;
57198             }
57199             if (type.restrictiveInstantiation) {
57200                 return type.restrictiveInstantiation;
57201             }
57202             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
57203             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
57204             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
57205             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
57206             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
57207             // are constrained to `unknown` and produce tons of false positives/negatives!
57208             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
57209             return type.restrictiveInstantiation;
57210         }
57211         function instantiateIndexInfo(info, mapper) {
57212             return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
57213         }
57214         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
57215         // that is subject to contextual typing.
57216         function isContextSensitive(node) {
57217             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
57218             switch (node.kind) {
57219                 case 208 /* FunctionExpression */:
57220                 case 209 /* ArrowFunction */:
57221                 case 165 /* MethodDeclaration */:
57222                 case 251 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
57223                     return isContextSensitiveFunctionLikeDeclaration(node);
57224                 case 200 /* ObjectLiteralExpression */:
57225                     return ts.some(node.properties, isContextSensitive);
57226                 case 199 /* ArrayLiteralExpression */:
57227                     return ts.some(node.elements, isContextSensitive);
57228                 case 217 /* ConditionalExpression */:
57229                     return isContextSensitive(node.whenTrue) ||
57230                         isContextSensitive(node.whenFalse);
57231                 case 216 /* BinaryExpression */:
57232                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
57233                         (isContextSensitive(node.left) || isContextSensitive(node.right));
57234                 case 288 /* PropertyAssignment */:
57235                     return isContextSensitive(node.initializer);
57236                 case 207 /* ParenthesizedExpression */:
57237                     return isContextSensitive(node.expression);
57238                 case 281 /* JsxAttributes */:
57239                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
57240                 case 280 /* JsxAttribute */: {
57241                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
57242                     var initializer = node.initializer;
57243                     return !!initializer && isContextSensitive(initializer);
57244                 }
57245                 case 283 /* JsxExpression */: {
57246                     // It is possible to that node.expression is undefined (e.g <div x={} />)
57247                     var expression = node.expression;
57248                     return !!expression && isContextSensitive(expression);
57249                 }
57250             }
57251             return false;
57252         }
57253         function isContextSensitiveFunctionLikeDeclaration(node) {
57254             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
57255                 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
57256         }
57257         function hasContextSensitiveParameters(node) {
57258             // Functions with type parameters are not context sensitive.
57259             if (!node.typeParameters) {
57260                 // Functions with any parameters that lack type annotations are context sensitive.
57261                 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
57262                     return true;
57263                 }
57264                 if (node.kind !== 209 /* ArrowFunction */) {
57265                     // If the first parameter is not an explicit 'this' parameter, then the function has
57266                     // an implicit 'this' parameter which is subject to contextual typing.
57267                     var parameter = ts.firstOrUndefined(node.parameters);
57268                     if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
57269                         return true;
57270                     }
57271                 }
57272             }
57273             return false;
57274         }
57275         function hasContextSensitiveReturnExpression(node) {
57276             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
57277             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 230 /* Block */ && isContextSensitive(node.body);
57278         }
57279         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
57280             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
57281                 isContextSensitiveFunctionLikeDeclaration(func);
57282         }
57283         function getTypeWithoutSignatures(type) {
57284             if (type.flags & 524288 /* Object */) {
57285                 var resolved = resolveStructuredTypeMembers(type);
57286                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
57287                     var result = createObjectType(16 /* Anonymous */, type.symbol);
57288                     result.members = resolved.members;
57289                     result.properties = resolved.properties;
57290                     result.callSignatures = ts.emptyArray;
57291                     result.constructSignatures = ts.emptyArray;
57292                     return result;
57293                 }
57294             }
57295             else if (type.flags & 2097152 /* Intersection */) {
57296                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
57297             }
57298             return type;
57299         }
57300         // TYPE CHECKING
57301         function isTypeIdenticalTo(source, target) {
57302             return isTypeRelatedTo(source, target, identityRelation);
57303         }
57304         function compareTypesIdentical(source, target) {
57305             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
57306         }
57307         function compareTypesAssignable(source, target) {
57308             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
57309         }
57310         function compareTypesSubtypeOf(source, target) {
57311             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
57312         }
57313         function isTypeSubtypeOf(source, target) {
57314             return isTypeRelatedTo(source, target, subtypeRelation);
57315         }
57316         function isTypeAssignableTo(source, target) {
57317             return isTypeRelatedTo(source, target, assignableRelation);
57318         }
57319         // An object type S is considered to be derived from an object type T if
57320         // S is a union type and every constituent of S is derived from T,
57321         // T is a union type and S is derived from at least one constituent of T, or
57322         // S is a type variable with a base constraint that is derived from T,
57323         // T is one of the global types Object and Function and S is a subtype of T, or
57324         // T occurs directly or indirectly in an 'extends' clause of S.
57325         // Note that this check ignores type parameters and only considers the
57326         // inheritance hierarchy.
57327         function isTypeDerivedFrom(source, target) {
57328             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
57329                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
57330                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
57331                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
57332                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
57333                                 hasBaseType(source, getTargetType(target)) || (isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType));
57334         }
57335         /**
57336          * This is *not* a bi-directional relationship.
57337          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
57338          *
57339          * 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.
57340          * It is used to check following cases:
57341          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
57342          *   - the types of `case` clause expressions and their respective `switch` expressions.
57343          *   - the type of an expression in a type assertion with the type being asserted.
57344          */
57345         function isTypeComparableTo(source, target) {
57346             return isTypeRelatedTo(source, target, comparableRelation);
57347         }
57348         function areTypesComparable(type1, type2) {
57349             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
57350         }
57351         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
57352             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
57353         }
57354         /**
57355          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
57356          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
57357          */
57358         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
57359             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
57360         }
57361         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
57362             if (isTypeRelatedTo(source, target, relation))
57363                 return true;
57364             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
57365                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
57366             }
57367             return false;
57368         }
57369         function isOrHasGenericConditional(type) {
57370             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
57371         }
57372         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
57373             if (!node || isOrHasGenericConditional(target))
57374                 return false;
57375             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
57376                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
57377                 return true;
57378             }
57379             switch (node.kind) {
57380                 case 283 /* JsxExpression */:
57381                 case 207 /* ParenthesizedExpression */:
57382                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
57383                 case 216 /* BinaryExpression */:
57384                     switch (node.operatorToken.kind) {
57385                         case 62 /* EqualsToken */:
57386                         case 27 /* CommaToken */:
57387                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
57388                     }
57389                     break;
57390                 case 200 /* ObjectLiteralExpression */:
57391                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
57392                 case 199 /* ArrayLiteralExpression */:
57393                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
57394                 case 281 /* JsxAttributes */:
57395                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
57396                 case 209 /* ArrowFunction */:
57397                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
57398             }
57399             return false;
57400         }
57401         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
57402             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
57403             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
57404             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
57405                 var signatures = _a[_i];
57406                 if (ts.some(signatures, function (s) {
57407                     var returnType = getReturnTypeOfSignature(s);
57408                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
57409                 })) {
57410                     var resultObj = errorOutputContainer || {};
57411                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
57412                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
57413                     ts.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));
57414                     return true;
57415                 }
57416             }
57417             return false;
57418         }
57419         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
57420             // Don't elaborate blocks
57421             if (ts.isBlock(node.body)) {
57422                 return false;
57423             }
57424             // Or functions with annotated parameter types
57425             if (ts.some(node.parameters, ts.hasType)) {
57426                 return false;
57427             }
57428             var sourceSig = getSingleCallSignature(source);
57429             if (!sourceSig) {
57430                 return false;
57431             }
57432             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
57433             if (!ts.length(targetSignatures)) {
57434                 return false;
57435             }
57436             var returnExpression = node.body;
57437             var sourceReturn = getReturnTypeOfSignature(sourceSig);
57438             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
57439             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
57440                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57441                 if (elaborated) {
57442                     return elaborated;
57443                 }
57444                 var resultObj = errorOutputContainer || {};
57445                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
57446                 if (resultObj.errors) {
57447                     if (target.symbol && ts.length(target.symbol.declarations)) {
57448                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
57449                     }
57450                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
57451                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
57452                         // an IPromise and a Promise that are slightly different
57453                         && !getTypeOfPropertyOfType(sourceReturn, "then")
57454                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
57455                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
57456                     }
57457                     return true;
57458                 }
57459             }
57460             return false;
57461         }
57462         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
57463             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
57464             if (idx) {
57465                 return idx;
57466             }
57467             if (target.flags & 1048576 /* Union */) {
57468                 var best = getBestMatchingType(source, target);
57469                 if (best) {
57470                     return getIndexedAccessTypeOrUndefined(best, nameType);
57471                 }
57472             }
57473         }
57474         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
57475             next.contextualType = sourcePropType;
57476             try {
57477                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
57478             }
57479             finally {
57480                 next.contextualType = undefined;
57481             }
57482         }
57483         /**
57484          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
57485          * 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`
57486          * Otherwise, we issue an error on _every_ element which fail the assignability check
57487          */
57488         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
57489             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
57490             var reportedError = false;
57491             for (var status = iterator.next(); !status.done; status = iterator.next()) {
57492                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
57493                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
57494                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
57495                     continue; // Don't elaborate on indexes on generic variables
57496                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
57497                 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
57498                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57499                     if (elaborated) {
57500                         reportedError = true;
57501                     }
57502                     else {
57503                         // Issue error on the prop itself, since the prop couldn't elaborate the error
57504                         var resultObj = errorOutputContainer || {};
57505                         // Use the expression type, if available
57506                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
57507                         var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
57508                         if (result && specificSource !== sourcePropType) {
57509                             // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
57510                             checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
57511                         }
57512                         if (resultObj.errors) {
57513                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
57514                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
57515                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
57516                             var issuedElaboration = false;
57517                             if (!targetProp) {
57518                                 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
57519                                     getIndexInfoOfType(target, 0 /* String */) ||
57520                                     undefined;
57521                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
57522                                     issuedElaboration = true;
57523                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
57524                                 }
57525                             }
57526                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
57527                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
57528                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
57529                                     ts.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)));
57530                                 }
57531                             }
57532                         }
57533                         reportedError = true;
57534                     }
57535                 }
57536             }
57537             return reportedError;
57538         }
57539         function generateJsxAttributes(node) {
57540             var _i, _a, prop;
57541             return __generator(this, function (_b) {
57542                 switch (_b.label) {
57543                     case 0:
57544                         if (!ts.length(node.properties))
57545                             return [2 /*return*/];
57546                         _i = 0, _a = node.properties;
57547                         _b.label = 1;
57548                     case 1:
57549                         if (!(_i < _a.length)) return [3 /*break*/, 4];
57550                         prop = _a[_i];
57551                         if (ts.isJsxSpreadAttribute(prop))
57552                             return [3 /*break*/, 3];
57553                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
57554                     case 2:
57555                         _b.sent();
57556                         _b.label = 3;
57557                     case 3:
57558                         _i++;
57559                         return [3 /*break*/, 1];
57560                     case 4: return [2 /*return*/];
57561                 }
57562             });
57563         }
57564         function generateJsxChildren(node, getInvalidTextDiagnostic) {
57565             var memberOffset, i, child, nameType, elem;
57566             return __generator(this, function (_a) {
57567                 switch (_a.label) {
57568                     case 0:
57569                         if (!ts.length(node.children))
57570                             return [2 /*return*/];
57571                         memberOffset = 0;
57572                         i = 0;
57573                         _a.label = 1;
57574                     case 1:
57575                         if (!(i < node.children.length)) return [3 /*break*/, 5];
57576                         child = node.children[i];
57577                         nameType = getLiteralType(i - memberOffset);
57578                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
57579                         if (!elem) return [3 /*break*/, 3];
57580                         return [4 /*yield*/, elem];
57581                     case 2:
57582                         _a.sent();
57583                         return [3 /*break*/, 4];
57584                     case 3:
57585                         memberOffset++;
57586                         _a.label = 4;
57587                     case 4:
57588                         i++;
57589                         return [3 /*break*/, 1];
57590                     case 5: return [2 /*return*/];
57591                 }
57592             });
57593         }
57594         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
57595             switch (child.kind) {
57596                 case 283 /* JsxExpression */:
57597                     // child is of the type of the expression
57598                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
57599                 case 11 /* JsxText */:
57600                     if (child.containsOnlyTriviaWhiteSpaces) {
57601                         break; // Whitespace only jsx text isn't real jsx text
57602                     }
57603                     // child is a string
57604                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
57605                 case 273 /* JsxElement */:
57606                 case 274 /* JsxSelfClosingElement */:
57607                 case 277 /* JsxFragment */:
57608                     // child is of type JSX.Element
57609                     return { errorNode: child, innerExpression: child, nameType: nameType };
57610                 default:
57611                     return ts.Debug.assertNever(child, "Found invalid jsx child");
57612             }
57613         }
57614         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
57615             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
57616             var invalidTextDiagnostic;
57617             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
57618                 var containingElement = node.parent.parent;
57619                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
57620                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
57621                 var childrenNameType = getLiteralType(childrenPropName);
57622                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
57623                 var validChildren = ts.getSemanticJsxChildren(containingElement.children);
57624                 if (!ts.length(validChildren)) {
57625                     return result;
57626                 }
57627                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
57628                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
57629                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
57630                 if (moreThanOneRealChildren) {
57631                     if (arrayLikeTargetParts !== neverType) {
57632                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
57633                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
57634                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
57635                     }
57636                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
57637                         // arity mismatch
57638                         result = true;
57639                         var diag = error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType));
57640                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
57641                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
57642                         }
57643                     }
57644                 }
57645                 else {
57646                     if (nonArrayLikeTargetParts !== neverType) {
57647                         var child = validChildren[0];
57648                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
57649                         if (elem_1) {
57650                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
57651                                 switch (_a.label) {
57652                                     case 0: return [4 /*yield*/, elem_1];
57653                                     case 1:
57654                                         _a.sent();
57655                                         return [2 /*return*/];
57656                                 }
57657                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
57658                         }
57659                     }
57660                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
57661                         // arity mismatch
57662                         result = true;
57663                         var diag = error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType));
57664                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
57665                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
57666                         }
57667                     }
57668                 }
57669             }
57670             return result;
57671             function getInvalidTextualChildDiagnostic() {
57672                 if (!invalidTextDiagnostic) {
57673                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
57674                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
57675                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
57676                     var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
57677                     var diagnostic = ts.Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2;
57678                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
57679                 }
57680                 return invalidTextDiagnostic;
57681             }
57682         }
57683         function generateLimitedTupleElements(node, target) {
57684             var len, i, elem, nameType;
57685             return __generator(this, function (_a) {
57686                 switch (_a.label) {
57687                     case 0:
57688                         len = ts.length(node.elements);
57689                         if (!len)
57690                             return [2 /*return*/];
57691                         i = 0;
57692                         _a.label = 1;
57693                     case 1:
57694                         if (!(i < len)) return [3 /*break*/, 4];
57695                         // 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
57696                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
57697                             return [3 /*break*/, 3];
57698                         elem = node.elements[i];
57699                         if (ts.isOmittedExpression(elem))
57700                             return [3 /*break*/, 3];
57701                         nameType = getLiteralType(i);
57702                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
57703                     case 2:
57704                         _a.sent();
57705                         _a.label = 3;
57706                     case 3:
57707                         i++;
57708                         return [3 /*break*/, 1];
57709                     case 4: return [2 /*return*/];
57710                 }
57711             });
57712         }
57713         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
57714             if (target.flags & 131068 /* Primitive */)
57715                 return false;
57716             if (isTupleLikeType(source)) {
57717                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
57718             }
57719             // recreate a tuple from the elements, if possible
57720             // Since we're re-doing the expression type, we need to reapply the contextual type
57721             var oldContext = node.contextualType;
57722             node.contextualType = target;
57723             try {
57724                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
57725                 node.contextualType = oldContext;
57726                 if (isTupleLikeType(tupleizedType)) {
57727                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
57728                 }
57729                 return false;
57730             }
57731             finally {
57732                 node.contextualType = oldContext;
57733             }
57734         }
57735         function generateObjectLiteralElements(node) {
57736             var _i, _a, prop, type, _b;
57737             return __generator(this, function (_c) {
57738                 switch (_c.label) {
57739                     case 0:
57740                         if (!ts.length(node.properties))
57741                             return [2 /*return*/];
57742                         _i = 0, _a = node.properties;
57743                         _c.label = 1;
57744                     case 1:
57745                         if (!(_i < _a.length)) return [3 /*break*/, 8];
57746                         prop = _a[_i];
57747                         if (ts.isSpreadAssignment(prop))
57748                             return [3 /*break*/, 7];
57749                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
57750                         if (!type || (type.flags & 131072 /* Never */)) {
57751                             return [3 /*break*/, 7];
57752                         }
57753                         _b = prop.kind;
57754                         switch (_b) {
57755                             case 168 /* SetAccessor */: return [3 /*break*/, 2];
57756                             case 167 /* GetAccessor */: return [3 /*break*/, 2];
57757                             case 165 /* MethodDeclaration */: return [3 /*break*/, 2];
57758                             case 289 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
57759                             case 288 /* PropertyAssignment */: return [3 /*break*/, 4];
57760                         }
57761                         return [3 /*break*/, 6];
57762                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
57763                     case 3:
57764                         _c.sent();
57765                         return [3 /*break*/, 7];
57766                     case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: ts.isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }];
57767                     case 5:
57768                         _c.sent();
57769                         return [3 /*break*/, 7];
57770                     case 6:
57771                         ts.Debug.assertNever(prop);
57772                         _c.label = 7;
57773                     case 7:
57774                         _i++;
57775                         return [3 /*break*/, 1];
57776                     case 8: return [2 /*return*/];
57777                 }
57778             });
57779         }
57780         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
57781             if (target.flags & 131068 /* Primitive */)
57782                 return false;
57783             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
57784         }
57785         /**
57786          * This is *not* a bi-directional relationship.
57787          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
57788          */
57789         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
57790             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
57791         }
57792         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
57793             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
57794             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
57795         }
57796         /**
57797          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
57798          */
57799         function isAnySignature(s) {
57800             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
57801                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
57802                 isTypeAny(getReturnTypeOfSignature(s));
57803         }
57804         /**
57805          * See signatureRelatedTo, compareSignaturesIdentical
57806          */
57807         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
57808             // TODO (drosen): De-duplicate code between related functions.
57809             if (source === target) {
57810                 return -1 /* True */;
57811             }
57812             if (isAnySignature(target)) {
57813                 return -1 /* True */;
57814             }
57815             var targetCount = getParameterCount(target);
57816             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
57817                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
57818             if (sourceHasMoreParameters) {
57819                 return 0 /* False */;
57820             }
57821             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
57822                 target = getCanonicalSignature(target);
57823                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
57824             }
57825             var sourceCount = getParameterCount(source);
57826             var sourceRestType = getNonArrayRestType(source);
57827             var targetRestType = getNonArrayRestType(target);
57828             if (sourceRestType || targetRestType) {
57829                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
57830             }
57831             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
57832                 // We're not able to relate misaligned complex rest parameters
57833                 return 0 /* False */;
57834             }
57835             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
57836             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 165 /* MethodDeclaration */ &&
57837                 kind !== 164 /* MethodSignature */ && kind !== 166 /* Constructor */;
57838             var result = -1 /* True */;
57839             var sourceThisType = getThisTypeOfSignature(source);
57840             if (sourceThisType && sourceThisType !== voidType) {
57841                 var targetThisType = getThisTypeOfSignature(target);
57842                 if (targetThisType) {
57843                     // void sources are assignable to anything.
57844                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
57845                         || compareTypes(targetThisType, sourceThisType, reportErrors);
57846                     if (!related) {
57847                         if (reportErrors) {
57848                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
57849                         }
57850                         return 0 /* False */;
57851                     }
57852                     result &= related;
57853                 }
57854             }
57855             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
57856             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
57857             for (var i = 0; i < paramCount; i++) {
57858                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : tryGetTypeAtPosition(source, i);
57859                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : tryGetTypeAtPosition(target, i);
57860                 if (sourceType && targetType) {
57861                     // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
57862                     // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
57863                     // they naturally relate only contra-variantly). However, if the source and target parameters both have
57864                     // function types with a single call signature, we know we are relating two callback parameters. In
57865                     // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
57866                     // similar to return values, callback parameters are output positions. This means that a Promise<T>,
57867                     // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
57868                     // with respect to T.
57869                     var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
57870                     var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
57871                     var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
57872                         (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
57873                     var related = callbacks ?
57874                         compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
57875                         !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
57876                     // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
57877                     if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
57878                         related = 0 /* False */;
57879                     }
57880                     if (!related) {
57881                         if (reportErrors) {
57882                             errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
57883                         }
57884                         return 0 /* False */;
57885                     }
57886                     result &= related;
57887                 }
57888             }
57889             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
57890                 // If a signature resolution is already in-flight, skip issuing a circularity error
57891                 // here and just use the `any` type directly
57892                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
57893                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
57894                         : getReturnTypeOfSignature(target);
57895                 if (targetReturnType === voidType) {
57896                     return result;
57897                 }
57898                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
57899                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
57900                         : getReturnTypeOfSignature(source);
57901                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
57902                 var targetTypePredicate = getTypePredicateOfSignature(target);
57903                 if (targetTypePredicate) {
57904                     var sourceTypePredicate = getTypePredicateOfSignature(source);
57905                     if (sourceTypePredicate) {
57906                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
57907                     }
57908                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
57909                         if (reportErrors) {
57910                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
57911                         }
57912                         return 0 /* False */;
57913                     }
57914                 }
57915                 else {
57916                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
57917                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
57918                     // wouldn't be co-variant for T without this rule.
57919                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
57920                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
57921                     if (!result && reportErrors && incompatibleErrorReporter) {
57922                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
57923                     }
57924                 }
57925             }
57926             return result;
57927         }
57928         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
57929             if (source.kind !== target.kind) {
57930                 if (reportErrors) {
57931                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
57932                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
57933                 }
57934                 return 0 /* False */;
57935             }
57936             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
57937                 if (source.parameterIndex !== target.parameterIndex) {
57938                     if (reportErrors) {
57939                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
57940                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
57941                     }
57942                     return 0 /* False */;
57943                 }
57944             }
57945             var related = source.type === target.type ? -1 /* True */ :
57946                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
57947                     0 /* False */;
57948             if (related === 0 /* False */ && reportErrors) {
57949                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
57950             }
57951             return related;
57952         }
57953         function isImplementationCompatibleWithOverload(implementation, overload) {
57954             var erasedSource = getErasedSignature(implementation);
57955             var erasedTarget = getErasedSignature(overload);
57956             // First see if the return types are compatible in either direction.
57957             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
57958             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
57959             if (targetReturnType === voidType
57960                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
57961                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
57962                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
57963             }
57964             return false;
57965         }
57966         function isEmptyResolvedType(t) {
57967             return t !== anyFunctionType &&
57968                 t.properties.length === 0 &&
57969                 t.callSignatures.length === 0 &&
57970                 t.constructSignatures.length === 0 &&
57971                 !t.stringIndexInfo &&
57972                 !t.numberIndexInfo;
57973         }
57974         function isEmptyObjectType(type) {
57975             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
57976                 type.flags & 67108864 /* NonPrimitive */ ? true :
57977                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
57978                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
57979                             false;
57980         }
57981         function isEmptyAnonymousObjectType(type) {
57982             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */ && (type.members && isEmptyResolvedType(type) ||
57983                 type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0));
57984         }
57985         function isStringIndexSignatureOnlyType(type) {
57986             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
57987                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
57988                 false;
57989         }
57990         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
57991             if (sourceSymbol === targetSymbol) {
57992                 return true;
57993             }
57994             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
57995             var entry = enumRelation.get(id);
57996             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
57997                 return !!(entry & 1 /* Succeeded */);
57998             }
57999             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
58000                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
58001                 return false;
58002             }
58003             var targetEnumType = getTypeOfSymbol(targetSymbol);
58004             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
58005                 var property = _a[_i];
58006                 if (property.flags & 8 /* EnumMember */) {
58007                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
58008                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
58009                         if (errorReporter) {
58010                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
58011                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
58012                         }
58013                         else {
58014                             enumRelation.set(id, 2 /* Failed */);
58015                         }
58016                         return false;
58017                     }
58018                 }
58019             }
58020             enumRelation.set(id, 1 /* Succeeded */);
58021             return true;
58022         }
58023         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
58024             var s = source.flags;
58025             var t = target.flags;
58026             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
58027                 return true;
58028             if (t & 131072 /* Never */)
58029                 return false;
58030             if (s & 402653316 /* StringLike */ && t & 4 /* String */)
58031                 return true;
58032             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
58033                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
58034                 source.value === target.value)
58035                 return true;
58036             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
58037                 return true;
58038             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
58039                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
58040                 source.value === target.value)
58041                 return true;
58042             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
58043                 return true;
58044             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
58045                 return true;
58046             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
58047                 return true;
58048             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
58049                 return true;
58050             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
58051                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
58052                     return true;
58053                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
58054                     source.value === target.value &&
58055                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
58056                     return true;
58057             }
58058             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
58059                 return true;
58060             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
58061                 return true;
58062             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
58063                 return true;
58064             if (relation === assignableRelation || relation === comparableRelation) {
58065                 if (s & 1 /* Any */)
58066                     return true;
58067                 // Type number or any numeric literal type is assignable to any numeric enum type or any
58068                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
58069                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
58070                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
58071                     return true;
58072             }
58073             return false;
58074         }
58075         function isTypeRelatedTo(source, target, relation) {
58076             if (isFreshLiteralType(source)) {
58077                 source = source.regularType;
58078             }
58079             if (isFreshLiteralType(target)) {
58080                 target = target.regularType;
58081             }
58082             if (source === target) {
58083                 return true;
58084             }
58085             if (relation !== identityRelation) {
58086                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
58087                     return true;
58088                 }
58089             }
58090             else {
58091                 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
58092                     source.flags !== target.flags && !(source.flags & 469237760 /* Substructure */))
58093                     return false;
58094             }
58095             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
58096                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
58097                 if (related !== undefined) {
58098                     return !!(related & 1 /* Succeeded */);
58099                 }
58100             }
58101             if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) {
58102                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
58103             }
58104             return false;
58105         }
58106         function isIgnoredJsxProperty(source, sourceProp) {
58107             return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
58108         }
58109         function getNormalizedType(type, writing) {
58110             while (true) {
58111                 var t = isFreshLiteralType(type) ? type.regularType :
58112                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
58113                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
58114                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
58115                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
58116                                     type;
58117                 if (t === type)
58118                     break;
58119                 type = t;
58120             }
58121             return type;
58122         }
58123         /**
58124          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
58125          * @param source The left-hand-side of the relation.
58126          * @param target The right-hand-side of the relation.
58127          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
58128          * Used as both to determine which checks are performed and as a cache of previously computed results.
58129          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
58130          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
58131          * @param containingMessageChain A chain of errors to prepend any new errors found.
58132          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
58133          */
58134         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
58135             var errorInfo;
58136             var relatedInfo;
58137             var maybeKeys;
58138             var sourceStack;
58139             var targetStack;
58140             var maybeCount = 0;
58141             var depth = 0;
58142             var expandingFlags = 0 /* None */;
58143             var overflow = false;
58144             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
58145             var lastSkippedInfo;
58146             var incompatibleStack = [];
58147             var inPropertyCheck = false;
58148             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
58149             var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
58150             if (incompatibleStack.length) {
58151                 reportIncompatibleStack();
58152             }
58153             if (overflow) {
58154                 ts.tracing.instant("check" /* Check */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth });
58155                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
58156                 if (errorOutputContainer) {
58157                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
58158                 }
58159             }
58160             else if (errorInfo) {
58161                 if (containingMessageChain) {
58162                     var chain = containingMessageChain();
58163                     if (chain) {
58164                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
58165                         errorInfo = chain;
58166                     }
58167                 }
58168                 var relatedInformation = void 0;
58169                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
58170                 if (headMessage && errorNode && !result && source.symbol) {
58171                     var links = getSymbolLinks(source.symbol);
58172                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
58173                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
58174                         if (helpfulRetry) {
58175                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
58176                             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);
58177                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
58178                         }
58179                     }
58180                 }
58181                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
58182                 if (relatedInfo) {
58183                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
58184                 }
58185                 if (errorOutputContainer) {
58186                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
58187                 }
58188                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
58189                     diagnostics.add(diag);
58190                 }
58191             }
58192             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
58193                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
58194             }
58195             return result !== 0 /* False */;
58196             function resetErrorInfo(saved) {
58197                 errorInfo = saved.errorInfo;
58198                 lastSkippedInfo = saved.lastSkippedInfo;
58199                 incompatibleStack = saved.incompatibleStack;
58200                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
58201                 relatedInfo = saved.relatedInfo;
58202             }
58203             function captureErrorCalculationState() {
58204                 return {
58205                     errorInfo: errorInfo,
58206                     lastSkippedInfo: lastSkippedInfo,
58207                     incompatibleStack: incompatibleStack.slice(),
58208                     overrideNextErrorInfo: overrideNextErrorInfo,
58209                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
58210                 };
58211             }
58212             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
58213                 overrideNextErrorInfo++; // Suppress the next relation error
58214                 lastSkippedInfo = undefined; // Reset skipped info cache
58215                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
58216             }
58217             function reportIncompatibleStack() {
58218                 var stack = incompatibleStack;
58219                 incompatibleStack = [];
58220                 var info = lastSkippedInfo;
58221                 lastSkippedInfo = undefined;
58222                 if (stack.length === 1) {
58223                     reportError.apply(void 0, stack[0]);
58224                     if (info) {
58225                         // Actually do the last relation error
58226                         reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
58227                     }
58228                     return;
58229                 }
58230                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
58231                 // we can build from left to right
58232                 var path = "";
58233                 var secondaryRootErrors = [];
58234                 while (stack.length) {
58235                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
58236                     switch (msg.code) {
58237                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
58238                             // Parenthesize a `new` if there is one
58239                             if (path.indexOf("new ") === 0) {
58240                                 path = "(" + path + ")";
58241                             }
58242                             var str = "" + args[0];
58243                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
58244                             if (path.length === 0) {
58245                                 path = "" + str;
58246                             }
58247                             // Otherwise write a dotted name if possible
58248                             else if (ts.isIdentifierText(str, compilerOptions.target)) {
58249                                 path = path + "." + str;
58250                             }
58251                             // Failing that, check if the name is already a computed name
58252                             else if (str[0] === "[" && str[str.length - 1] === "]") {
58253                                 path = "" + path + str;
58254                             }
58255                             // And finally write out a computed name as a last resort
58256                             else {
58257                                 path = path + "[" + str + "]";
58258                             }
58259                             break;
58260                         }
58261                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
58262                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
58263                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
58264                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
58265                             if (path.length === 0) {
58266                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
58267                                 // to unify (the with no arguments bit is excessive for printback) and print them back
58268                                 var mappedMsg = msg;
58269                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
58270                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
58271                                 }
58272                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
58273                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
58274                                 }
58275                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
58276                             }
58277                             else {
58278                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
58279                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
58280                                     ? "new "
58281                                     : "";
58282                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
58283                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
58284                                     ? ""
58285                                     : "...";
58286                                 path = "" + prefix + path + "(" + params + ")";
58287                             }
58288                             break;
58289                         }
58290                         default:
58291                             return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
58292                     }
58293                 }
58294                 if (path) {
58295                     reportError(path[path.length - 1] === ")"
58296                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
58297                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
58298                 }
58299                 else {
58300                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
58301                     secondaryRootErrors.shift();
58302                 }
58303                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
58304                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
58305                     var originalValue = msg.elidedInCompatabilityPyramid;
58306                     msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
58307                     reportError.apply(void 0, __spreadArrays([msg], args));
58308                     msg.elidedInCompatabilityPyramid = originalValue;
58309                 }
58310                 if (info) {
58311                     // Actually do the last relation error
58312                     reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
58313                 }
58314             }
58315             function reportError(message, arg0, arg1, arg2, arg3) {
58316                 ts.Debug.assert(!!errorNode);
58317                 if (incompatibleStack.length)
58318                     reportIncompatibleStack();
58319                 if (message.elidedInCompatabilityPyramid)
58320                     return;
58321                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
58322             }
58323             function associateRelatedInfo(info) {
58324                 ts.Debug.assert(!!errorInfo);
58325                 if (!relatedInfo) {
58326                     relatedInfo = [info];
58327                 }
58328                 else {
58329                     relatedInfo.push(info);
58330                 }
58331             }
58332             function reportRelationError(message, source, target) {
58333                 if (incompatibleStack.length)
58334                     reportIncompatibleStack();
58335                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
58336                 var generalizedSource = source;
58337                 var generalizedSourceType = sourceType;
58338                 if (isLiteralType(source) && !typeCouldHaveTopLevelSingletonTypes(target)) {
58339                     generalizedSource = getBaseTypeOfLiteralType(source);
58340                     ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable");
58341                     generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource);
58342                 }
58343                 if (target.flags & 262144 /* TypeParameter */) {
58344                     var constraint = getBaseConstraintOfType(target);
58345                     var needsOriginalSource = void 0;
58346                     if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) {
58347                         reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, needsOriginalSource ? sourceType : generalizedSourceType, targetType, typeToString(constraint));
58348                     }
58349                     else {
58350                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType);
58351                     }
58352                 }
58353                 if (!message) {
58354                     if (relation === comparableRelation) {
58355                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
58356                     }
58357                     else if (sourceType === targetType) {
58358                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
58359                     }
58360                     else {
58361                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
58362                     }
58363                 }
58364                 reportError(message, generalizedSourceType, targetType);
58365             }
58366             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
58367                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
58368                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
58369                 if ((globalStringType === source && stringType === target) ||
58370                     (globalNumberType === source && numberType === target) ||
58371                     (globalBooleanType === source && booleanType === target) ||
58372                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
58373                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
58374                 }
58375             }
58376             /**
58377              * Try and elaborate array and tuple errors. Returns false
58378              * if we have found an elaboration, or we should ignore
58379              * any other elaborations when relating the `source` and
58380              * `target` types.
58381              */
58382             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
58383                 /**
58384                  * The spec for elaboration is:
58385                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
58386                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
58387                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
58388                  * - If the source an array then skip property elaborations if the target is a tuple.
58389                  */
58390                 if (isTupleType(source)) {
58391                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
58392                         if (reportErrors) {
58393                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
58394                         }
58395                         return false;
58396                     }
58397                     return isTupleType(target) || isArrayType(target);
58398                 }
58399                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
58400                     if (reportErrors) {
58401                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
58402                     }
58403                     return false;
58404                 }
58405                 if (isTupleType(target)) {
58406                     return isArrayType(source);
58407                 }
58408                 return true;
58409             }
58410             /**
58411              * Compare two types and return
58412              * * Ternary.True if they are related with no assumptions,
58413              * * Ternary.Maybe if they are related with assumptions of other relationships, or
58414              * * Ternary.False if they are not related.
58415              */
58416             function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
58417                 if (reportErrors === void 0) { reportErrors = false; }
58418                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
58419                 // Before normalization: if `source` is type an object type, and `target` is primitive,
58420                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
58421                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
58422                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
58423                         return -1 /* True */;
58424                     }
58425                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
58426                     return 0 /* False */;
58427                 }
58428                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
58429                 // turn deferred type references into regular type references, simplify indexed access and
58430                 // conditional types, and resolve substitution types to either the substitution (on the source
58431                 // side) or the type variable (on the target side).
58432                 var source = getNormalizedType(originalSource, /*writing*/ false);
58433                 var target = getNormalizedType(originalTarget, /*writing*/ true);
58434                 if (source === target)
58435                     return -1 /* True */;
58436                 if (relation === identityRelation) {
58437                     return isIdenticalTo(source, target);
58438                 }
58439                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
58440                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
58441                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
58442                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
58443                 // the target is exactly the constraint.
58444                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
58445                     return -1 /* True */;
58446                 }
58447                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
58448                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
58449                 // First, see if we're even relating an object type to a union.
58450                 // Then see if the target is stripped down to a single non-union type.
58451                 // Note
58452                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
58453                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
58454                 //    when dealing with generics.
58455                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
58456                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
58457                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
58458                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
58459                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
58460                         if (source === nullStrippedTarget)
58461                             return -1 /* True */;
58462                         target = nullStrippedTarget;
58463                     }
58464                 }
58465                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
58466                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
58467                     return -1 /* True */;
58468                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
58469                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
58470                 if (isPerformingExcessPropertyChecks) {
58471                     if (hasExcessProperties(source, target, reportErrors)) {
58472                         if (reportErrors) {
58473                             reportRelationError(headMessage, source, target);
58474                         }
58475                         return 0 /* False */;
58476                     }
58477                 }
58478                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
58479                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
58480                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
58481                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
58482                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
58483                     if (reportErrors) {
58484                         var calls = getSignaturesOfType(source, 0 /* Call */);
58485                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
58486                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
58487                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
58488                             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));
58489                         }
58490                         else {
58491                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
58492                         }
58493                     }
58494                     return 0 /* False */;
58495                 }
58496                 var result = 0 /* False */;
58497                 var saveErrorInfo = captureErrorCalculationState();
58498                 // Note that these checks are specifically ordered to produce correct results. In particular,
58499                 // we need to deconstruct unions before intersections (because unions are always at the top),
58500                 // and we need to handle "each" relations before "some" relations for the same kind of type.
58501                 if (source.flags & 1048576 /* Union */) {
58502                     result = relation === comparableRelation ?
58503                         someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
58504                         eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
58505                 }
58506                 else {
58507                     if (target.flags & 1048576 /* Union */) {
58508                         result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
58509                     }
58510                     else if (target.flags & 2097152 /* Intersection */) {
58511                         result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
58512                     }
58513                     else if (source.flags & 2097152 /* Intersection */) {
58514                         // Check to see if any constituents of the intersection are immediately related to the target.
58515                         //
58516                         // Don't report errors though. Checking whether a constituent is related to the source is not actually
58517                         // useful and leads to some confusing error messages. Instead it is better to let the below checks
58518                         // take care of this, or to not elaborate at all. For instance,
58519                         //
58520                         //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
58521                         //
58522                         //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
58523                         //          than to report that 'D' is not assignable to 'A' or 'B'.
58524                         //
58525                         //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
58526                         //          breaking the intersection apart.
58527                         result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
58528                     }
58529                     if (!result && (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */)) {
58530                         if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
58531                             resetErrorInfo(saveErrorInfo);
58532                         }
58533                     }
58534                 }
58535                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
58536                     // The combined constraint of an intersection type is the intersection of the constraints of
58537                     // the constituents. When an intersection type contains instantiable types with union type
58538                     // constraints, there are situations where we need to examine the combined constraint. One is
58539                     // when the target is a union type. Another is when the intersection contains types belonging
58540                     // to one of the disjoint domains. For example, given type variables T and U, each with the
58541                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
58542                     // we need to check this constraint against a union on the target side. Also, given a type
58543                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
58544                     // 'string & number | number & number' which reduces to just 'number'.
58545                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
58546                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
58547                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
58548                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
58549                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
58550                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
58551                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
58552                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
58553                             if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
58554                                 resetErrorInfo(saveErrorInfo);
58555                             }
58556                         }
58557                     }
58558                 }
58559                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
58560                 // an extra property check where the intersection is viewed as a single object. The following are motivating
58561                 // examples that all should be errors, but aren't without this extra property check:
58562                 //
58563                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
58564                 //
58565                 //   declare let wrong: { a: { y: string } };
58566                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
58567                 //
58568                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
58569                 //     x = y;  // Mismatched property in source intersection
58570                 //   }
58571                 //
58572                 // We suppress recursive intersection property checks because they can generate lots of work when relating
58573                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
58574                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
58575                     isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) {
58576                     inPropertyCheck = true;
58577                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
58578                     inPropertyCheck = false;
58579                 }
58580                 reportErrorResults(source, target, result, isComparingJsxAttributes);
58581                 return result;
58582                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
58583                     if (!result && reportErrors) {
58584                         source = originalSource.aliasSymbol ? originalSource : source;
58585                         target = originalTarget.aliasSymbol ? originalTarget : target;
58586                         var maybeSuppress = overrideNextErrorInfo > 0;
58587                         if (maybeSuppress) {
58588                             overrideNextErrorInfo--;
58589                         }
58590                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
58591                             var currentError = errorInfo;
58592                             tryElaborateArrayLikeErrors(source, target, reportErrors);
58593                             if (errorInfo !== currentError) {
58594                                 maybeSuppress = !!errorInfo;
58595                             }
58596                         }
58597                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
58598                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
58599                         }
58600                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
58601                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
58602                         }
58603                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
58604                             var targetTypes = target.types;
58605                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
58606                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
58607                             if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
58608                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
58609                                 // do not report top error
58610                                 return result;
58611                             }
58612                         }
58613                         else {
58614                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
58615                         }
58616                         if (!headMessage && maybeSuppress) {
58617                             lastSkippedInfo = [source, target];
58618                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
58619                             return result;
58620                         }
58621                         reportRelationError(headMessage, source, target);
58622                     }
58623                 }
58624             }
58625             function isIdenticalTo(source, target) {
58626                 var flags = source.flags & target.flags;
58627                 if (!(flags & 469237760 /* Substructure */)) {
58628                     return 0 /* False */;
58629                 }
58630                 if (flags & 3145728 /* UnionOrIntersection */) {
58631                     var result_6 = eachTypeRelatedToSomeType(source, target);
58632                     if (result_6) {
58633                         result_6 &= eachTypeRelatedToSomeType(target, source);
58634                     }
58635                     return result_6;
58636                 }
58637                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
58638             }
58639             function getTypeOfPropertyInTypes(types, name) {
58640                 var appendPropType = function (propTypes, type) {
58641                     type = getApparentType(type);
58642                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
58643                     var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
58644                     return ts.append(propTypes, propType);
58645                 };
58646                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
58647             }
58648             function hasExcessProperties(source, target, reportErrors) {
58649                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
58650                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
58651                 }
58652                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
58653                 if ((relation === assignableRelation || relation === comparableRelation) &&
58654                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
58655                     return false;
58656                 }
58657                 var reducedTarget = target;
58658                 var checkTypes;
58659                 if (target.flags & 1048576 /* Union */) {
58660                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
58661                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
58662                 }
58663                 var _loop_16 = function (prop) {
58664                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
58665                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
58666                             if (reportErrors) {
58667                                 // Report error in terms of object types in the target as those are the only ones
58668                                 // we check in isKnownProperty.
58669                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
58670                                 // We know *exactly* where things went wrong when comparing the types.
58671                                 // Use this property as the error node as this will be more helpful in
58672                                 // reasoning about what went wrong.
58673                                 if (!errorNode)
58674                                     return { value: ts.Debug.fail() };
58675                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
58676                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
58677                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
58678                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
58679                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
58680                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
58681                                         errorNode = prop.valueDeclaration.name;
58682                                     }
58683                                     var propName = symbolToString(prop);
58684                                     var suggestionSymbol = getSuggestedSymbolForNonexistentJSXAttribute(propName, errorTarget);
58685                                     var suggestion = suggestionSymbol ? symbolToString(suggestionSymbol) : undefined;
58686                                     if (suggestion) {
58687                                         reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(errorTarget), suggestion);
58688                                     }
58689                                     else {
58690                                         reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, propName, typeToString(errorTarget));
58691                                     }
58692                                 }
58693                                 else {
58694                                     // use the property's value declaration if the property is assigned inside the literal itself
58695                                     var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
58696                                     var suggestion = void 0;
58697                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
58698                                         var propDeclaration = prop.valueDeclaration;
58699                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
58700                                         errorNode = propDeclaration;
58701                                         var name = propDeclaration.name;
58702                                         if (ts.isIdentifier(name)) {
58703                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
58704                                         }
58705                                     }
58706                                     if (suggestion !== undefined) {
58707                                         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(errorTarget), suggestion);
58708                                     }
58709                                     else {
58710                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
58711                                     }
58712                                 }
58713                             }
58714                             return { value: true };
58715                         }
58716                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
58717                             if (reportErrors) {
58718                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
58719                             }
58720                             return { value: true };
58721                         }
58722                     }
58723                 };
58724                 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
58725                     var prop = _a[_i];
58726                     var state_5 = _loop_16(prop);
58727                     if (typeof state_5 === "object")
58728                         return state_5.value;
58729                 }
58730                 return false;
58731             }
58732             function shouldCheckAsExcessProperty(prop, container) {
58733                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
58734             }
58735             function eachTypeRelatedToSomeType(source, target) {
58736                 var result = -1 /* True */;
58737                 var sourceTypes = source.types;
58738                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
58739                     var sourceType = sourceTypes_1[_i];
58740                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
58741                     if (!related) {
58742                         return 0 /* False */;
58743                     }
58744                     result &= related;
58745                 }
58746                 return result;
58747             }
58748             function typeRelatedToSomeType(source, target, reportErrors) {
58749                 var targetTypes = target.types;
58750                 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
58751                     return -1 /* True */;
58752                 }
58753                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
58754                     var type = targetTypes_1[_i];
58755                     var related = isRelatedTo(source, type, /*reportErrors*/ false);
58756                     if (related) {
58757                         return related;
58758                     }
58759                 }
58760                 if (reportErrors) {
58761                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
58762                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
58763                 }
58764                 return 0 /* False */;
58765             }
58766             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
58767                 var result = -1 /* True */;
58768                 var targetTypes = target.types;
58769                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
58770                     var targetType = targetTypes_2[_i];
58771                     var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
58772                     if (!related) {
58773                         return 0 /* False */;
58774                     }
58775                     result &= related;
58776                 }
58777                 return result;
58778             }
58779             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
58780                 var sourceTypes = source.types;
58781                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
58782                     return -1 /* True */;
58783                 }
58784                 var len = sourceTypes.length;
58785                 for (var i = 0; i < len; i++) {
58786                     var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
58787                     if (related) {
58788                         return related;
58789                     }
58790                 }
58791                 return 0 /* False */;
58792             }
58793             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
58794                 var result = -1 /* True */;
58795                 var sourceTypes = source.types;
58796                 for (var i = 0; i < sourceTypes.length; i++) {
58797                     var sourceType = sourceTypes[i];
58798                     if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
58799                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
58800                         var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
58801                         if (related_1) {
58802                             result &= related_1;
58803                             continue;
58804                         }
58805                     }
58806                     var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
58807                     if (!related) {
58808                         return 0 /* False */;
58809                     }
58810                     result &= related;
58811                 }
58812                 return result;
58813             }
58814             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
58815                 if (sources === void 0) { sources = ts.emptyArray; }
58816                 if (targets === void 0) { targets = ts.emptyArray; }
58817                 if (variances === void 0) { variances = ts.emptyArray; }
58818                 if (sources.length !== targets.length && relation === identityRelation) {
58819                     return 0 /* False */;
58820                 }
58821                 var length = sources.length <= targets.length ? sources.length : targets.length;
58822                 var result = -1 /* True */;
58823                 for (var i = 0; i < length; i++) {
58824                     // When variance information isn't available we default to covariance. This happens
58825                     // in the process of computing variance information for recursive types and when
58826                     // comparing 'this' type arguments.
58827                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
58828                     var variance = varianceFlags & 7 /* VarianceMask */;
58829                     // We ignore arguments for independent type parameters (because they're never witnessed).
58830                     if (variance !== 4 /* Independent */) {
58831                         var s = sources[i];
58832                         var t = targets[i];
58833                         var related = -1 /* True */;
58834                         if (varianceFlags & 8 /* Unmeasurable */) {
58835                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
58836                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
58837                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
58838                             related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
58839                         }
58840                         else if (variance === 1 /* Covariant */) {
58841                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
58842                         }
58843                         else if (variance === 2 /* Contravariant */) {
58844                             related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
58845                         }
58846                         else if (variance === 3 /* Bivariant */) {
58847                             // In the bivariant case we first compare contravariantly without reporting
58848                             // errors. Then, if that doesn't succeed, we compare covariantly with error
58849                             // reporting. Thus, error elaboration will be based on the the covariant check,
58850                             // which is generally easier to reason about.
58851                             related = isRelatedTo(t, s, /*reportErrors*/ false);
58852                             if (!related) {
58853                                 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
58854                             }
58855                         }
58856                         else {
58857                             // In the invariant case we first compare covariantly, and only when that
58858                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
58859                             // will typically be based on the covariant check.
58860                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
58861                             if (related) {
58862                                 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
58863                             }
58864                         }
58865                         if (!related) {
58866                             return 0 /* False */;
58867                         }
58868                         result &= related;
58869                     }
58870                 }
58871                 return result;
58872             }
58873             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
58874             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
58875             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
58876             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
58877             // and issue an error. Otherwise, actually compare the structure of the two types.
58878             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
58879                 if (overflow) {
58880                     return 0 /* False */;
58881                 }
58882                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
58883                 var entry = relation.get(id);
58884                 if (entry !== undefined) {
58885                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
58886                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
58887                         // as a failure, and should be updated as a reported failure by the bottom of this function.
58888                     }
58889                     else {
58890                         if (outofbandVarianceMarkerHandler) {
58891                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
58892                             var saved = entry & 24 /* ReportsMask */;
58893                             if (saved & 8 /* ReportsUnmeasurable */) {
58894                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
58895                             }
58896                             if (saved & 16 /* ReportsUnreliable */) {
58897                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
58898                             }
58899                         }
58900                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
58901                     }
58902                 }
58903                 if (!maybeKeys) {
58904                     maybeKeys = [];
58905                     sourceStack = [];
58906                     targetStack = [];
58907                 }
58908                 else {
58909                     for (var i = 0; i < maybeCount; i++) {
58910                         // If source and target are already being compared, consider them related with assumptions
58911                         if (id === maybeKeys[i]) {
58912                             return 3 /* Maybe */;
58913                         }
58914                     }
58915                     if (depth === 100) {
58916                         overflow = true;
58917                         return 0 /* False */;
58918                     }
58919                 }
58920                 var maybeStart = maybeCount;
58921                 maybeKeys[maybeCount] = id;
58922                 maybeCount++;
58923                 sourceStack[depth] = source;
58924                 targetStack[depth] = target;
58925                 depth++;
58926                 var saveExpandingFlags = expandingFlags;
58927                 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
58928                     expandingFlags |= 1 /* Source */;
58929                 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
58930                     expandingFlags |= 2 /* Target */;
58931                 var originalHandler;
58932                 var propagatingVarianceFlags = 0;
58933                 if (outofbandVarianceMarkerHandler) {
58934                     originalHandler = outofbandVarianceMarkerHandler;
58935                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
58936                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
58937                         return originalHandler(onlyUnreliable);
58938                     };
58939                 }
58940                 if (expandingFlags === 3 /* Both */) {
58941                     ts.tracing.instant("check" /* Check */, "recursiveTypeRelatedTo_DepthLimit", {
58942                         sourceId: source.id,
58943                         sourceIdStack: sourceStack.map(function (t) { return t.id; }),
58944                         targetId: target.id,
58945                         targetIdStack: targetStack.map(function (t) { return t.id; }),
58946                         depth: depth,
58947                     });
58948                 }
58949                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 3 /* Maybe */;
58950                 if (outofbandVarianceMarkerHandler) {
58951                     outofbandVarianceMarkerHandler = originalHandler;
58952                 }
58953                 expandingFlags = saveExpandingFlags;
58954                 depth--;
58955                 if (result) {
58956                     if (result === -1 /* True */ || depth === 0) {
58957                         if (result === -1 /* True */ || result === 3 /* Maybe */) {
58958                             // If result is definitely true, record all maybe keys as having succeeded. Also, record Ternary.Maybe
58959                             // results as having succeeded once we reach depth 0, but never record Ternary.Unknown results.
58960                             for (var i = maybeStart; i < maybeCount; i++) {
58961                                 relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
58962                             }
58963                         }
58964                         maybeCount = maybeStart;
58965                     }
58966                 }
58967                 else {
58968                     // A false result goes straight into global cache (when something is false under
58969                     // assumptions it will also be false without assumptions)
58970                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
58971                     maybeCount = maybeStart;
58972                 }
58973                 return result;
58974             }
58975             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
58976                 ts.tracing.push("check" /* Check */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id });
58977                 var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState);
58978                 ts.tracing.pop();
58979                 return result;
58980             }
58981             function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) {
58982                 if (intersectionState & 4 /* PropertyCheck */) {
58983                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
58984                 }
58985                 var flags = source.flags & target.flags;
58986                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
58987                     if (flags & 4194304 /* Index */) {
58988                         return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
58989                     }
58990                     var result_7 = 0 /* False */;
58991                     if (flags & 8388608 /* IndexedAccess */) {
58992                         if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
58993                             if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
58994                                 return result_7;
58995                             }
58996                         }
58997                     }
58998                     if (flags & 16777216 /* Conditional */) {
58999                         if (source.root.isDistributive === target.root.isDistributive) {
59000                             if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
59001                                 if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
59002                                     if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
59003                                         if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
59004                                             return result_7;
59005                                         }
59006                                     }
59007                                 }
59008                             }
59009                         }
59010                     }
59011                     if (flags & 33554432 /* Substitution */) {
59012                         return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
59013                     }
59014                     return 0 /* False */;
59015                 }
59016                 var result;
59017                 var originalErrorInfo;
59018                 var varianceCheckFailed = false;
59019                 var saveErrorInfo = captureErrorCalculationState();
59020                 // We limit alias variance probing to only object and conditional types since their alias behavior
59021                 // is more predictable than other, interned types, which may or may not have an alias depending on
59022                 // the order in which things were checked.
59023                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
59024                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
59025                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
59026                     var variances = getAliasVariances(source.aliasSymbol);
59027                     if (variances === ts.emptyArray) {
59028                         return 1 /* Unknown */;
59029                     }
59030                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
59031                     if (varianceResult !== undefined) {
59032                         return varianceResult;
59033                     }
59034                 }
59035                 // For a generic type T and a type U that is assignable to T, [...U] is assignable to T, U is assignable to readonly [...T],
59036                 // and U is assignable to [...T] when U is constrained to a mutable array or tuple type.
59037                 if (isSingleElementGenericTupleType(source) && !source.target.readonly && (result = isRelatedTo(getTypeArguments(source)[0], target)) ||
59038                     isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0]))) {
59039                     return result;
59040                 }
59041                 if (target.flags & 262144 /* TypeParameter */) {
59042                     // 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].
59043                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && !source.declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
59044                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
59045                             var templateType = getTemplateTypeFromMappedType(source);
59046                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
59047                             if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
59048                                 return result;
59049                             }
59050                         }
59051                     }
59052                 }
59053                 else if (target.flags & 4194304 /* Index */) {
59054                     var targetType = target.type;
59055                     // A keyof S is related to a keyof T if T is related to S.
59056                     if (source.flags & 4194304 /* Index */) {
59057                         if (result = isRelatedTo(targetType, source.type, /*reportErrors*/ false)) {
59058                             return result;
59059                         }
59060                     }
59061                     if (isTupleType(targetType)) {
59062                         // An index type can have a tuple type target when the tuple type contains variadic elements.
59063                         // Check if the source is related to the known keys of the tuple type.
59064                         if (result = isRelatedTo(source, getKnownKeysOfTupleType(targetType), reportErrors)) {
59065                             return result;
59066                         }
59067                     }
59068                     else {
59069                         // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
59070                         // simplified form of T or, if T doesn't simplify, the constraint of T.
59071                         var constraint = getSimplifiedTypeOrConstraint(targetType);
59072                         if (constraint) {
59073                             // We require Ternary.True here such that circular constraints don't cause
59074                             // false positives. For example, given 'T extends { [K in keyof T]: string }',
59075                             // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
59076                             // related to other types.
59077                             if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
59078                                 return -1 /* True */;
59079                             }
59080                         }
59081                     }
59082                 }
59083                 else if (target.flags & 8388608 /* IndexedAccess */) {
59084                     // A type S is related to a type T[K] if S is related to C, where C is the base
59085                     // constraint of T[K] for writing.
59086                     if (relation === assignableRelation || relation === comparableRelation) {
59087                         var objectType = target.objectType;
59088                         var indexType = target.indexType;
59089                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
59090                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
59091                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
59092                             var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
59093                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags);
59094                             if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
59095                                 return result;
59096                             }
59097                         }
59098                     }
59099                 }
59100                 else if (isGenericMappedType(target) && !target.declaration.nameType) {
59101                     // A source type T is related to a target type { [P in X]: T[P] }
59102                     var template = getTemplateTypeFromMappedType(target);
59103                     var modifiers = getMappedTypeModifiers(target);
59104                     if (!(modifiers & 8 /* ExcludeOptional */)) {
59105                         if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
59106                             template.indexType === getTypeParameterFromMappedType(target)) {
59107                             return -1 /* True */;
59108                         }
59109                         if (!isGenericMappedType(source)) {
59110                             var targetConstraint = getConstraintTypeFromMappedType(target);
59111                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
59112                             var includeOptional = modifiers & 4 /* IncludeOptional */;
59113                             var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
59114                             // 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.
59115                             // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
59116                             if (includeOptional
59117                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
59118                                 : isRelatedTo(targetConstraint, sourceKeys)) {
59119                                 var templateType = getTemplateTypeFromMappedType(target);
59120                                 var typeParameter = getTypeParameterFromMappedType(target);
59121                                 // Fastpath: When the template has the form Obj[P] where P is the mapped type parameter, directly compare `source` with `Obj`
59122                                 // to avoid creating the (potentially very large) number of new intermediate types made by manufacturing `source[P]`
59123                                 var nonNullComponent = extractTypesOfKind(templateType, ~98304 /* Nullable */);
59124                                 if (nonNullComponent.flags & 8388608 /* IndexedAccess */ && nonNullComponent.indexType === typeParameter) {
59125                                     if (result = isRelatedTo(source, nonNullComponent.objectType, reportErrors)) {
59126                                         return result;
59127                                     }
59128                                 }
59129                                 else {
59130                                     var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
59131                                     var indexedAccessType = getIndexedAccessType(source, indexingType);
59132                                     if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
59133                                         return result;
59134                                     }
59135                                 }
59136                             }
59137                             originalErrorInfo = errorInfo;
59138                             resetErrorInfo(saveErrorInfo);
59139                         }
59140                     }
59141                 }
59142                 else if (target.flags & 134217728 /* TemplateLiteral */ && source.flags & 128 /* StringLiteral */) {
59143                     if (isPatternLiteralType(target)) {
59144                         // match all non-`string` segments
59145                         var result_8 = inferLiteralsFromTemplateLiteralType(source, target);
59146                         if (result_8 && ts.every(result_8, function (r, i) { return isStringLiteralTypeValueParsableAsType(r, target.types[i]); })) {
59147                             return -1 /* True */;
59148                         }
59149                     }
59150                 }
59151                 if (source.flags & 8650752 /* TypeVariable */) {
59152                     if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
59153                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
59154                         if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
59155                             result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
59156                         }
59157                         if (result) {
59158                             resetErrorInfo(saveErrorInfo);
59159                             return result;
59160                         }
59161                     }
59162                     else {
59163                         var constraint = getConstraintOfType(source);
59164                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
59165                             // A type variable with no constraint is not related to the non-primitive object type.
59166                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
59167                                 resetErrorInfo(saveErrorInfo);
59168                                 return result;
59169                             }
59170                         }
59171                         // 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
59172                         else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
59173                             resetErrorInfo(saveErrorInfo);
59174                             return result;
59175                         }
59176                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
59177                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
59178                             resetErrorInfo(saveErrorInfo);
59179                             return result;
59180                         }
59181                     }
59182                 }
59183                 else if (source.flags & 4194304 /* Index */) {
59184                     if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
59185                         resetErrorInfo(saveErrorInfo);
59186                         return result;
59187                     }
59188                 }
59189                 else if (source.flags & 134217728 /* TemplateLiteral */) {
59190                     if (target.flags & 134217728 /* TemplateLiteral */ &&
59191                         source.texts.length === target.texts.length &&
59192                         source.types.length === target.types.length &&
59193                         ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) &&
59194                         ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) {
59195                         return -1 /* True */;
59196                     }
59197                     var constraint = getBaseConstraintOfType(source);
59198                     if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) {
59199                         resetErrorInfo(saveErrorInfo);
59200                         return result;
59201                     }
59202                 }
59203                 else if (source.flags & 268435456 /* StringMapping */) {
59204                     if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) {
59205                         if (result = isRelatedTo(source.type, target.type, reportErrors)) {
59206                             resetErrorInfo(saveErrorInfo);
59207                             return result;
59208                         }
59209                     }
59210                     else {
59211                         var constraint = getBaseConstraintOfType(source);
59212                         if (constraint && (result = isRelatedTo(constraint, target, reportErrors))) {
59213                             resetErrorInfo(saveErrorInfo);
59214                             return result;
59215                         }
59216                     }
59217                 }
59218                 else if (source.flags & 16777216 /* Conditional */) {
59219                     if (target.flags & 16777216 /* Conditional */) {
59220                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
59221                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
59222                         // and Y1 is related to Y2.
59223                         var sourceParams = source.root.inferTypeParameters;
59224                         var sourceExtends = source.extendsType;
59225                         var mapper = void 0;
59226                         if (sourceParams) {
59227                             // If the source has infer type parameters, we instantiate them in the context of the target
59228                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
59229                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */);
59230                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
59231                             mapper = ctx.mapper;
59232                         }
59233                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
59234                             (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
59235                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
59236                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
59237                             }
59238                             if (result) {
59239                                 resetErrorInfo(saveErrorInfo);
59240                                 return result;
59241                             }
59242                         }
59243                     }
59244                     else {
59245                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
59246                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
59247                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
59248                         if (distributiveConstraint) {
59249                             if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
59250                                 resetErrorInfo(saveErrorInfo);
59251                                 return result;
59252                             }
59253                         }
59254                     }
59255                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
59256                     // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
59257                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
59258                     if (defaultConstraint) {
59259                         if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
59260                             resetErrorInfo(saveErrorInfo);
59261                             return result;
59262                         }
59263                     }
59264                 }
59265                 else {
59266                     // An empty object type is related to any mapped type that includes a '?' modifier.
59267                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
59268                         return -1 /* True */;
59269                     }
59270                     if (isGenericMappedType(target)) {
59271                         if (isGenericMappedType(source)) {
59272                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
59273                                 resetErrorInfo(saveErrorInfo);
59274                                 return result;
59275                             }
59276                         }
59277                         return 0 /* False */;
59278                     }
59279                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
59280                     if (relation !== identityRelation) {
59281                         source = getApparentType(source);
59282                     }
59283                     else if (isGenericMappedType(source)) {
59284                         return 0 /* False */;
59285                     }
59286                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
59287                         !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
59288                         // We have type references to the same generic type, and the type references are not marker
59289                         // type references (which are intended by be compared structurally). Obtain the variance
59290                         // information for the type parameters and relate the type arguments accordingly.
59291                         var variances = getVariances(source.target);
59292                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
59293                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
59294                         // recursive instantiations of the generic type.
59295                         if (variances === ts.emptyArray) {
59296                             return 1 /* Unknown */;
59297                         }
59298                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
59299                         if (varianceResult !== undefined) {
59300                             return varianceResult;
59301                         }
59302                     }
59303                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
59304                         if (relation !== identityRelation) {
59305                             return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
59306                         }
59307                         else {
59308                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
59309                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
59310                             return 0 /* False */;
59311                         }
59312                     }
59313                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
59314                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
59315                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
59316                         return 0 /* False */;
59317                     }
59318                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
59319                     // it may hold in a structural comparison.
59320                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
59321                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
59322                     // relates to X. Thus, we include intersection types on the source side here.
59323                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
59324                         // Report structural errors only if we haven't reported any errors yet
59325                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
59326                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
59327                         if (result) {
59328                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
59329                             if (result) {
59330                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
59331                                 if (result) {
59332                                     result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
59333                                     if (result) {
59334                                         result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
59335                                     }
59336                                 }
59337                             }
59338                         }
59339                         if (varianceCheckFailed && result) {
59340                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
59341                         }
59342                         else if (result) {
59343                             return result;
59344                         }
59345                     }
59346                     // If S is an object type and T is a discriminated union, S may be related to T if
59347                     // there exists a constituent of T for every combination of the discriminants of S
59348                     // with respect to T. We do not report errors here, as we will use the existing
59349                     // error result from checking each constituent of the union.
59350                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
59351                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
59352                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
59353                             var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
59354                             if (result_9) {
59355                                 return result_9;
59356                             }
59357                         }
59358                     }
59359                 }
59360                 return 0 /* False */;
59361                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
59362                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
59363                         return result;
59364                     }
59365                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
59366                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
59367                         // have to allow a structural fallback check
59368                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
59369                         // be assuming identity of the type parameter.
59370                         originalErrorInfo = undefined;
59371                         resetErrorInfo(saveErrorInfo);
59372                         return undefined;
59373                     }
59374                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
59375                     varianceCheckFailed = !allowStructuralFallback;
59376                     // The type arguments did not relate appropriately, but it may be because we have no variance
59377                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
59378                     // arguments). It might also be the case that the target type has a 'void' type argument for
59379                     // a covariant type parameter that is only used in return positions within the generic type
59380                     // (in which case any type argument is permitted on the source side). In those cases we proceed
59381                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
59382                     // related and we can return here.
59383                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
59384                         // In some cases generic types that are covariant in regular type checking mode become
59385                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
59386                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
59387                         // types are invariant, if any of the type parameters are invariant we reset the reported
59388                         // errors and instead force a structural comparison (which will include elaborations that
59389                         // reveal the reason).
59390                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
59391                         // we can return `False` early here to skip calculating the structural error message we don't need.
59392                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
59393                             return 0 /* False */;
59394                         }
59395                         // We remember the original error information so we can restore it in case the structural
59396                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
59397                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
59398                         originalErrorInfo = errorInfo;
59399                         resetErrorInfo(saveErrorInfo);
59400                     }
59401                 }
59402             }
59403             function reportUnmeasurableMarkers(p) {
59404                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
59405                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
59406                 }
59407                 return p;
59408             }
59409             function reportUnreliableMarkers(p) {
59410                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
59411                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
59412                 }
59413                 return p;
59414             }
59415             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
59416             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
59417             // that S and T are contra-variant whereas X and Y are co-variant.
59418             function mappedTypeRelatedTo(source, target, reportErrors) {
59419                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
59420                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
59421                 if (modifiersRelated) {
59422                     var result_10;
59423                     var targetConstraint = getConstraintTypeFromMappedType(target);
59424                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
59425                     if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
59426                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
59427                         if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) {
59428                             return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
59429                         }
59430                     }
59431                 }
59432                 return 0 /* False */;
59433             }
59434             function typeRelatedToDiscriminatedType(source, target) {
59435                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
59436                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
59437                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
59438                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
59439                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
59440                 //    'target' are related to a property in 'source'.
59441                 //
59442                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
59443                 //       for examples.
59444                 var sourceProperties = getPropertiesOfType(source);
59445                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
59446                 if (!sourcePropertiesFiltered)
59447                     return 0 /* False */;
59448                 // Though we could compute the number of combinations as we generate
59449                 // the matrix, this would incur additional memory overhead due to
59450                 // array allocations. To reduce this overhead, we first compute
59451                 // the number of combinations to ensure we will not surpass our
59452                 // fixed limit before incurring the cost of any allocations:
59453                 var numCombinations = 1;
59454                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
59455                     var sourceProperty = sourcePropertiesFiltered_1[_i];
59456                     numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
59457                     if (numCombinations > 25) {
59458                         // We've reached the complexity limit.
59459                         ts.tracing.instant("check" /* Check */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations });
59460                         return 0 /* False */;
59461                     }
59462                 }
59463                 // Compute the set of types for each discriminant property.
59464                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
59465                 var excludedProperties = new ts.Set();
59466                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
59467                     var sourceProperty = sourcePropertiesFiltered[i];
59468                     var sourcePropertyType = getTypeOfSymbol(sourceProperty);
59469                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
59470                         ? sourcePropertyType.types
59471                         : [sourcePropertyType];
59472                     excludedProperties.add(sourceProperty.escapedName);
59473                 }
59474                 // Match each combination of the cartesian product of discriminant properties to one or more
59475                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
59476                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
59477                 var matchingTypes = [];
59478                 var _loop_17 = function (combination) {
59479                     var hasMatch = false;
59480                     outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
59481                         var type = _a[_i];
59482                         var _loop_18 = function (i) {
59483                             var sourceProperty = sourcePropertiesFiltered[i];
59484                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
59485                             if (!targetProperty)
59486                                 return "continue-outer";
59487                             if (sourceProperty === targetProperty)
59488                                 return "continue";
59489                             // We compare the source property to the target in the context of a single discriminant type.
59490                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
59491                             // If the target property could not be found, or if the properties were not related,
59492                             // then this constituent is not a match.
59493                             if (!related) {
59494                                 return "continue-outer";
59495                             }
59496                         };
59497                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
59498                             var state_7 = _loop_18(i);
59499                             switch (state_7) {
59500                                 case "continue-outer": continue outer;
59501                             }
59502                         }
59503                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
59504                         hasMatch = true;
59505                     }
59506                     if (!hasMatch) {
59507                         return { value: 0 /* False */ };
59508                     }
59509                 };
59510                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
59511                     var combination = discriminantCombinations_1[_a];
59512                     var state_6 = _loop_17(combination);
59513                     if (typeof state_6 === "object")
59514                         return state_6.value;
59515                 }
59516                 // Compare the remaining non-discriminant properties of each match.
59517                 var result = -1 /* True */;
59518                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
59519                     var type = matchingTypes_1[_b];
59520                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
59521                     if (result) {
59522                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
59523                         if (result) {
59524                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
59525                             if (result) {
59526                                 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
59527                                 // Comparing numeric index types when both `source` and `type` are tuples is unnecessary as the
59528                                 // element types should be sufficiently covered by `propertiesRelatedTo`. It also causes problems
59529                                 // with index type assignability as the types for the excluded discriminants are still included
59530                                 // in the index type.
59531                                 if (result && !(isTupleType(source) && isTupleType(type))) {
59532                                     result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
59533                                 }
59534                             }
59535                         }
59536                     }
59537                     if (!result) {
59538                         return result;
59539                     }
59540                 }
59541                 return result;
59542             }
59543             function excludeProperties(properties, excludedProperties) {
59544                 if (!excludedProperties || properties.length === 0)
59545                     return properties;
59546                 var result;
59547                 for (var i = 0; i < properties.length; i++) {
59548                     if (!excludedProperties.has(properties[i].escapedName)) {
59549                         if (result) {
59550                             result.push(properties[i]);
59551                         }
59552                     }
59553                     else if (!result) {
59554                         result = properties.slice(0, i);
59555                     }
59556                 }
59557                 return result || properties;
59558             }
59559             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
59560                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
59561                 var source = getTypeOfSourceProperty(sourceProp);
59562                 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
59563                     // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
59564                     var links = getSymbolLinks(targetProp);
59565                     ts.Debug.assertIsDefined(links.deferralParent);
59566                     ts.Debug.assertIsDefined(links.deferralConstituents);
59567                     var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
59568                     var result_11 = unionParent ? 0 /* False */ : -1 /* True */;
59569                     var targetTypes = links.deferralConstituents;
59570                     for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
59571                         var targetType = targetTypes_3[_i];
59572                         var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
59573                         if (!unionParent) {
59574                             if (!related) {
59575                                 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
59576                                 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
59577                             }
59578                             result_11 &= related;
59579                         }
59580                         else {
59581                             if (related) {
59582                                 return related;
59583                             }
59584                         }
59585                     }
59586                     if (unionParent && !result_11 && targetIsOptional) {
59587                         result_11 = isRelatedTo(source, undefinedType);
59588                     }
59589                     if (unionParent && !result_11 && reportErrors) {
59590                         // The easiest way to get the right errors here is to un-defer (which may be costly)
59591                         // If it turns out this is too costly too often, we can replicate the error handling logic within
59592                         // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
59593                         // type on which to hand discriminable properties, which we are expressly trying to avoid here)
59594                         return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
59595                     }
59596                     return result_11;
59597                 }
59598                 else {
59599                     return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
59600                 }
59601             }
59602             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
59603                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
59604                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
59605                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
59606                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
59607                         if (reportErrors) {
59608                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
59609                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
59610                             }
59611                             else {
59612                                 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));
59613                             }
59614                         }
59615                         return 0 /* False */;
59616                     }
59617                 }
59618                 else if (targetPropFlags & 16 /* Protected */) {
59619                     if (!isValidOverrideOf(sourceProp, targetProp)) {
59620                         if (reportErrors) {
59621                             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));
59622                         }
59623                         return 0 /* False */;
59624                     }
59625                 }
59626                 else if (sourcePropFlags & 16 /* Protected */) {
59627                     if (reportErrors) {
59628                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
59629                     }
59630                     return 0 /* False */;
59631                 }
59632                 // If the target comes from a partial union prop, allow `undefined` in the target type
59633                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
59634                 if (!related) {
59635                     if (reportErrors) {
59636                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
59637                     }
59638                     return 0 /* False */;
59639                 }
59640                 // When checking for comparability, be more lenient with optional properties.
59641                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
59642                     // TypeScript 1.0 spec (April 2014): 3.8.3
59643                     // S is a subtype of a type T, and T is a supertype of S if ...
59644                     // S' and T are object types and, for each member M in T..
59645                     // M is a property and S' contains a property N where
59646                     // if M is a required property, N is also a required property
59647                     // (M - property in T)
59648                     // (N - property in S)
59649                     if (reportErrors) {
59650                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
59651                     }
59652                     return 0 /* False */;
59653                 }
59654                 return related;
59655             }
59656             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
59657                 var shouldSkipElaboration = false;
59658                 // give specific error in case where private names have the same description
59659                 if (unmatchedProperty.valueDeclaration
59660                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
59661                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
59662                     && source.symbol
59663                     && source.symbol.flags & 32 /* Class */) {
59664                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
59665                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
59666                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
59667                         var sourceName = ts.factory.getDeclarationName(source.symbol.valueDeclaration);
59668                         var targetName = ts.factory.getDeclarationName(target.symbol.valueDeclaration);
59669                         reportError(ts.Diagnostics.Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2, diagnosticName(privateIdentifierDescription), diagnosticName(sourceName.escapedText === "" ? anon : sourceName), diagnosticName(targetName.escapedText === "" ? anon : targetName));
59670                         return;
59671                     }
59672                 }
59673                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
59674                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
59675                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
59676                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
59677                 }
59678                 if (props.length === 1) {
59679                     var propName = symbolToString(unmatchedProperty);
59680                     reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
59681                     if (ts.length(unmatchedProperty.declarations)) {
59682                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
59683                     }
59684                     if (shouldSkipElaboration && errorInfo) {
59685                         overrideNextErrorInfo++;
59686                     }
59687                 }
59688                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
59689                     if (props.length > 5) { // arbitrary cutoff for too-long list form
59690                         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);
59691                     }
59692                     else {
59693                         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(", "));
59694                     }
59695                     if (shouldSkipElaboration && errorInfo) {
59696                         overrideNextErrorInfo++;
59697                     }
59698                 }
59699                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
59700             }
59701             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
59702                 if (relation === identityRelation) {
59703                     return propertiesIdenticalTo(source, target, excludedProperties);
59704                 }
59705                 var result = -1 /* True */;
59706                 if (isTupleType(target)) {
59707                     if (isArrayType(source) || isTupleType(source)) {
59708                         if (!target.target.readonly && (isReadonlyArrayType(source) || isTupleType(source) && source.target.readonly)) {
59709                             return 0 /* False */;
59710                         }
59711                         var sourceArity = getTypeReferenceArity(source);
59712                         var targetArity = getTypeReferenceArity(target);
59713                         var sourceRestFlag = isTupleType(source) ? source.target.combinedFlags & 4 /* Rest */ : 4 /* Rest */;
59714                         var targetRestFlag = target.target.combinedFlags & 4 /* Rest */;
59715                         var sourceMinLength = isTupleType(source) ? source.target.minLength : 0;
59716                         var targetMinLength = target.target.minLength;
59717                         if (!sourceRestFlag && sourceArity < targetMinLength) {
59718                             if (reportErrors) {
59719                                 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_requires_1, sourceArity, targetMinLength);
59720                             }
59721                             return 0 /* False */;
59722                         }
59723                         if (!targetRestFlag && targetArity < sourceMinLength) {
59724                             if (reportErrors) {
59725                                 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity);
59726                             }
59727                             return 0 /* False */;
59728                         }
59729                         if (!targetRestFlag && sourceRestFlag) {
59730                             if (reportErrors) {
59731                                 if (sourceMinLength < targetMinLength) {
59732                                     reportError(ts.Diagnostics.Target_requires_0_element_s_but_source_may_have_fewer, targetMinLength);
59733                                 }
59734                                 else {
59735                                     reportError(ts.Diagnostics.Target_allows_only_0_element_s_but_source_may_have_more, targetArity);
59736                                 }
59737                             }
59738                             return 0 /* False */;
59739                         }
59740                         var maxArity = Math.max(sourceArity, targetArity);
59741                         for (var i = 0; i < maxArity; i++) {
59742                             var targetFlags = i < targetArity ? target.target.elementFlags[i] : targetRestFlag;
59743                             var sourceFlags = isTupleType(source) && i < sourceArity ? source.target.elementFlags[i] : sourceRestFlag;
59744                             var canExcludeDiscriminants = !!excludedProperties;
59745                             if (sourceFlags && targetFlags) {
59746                                 if (targetFlags & 8 /* Variadic */ && !(sourceFlags & 8 /* Variadic */) ||
59747                                     (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */))) {
59748                                     if (reportErrors) {
59749                                         reportError(ts.Diagnostics.Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other, i);
59750                                     }
59751                                     return 0 /* False */;
59752                                 }
59753                                 if (targetFlags & 1 /* Required */) {
59754                                     if (!(sourceFlags & 1 /* Required */)) {
59755                                         if (reportErrors) {
59756                                             reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, i, typeToString(source), typeToString(target));
59757                                         }
59758                                         return 0 /* False */;
59759                                     }
59760                                 }
59761                                 // We can only exclude discriminant properties if we have not yet encountered a variable-length element.
59762                                 if (canExcludeDiscriminants) {
59763                                     if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) {
59764                                         canExcludeDiscriminants = false;
59765                                     }
59766                                     if (canExcludeDiscriminants && (excludedProperties === null || excludedProperties === void 0 ? void 0 : excludedProperties.has(("" + i)))) {
59767                                         continue;
59768                                     }
59769                                 }
59770                                 var sourceType = getTypeArguments(source)[Math.min(i, sourceArity - 1)];
59771                                 var targetType = getTypeArguments(target)[Math.min(i, targetArity - 1)];
59772                                 var targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) : targetType;
59773                                 var related = isRelatedTo(sourceType, targetCheckType, reportErrors, /*headMessage*/ undefined, intersectionState);
59774                                 if (!related) {
59775                                     if (reportErrors) {
59776                                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, i);
59777                                     }
59778                                     return 0 /* False */;
59779                                 }
59780                                 result &= related;
59781                             }
59782                         }
59783                         return result;
59784                     }
59785                     if (target.target.combinedFlags & 12 /* Variable */) {
59786                         return 0 /* False */;
59787                     }
59788                 }
59789                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
59790                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
59791                 if (unmatchedProperty) {
59792                     if (reportErrors) {
59793                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
59794                     }
59795                     return 0 /* False */;
59796                 }
59797                 if (isObjectLiteralType(target)) {
59798                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
59799                         var sourceProp = _a[_i];
59800                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
59801                             var sourceType = getTypeOfSymbol(sourceProp);
59802                             if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
59803                                 if (reportErrors) {
59804                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
59805                                 }
59806                                 return 0 /* False */;
59807                             }
59808                         }
59809                     }
59810                 }
59811                 // We only call this for union target types when we're attempting to do excess property checking - in those cases, we want to get _all possible props_
59812                 // from the target union, across all members
59813                 var properties = getPropertiesOfType(target);
59814                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
59815                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
59816                     var targetProp = _c[_b];
59817                     var name = targetProp.escapedName;
59818                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
59819                         var sourceProp = getPropertyOfType(source, name);
59820                         if (sourceProp && sourceProp !== targetProp) {
59821                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
59822                             if (!related) {
59823                                 return 0 /* False */;
59824                             }
59825                             result &= related;
59826                         }
59827                     }
59828                 }
59829                 return result;
59830             }
59831             function propertiesIdenticalTo(source, target, excludedProperties) {
59832                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
59833                     return 0 /* False */;
59834                 }
59835                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
59836                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
59837                 if (sourceProperties.length !== targetProperties.length) {
59838                     return 0 /* False */;
59839                 }
59840                 var result = -1 /* True */;
59841                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
59842                     var sourceProp = sourceProperties_1[_i];
59843                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
59844                     if (!targetProp) {
59845                         return 0 /* False */;
59846                     }
59847                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
59848                     if (!related) {
59849                         return 0 /* False */;
59850                     }
59851                     result &= related;
59852                 }
59853                 return result;
59854             }
59855             function signaturesRelatedTo(source, target, kind, reportErrors) {
59856                 var _a, _b;
59857                 if (relation === identityRelation) {
59858                     return signaturesIdenticalTo(source, target, kind);
59859                 }
59860                 if (target === anyFunctionType || source === anyFunctionType) {
59861                     return -1 /* True */;
59862                 }
59863                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
59864                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
59865                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
59866                     0 /* Call */ : kind);
59867                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
59868                     0 /* Call */ : kind);
59869                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
59870                     if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
59871                         // An abstract constructor type is not assignable to a non-abstract constructor type
59872                         // as it would otherwise be possible to new an abstract class. Note that the assignability
59873                         // check we perform for an extends clause excludes construct signatures from the target,
59874                         // so this check never proceeds.
59875                         if (reportErrors) {
59876                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
59877                         }
59878                         return 0 /* False */;
59879                     }
59880                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
59881                         return 0 /* False */;
59882                     }
59883                 }
59884                 var result = -1 /* True */;
59885                 var saveErrorInfo = captureErrorCalculationState();
59886                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
59887                 var sourceObjectFlags = ts.getObjectFlags(source);
59888                 var targetObjectFlags = ts.getObjectFlags(target);
59889                 if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source.symbol === target.symbol) {
59890                     // We have instantiations of the same anonymous type (which typically will be the type of a
59891                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
59892                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
59893                     // as they are known to always be the same.
59894                     for (var i = 0; i < targetSignatures.length; i++) {
59895                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
59896                         if (!related) {
59897                             return 0 /* False */;
59898                         }
59899                         result &= related;
59900                     }
59901                 }
59902                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
59903                     // For simple functions (functions with a single signature) we only erase type parameters for
59904                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
59905                     // in the context of the target signature before checking the relationship. Ideally we'd do
59906                     // this regardless of the number of signatures, but the potential costs are prohibitive due
59907                     // to the quadratic nature of the logic below.
59908                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
59909                     var sourceSignature = ts.first(sourceSignatures);
59910                     var targetSignature = ts.first(targetSignatures);
59911                     result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature));
59912                     if (!result && reportErrors && kind === 1 /* Construct */ && (sourceObjectFlags & targetObjectFlags) &&
59913                         (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 166 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 166 /* Constructor */)) {
59914                         var constructSignatureToString = function (signature) {
59915                             return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* WriteArrowStyleSignature */, kind);
59916                         };
59917                         reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, constructSignatureToString(sourceSignature), constructSignatureToString(targetSignature));
59918                         reportError(ts.Diagnostics.Types_of_construct_signatures_are_incompatible);
59919                         return result;
59920                     }
59921                 }
59922                 else {
59923                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
59924                         var t = targetSignatures_1[_i];
59925                         // Only elaborate errors from the first failure
59926                         var shouldElaborateErrors = reportErrors;
59927                         for (var _c = 0, sourceSignatures_1 = sourceSignatures; _c < sourceSignatures_1.length; _c++) {
59928                             var s = sourceSignatures_1[_c];
59929                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
59930                             if (related) {
59931                                 result &= related;
59932                                 resetErrorInfo(saveErrorInfo);
59933                                 continue outer;
59934                             }
59935                             shouldElaborateErrors = false;
59936                         }
59937                         if (shouldElaborateErrors) {
59938                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
59939                         }
59940                         return 0 /* False */;
59941                     }
59942                 }
59943                 return result;
59944             }
59945             function reportIncompatibleCallSignatureReturn(siga, sigb) {
59946                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
59947                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
59948                 }
59949                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
59950             }
59951             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
59952                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
59953                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
59954                 }
59955                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
59956             }
59957             /**
59958              * See signatureAssignableTo, compareSignaturesIdentical
59959              */
59960             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
59961                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
59962             }
59963             function signaturesIdenticalTo(source, target, kind) {
59964                 var sourceSignatures = getSignaturesOfType(source, kind);
59965                 var targetSignatures = getSignaturesOfType(target, kind);
59966                 if (sourceSignatures.length !== targetSignatures.length) {
59967                     return 0 /* False */;
59968                 }
59969                 var result = -1 /* True */;
59970                 for (var i = 0; i < sourceSignatures.length; i++) {
59971                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
59972                     if (!related) {
59973                         return 0 /* False */;
59974                     }
59975                     result &= related;
59976                 }
59977                 return result;
59978             }
59979             function eachPropertyRelatedTo(source, target, kind, reportErrors) {
59980                 var result = -1 /* True */;
59981                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
59982                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
59983                     var prop = props_2[_i];
59984                     // Skip over ignored JSX and symbol-named members
59985                     if (isIgnoredJsxProperty(source, prop)) {
59986                         continue;
59987                     }
59988                     var nameType = getSymbolLinks(prop).nameType;
59989                     if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
59990                         continue;
59991                     }
59992                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
59993                         var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
59994                         if (!related) {
59995                             if (reportErrors) {
59996                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
59997                             }
59998                             return 0 /* False */;
59999                         }
60000                         result &= related;
60001                     }
60002                 }
60003                 return result;
60004             }
60005             function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
60006                 var related = isRelatedTo(sourceType, targetType, reportErrors);
60007                 if (!related && reportErrors) {
60008                     reportError(ts.Diagnostics.Index_signatures_are_incompatible);
60009                 }
60010                 return related;
60011             }
60012             function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
60013                 if (relation === identityRelation) {
60014                     return indexTypesIdenticalTo(source, target, kind);
60015                 }
60016                 var targetType = getIndexTypeOfType(target, kind);
60017                 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
60018                     // Index signature of type any permits assignment from everything but primitives
60019                     return -1 /* True */;
60020                 }
60021                 if (isGenericMappedType(source)) {
60022                     // A generic mapped type { [P in K]: T } is related to a type with an index signature
60023                     // { [x: string]: U }, and optionally with an index signature { [x: number]: V },
60024                     // if T is related to U and V.
60025                     return getIndexTypeOfType(target, 0 /* String */) ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
60026                 }
60027                 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
60028                 if (indexType) {
60029                     return indexTypeRelatedTo(indexType, targetType, reportErrors);
60030                 }
60031                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
60032                     // Intersection constituents are never considered to have an inferred index signature
60033                     var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
60034                     if (related && kind === 0 /* String */) {
60035                         var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
60036                         if (numberIndexType) {
60037                             related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
60038                         }
60039                     }
60040                     return related;
60041                 }
60042                 if (reportErrors) {
60043                     reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
60044                 }
60045                 return 0 /* False */;
60046             }
60047             function indexTypesIdenticalTo(source, target, indexKind) {
60048                 var targetInfo = getIndexInfoOfType(target, indexKind);
60049                 var sourceInfo = getIndexInfoOfType(source, indexKind);
60050                 if (!sourceInfo && !targetInfo) {
60051                     return -1 /* True */;
60052                 }
60053                 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
60054                     return isRelatedTo(sourceInfo.type, targetInfo.type);
60055                 }
60056                 return 0 /* False */;
60057             }
60058             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
60059                 if (!sourceSignature.declaration || !targetSignature.declaration) {
60060                     return true;
60061                 }
60062                 var sourceAccessibility = ts.getSelectedEffectiveModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
60063                 var targetAccessibility = ts.getSelectedEffectiveModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
60064                 // A public, protected and private signature is assignable to a private signature.
60065                 if (targetAccessibility === 8 /* Private */) {
60066                     return true;
60067                 }
60068                 // A public and protected signature is assignable to a protected signature.
60069                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
60070                     return true;
60071                 }
60072                 // Only a public signature is assignable to public signature.
60073                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
60074                     return true;
60075                 }
60076                 if (reportErrors) {
60077                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
60078                 }
60079                 return false;
60080             }
60081         }
60082         function typeCouldHaveTopLevelSingletonTypes(type) {
60083             // Okay, yes, 'boolean' is a union of 'true | false', but that's not useful
60084             // in error reporting scenarios. If you need to use this function but that detail matters,
60085             // feel free to add a flag.
60086             if (type.flags & 16 /* Boolean */) {
60087                 return false;
60088             }
60089             if (type.flags & 3145728 /* UnionOrIntersection */) {
60090                 return !!ts.forEach(type.types, typeCouldHaveTopLevelSingletonTypes);
60091             }
60092             if (type.flags & 465829888 /* Instantiable */) {
60093                 var constraint = getConstraintOfType(type);
60094                 if (constraint && constraint !== type) {
60095                     return typeCouldHaveTopLevelSingletonTypes(constraint);
60096                 }
60097             }
60098             return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */);
60099         }
60100         function getBestMatchingType(source, target, isRelatedTo) {
60101             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
60102             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
60103                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
60104                 findBestTypeForObjectLiteral(source, target) ||
60105                 findBestTypeForInvokable(source, target) ||
60106                 findMostOverlappyType(source, target);
60107         }
60108         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
60109             // undefined=unknown, true=discriminated, false=not discriminated
60110             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
60111             var discriminable = target.types.map(function (_) { return undefined; });
60112             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
60113                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
60114                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
60115                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
60116                     continue;
60117                 }
60118                 var i = 0;
60119                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
60120                     var type = _c[_b];
60121                     var targetType = getTypeOfPropertyOfType(type, propertyName);
60122                     if (targetType && related(getDiscriminatingType(), targetType)) {
60123                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
60124                     }
60125                     else {
60126                         discriminable[i] = false;
60127                     }
60128                     i++;
60129                 }
60130             }
60131             var match = discriminable.indexOf(/*searchElement*/ true);
60132             if (match === -1) {
60133                 return defaultValue;
60134             }
60135             // make sure exactly 1 matches before returning it
60136             var nextMatch = discriminable.indexOf(/*searchElement*/ true, match + 1);
60137             while (nextMatch !== -1) {
60138                 if (!isTypeIdenticalTo(target.types[match], target.types[nextMatch])) {
60139                     return defaultValue;
60140                 }
60141                 nextMatch = discriminable.indexOf(/*searchElement*/ true, nextMatch + 1);
60142             }
60143             return target.types[match];
60144         }
60145         /**
60146          * A type is 'weak' if it is an object type with at least one optional property
60147          * and no required properties, call/construct signatures or index signatures
60148          */
60149         function isWeakType(type) {
60150             if (type.flags & 524288 /* Object */) {
60151                 var resolved = resolveStructuredTypeMembers(type);
60152                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
60153                     !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
60154                     resolved.properties.length > 0 &&
60155                     ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
60156             }
60157             if (type.flags & 2097152 /* Intersection */) {
60158                 return ts.every(type.types, isWeakType);
60159             }
60160             return false;
60161         }
60162         function hasCommonProperties(source, target, isComparingJsxAttributes) {
60163             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
60164                 var prop = _a[_i];
60165                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
60166                     return true;
60167                 }
60168             }
60169             return false;
60170         }
60171         // Return a type reference where the source type parameter is replaced with the target marker
60172         // type, and flag the result as a marker type reference.
60173         function getMarkerTypeReference(type, source, target) {
60174             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
60175             result.objectFlags |= 8192 /* MarkerType */;
60176             return result;
60177         }
60178         function getAliasVariances(symbol) {
60179             var links = getSymbolLinks(symbol);
60180             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
60181                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
60182                 type.aliasTypeArgumentsContainsMarker = true;
60183                 return type;
60184             });
60185         }
60186         // Return an array containing the variance of each type parameter. The variance is effectively
60187         // a digest of the type comparisons that occur for each type argument when instantiations of the
60188         // generic type are structurally compared. We infer the variance information by comparing
60189         // instantiations of the generic type for type arguments with known relations. The function
60190         // returns the emptyArray singleton when invoked recursively for the given generic type.
60191         function getVariancesWorker(typeParameters, cache, createMarkerType) {
60192             var _a, _b, _c;
60193             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
60194             var variances = cache.variances;
60195             if (!variances) {
60196                 ts.tracing.push("check" /* Check */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 });
60197                 // The emptyArray singleton is used to signal a recursive invocation.
60198                 cache.variances = ts.emptyArray;
60199                 variances = [];
60200                 var _loop_19 = function (tp) {
60201                     var unmeasurable = false;
60202                     var unreliable = false;
60203                     var oldHandler = outofbandVarianceMarkerHandler;
60204                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
60205                     // We first compare instantiations where the type parameter is replaced with
60206                     // marker types that have a known subtype relationship. From this we can infer
60207                     // invariance, covariance, contravariance or bivariance.
60208                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
60209                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
60210                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
60211                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
60212                     // If the instantiations appear to be related bivariantly it may be because the
60213                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
60214                     // type). To determine this we compare instantiations where the type parameter is
60215                     // replaced with marker types that are known to be unrelated.
60216                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
60217                         variance = 4 /* Independent */;
60218                     }
60219                     outofbandVarianceMarkerHandler = oldHandler;
60220                     if (unmeasurable || unreliable) {
60221                         if (unmeasurable) {
60222                             variance |= 8 /* Unmeasurable */;
60223                         }
60224                         if (unreliable) {
60225                             variance |= 16 /* Unreliable */;
60226                         }
60227                     }
60228                     variances.push(variance);
60229                 };
60230                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
60231                     var tp = typeParameters_1[_i];
60232                     _loop_19(tp);
60233                 }
60234                 cache.variances = variances;
60235                 ts.tracing.pop();
60236             }
60237             return variances;
60238         }
60239         function getVariances(type) {
60240             // Arrays and tuples are known to be covariant, no need to spend time computing this.
60241             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
60242                 return arrayVariances;
60243             }
60244             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
60245         }
60246         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
60247         // See comment at call in recursiveTypeRelatedTo for when this case matters.
60248         function hasCovariantVoidArgument(typeArguments, variances) {
60249             for (var i = 0; i < variances.length; i++) {
60250                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
60251                     return true;
60252                 }
60253             }
60254             return false;
60255         }
60256         function isUnconstrainedTypeParameter(type) {
60257             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
60258         }
60259         function isNonDeferredTypeReference(type) {
60260             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
60261         }
60262         function isTypeReferenceWithGenericArguments(type) {
60263             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
60264         }
60265         /**
60266          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
60267          *   where A.id=111 and number.id=12
60268          */
60269         function getTypeReferenceId(type, typeParameters, depth) {
60270             if (depth === void 0) { depth = 0; }
60271             var result = "" + type.target.id;
60272             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
60273                 var t = _a[_i];
60274                 if (isUnconstrainedTypeParameter(t)) {
60275                     var index = typeParameters.indexOf(t);
60276                     if (index < 0) {
60277                         index = typeParameters.length;
60278                         typeParameters.push(t);
60279                     }
60280                     result += "=" + index;
60281                 }
60282                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
60283                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
60284                 }
60285                 else {
60286                     result += "-" + t.id;
60287                 }
60288             }
60289             return result;
60290         }
60291         /**
60292          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
60293          * For other cases, the types ids are used.
60294          */
60295         function getRelationKey(source, target, intersectionState, relation) {
60296             if (relation === identityRelation && source.id > target.id) {
60297                 var temp = source;
60298                 source = target;
60299                 target = temp;
60300             }
60301             var postFix = intersectionState ? ":" + intersectionState : "";
60302             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
60303                 var typeParameters = [];
60304                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
60305             }
60306             return source.id + "," + target.id + postFix;
60307         }
60308         // Invoke the callback for each underlying property symbol of the given symbol and return the first
60309         // value that isn't undefined.
60310         function forEachProperty(prop, callback) {
60311             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
60312                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
60313                     var t = _a[_i];
60314                     var p = getPropertyOfType(t, prop.escapedName);
60315                     var result = p && forEachProperty(p, callback);
60316                     if (result) {
60317                         return result;
60318                     }
60319                 }
60320                 return undefined;
60321             }
60322             return callback(prop);
60323         }
60324         // Return the declaring class type of a property or undefined if property not declared in class
60325         function getDeclaringClass(prop) {
60326             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
60327         }
60328         // Return the inherited type of the given property or undefined if property doesn't exist in a base class.
60329         function getTypeOfPropertyInBaseClass(property) {
60330             var classType = getDeclaringClass(property);
60331             var baseClassType = classType && getBaseTypes(classType)[0];
60332             return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName);
60333         }
60334         // Return true if some underlying source property is declared in a class that derives
60335         // from the given base class.
60336         function isPropertyInClassDerivedFrom(prop, baseClass) {
60337             return forEachProperty(prop, function (sp) {
60338                 var sourceClass = getDeclaringClass(sp);
60339                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
60340             });
60341         }
60342         // Return true if source property is a valid override of protected parts of target property.
60343         function isValidOverrideOf(sourceProp, targetProp) {
60344             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
60345                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
60346         }
60347         // Return true if the given class derives from each of the declaring classes of the protected
60348         // constituents of the given property.
60349         function isClassDerivedFromDeclaringClasses(checkClass, prop) {
60350             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
60351                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
60352         }
60353         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
60354         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
60355         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
60356         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
60357         // levels, but unequal at some level beyond that.
60358         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
60359         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
60360         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
60361         // It also detects when a recursive type reference has expanded 5 or more times, eg, if the true branch of
60362         // `type A<T> = null extends T ? [A<NonNullable<T>>] : [T]`
60363         // has expanded into `[A<NonNullable<NonNullable<NonNullable<NonNullable<NonNullable<T>>>>>>]`
60364         // in such cases we need to terminate the expansion, and we do so here.
60365         function isDeeplyNestedType(type, stack, depth) {
60366             if (depth >= 5) {
60367                 var identity_1 = getRecursionIdentity(type);
60368                 if (identity_1) {
60369                     var count = 0;
60370                     for (var i = 0; i < depth; i++) {
60371                         if (getRecursionIdentity(stack[i]) === identity_1) {
60372                             count++;
60373                             if (count >= 5) {
60374                                 return true;
60375                             }
60376                         }
60377                     }
60378                 }
60379             }
60380             return false;
60381         }
60382         // Types with constituents that could circularly reference the type have a recursion identity. The recursion
60383         // identity is some object that is common to instantiations of the type with the same origin.
60384         function getRecursionIdentity(type) {
60385             if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
60386                 if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) {
60387                     // Deferred type references are tracked through their associated AST node. This gives us finer
60388                     // granularity than using their associated target because each manifest type reference has a
60389                     // unique AST node.
60390                     return type.node;
60391                 }
60392                 if (type.symbol && !(ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol.flags & 32 /* Class */)) {
60393                     // We track all object types that have an associated symbol (representing the origin of the type), but
60394                     // exclude the static side of classes from this check since it shares its symbol with the instance side.
60395                     return type.symbol;
60396                 }
60397                 if (isTupleType(type)) {
60398                     // Tuple types are tracked through their target type
60399                     return type.target;
60400                 }
60401             }
60402             if (type.flags & 8388608 /* IndexedAccess */) {
60403                 // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A
60404                 do {
60405                     type = type.objectType;
60406                 } while (type.flags & 8388608 /* IndexedAccess */);
60407                 return type;
60408             }
60409             if (type.flags & 16777216 /* Conditional */) {
60410                 // The root object represents the origin of the conditional type
60411                 return type.root;
60412             }
60413             return undefined;
60414         }
60415         function isPropertyIdenticalTo(sourceProp, targetProp) {
60416             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
60417         }
60418         function compareProperties(sourceProp, targetProp, compareTypes) {
60419             // Two members are considered identical when
60420             // - they are public properties with identical names, optionality, and types,
60421             // - they are private or protected properties originating in the same declaration and having identical types
60422             if (sourceProp === targetProp) {
60423                 return -1 /* True */;
60424             }
60425             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
60426             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
60427             if (sourcePropAccessibility !== targetPropAccessibility) {
60428                 return 0 /* False */;
60429             }
60430             if (sourcePropAccessibility) {
60431                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
60432                     return 0 /* False */;
60433                 }
60434             }
60435             else {
60436                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
60437                     return 0 /* False */;
60438                 }
60439             }
60440             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
60441                 return 0 /* False */;
60442             }
60443             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
60444         }
60445         function isMatchingSignature(source, target, partialMatch) {
60446             var sourceParameterCount = getParameterCount(source);
60447             var targetParameterCount = getParameterCount(target);
60448             var sourceMinArgumentCount = getMinArgumentCount(source);
60449             var targetMinArgumentCount = getMinArgumentCount(target);
60450             var sourceHasRestParameter = hasEffectiveRestParameter(source);
60451             var targetHasRestParameter = hasEffectiveRestParameter(target);
60452             // A source signature matches a target signature if the two signatures have the same number of required,
60453             // optional, and rest parameters.
60454             if (sourceParameterCount === targetParameterCount &&
60455                 sourceMinArgumentCount === targetMinArgumentCount &&
60456                 sourceHasRestParameter === targetHasRestParameter) {
60457                 return true;
60458             }
60459             // A source signature partially matches a target signature if the target signature has no fewer required
60460             // parameters
60461             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
60462                 return true;
60463             }
60464             return false;
60465         }
60466         /**
60467          * See signatureRelatedTo, compareSignaturesIdentical
60468          */
60469         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
60470             // TODO (drosen): De-duplicate code between related functions.
60471             if (source === target) {
60472                 return -1 /* True */;
60473             }
60474             if (!(isMatchingSignature(source, target, partialMatch))) {
60475                 return 0 /* False */;
60476             }
60477             // Check that the two signatures have the same number of type parameters.
60478             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
60479                 return 0 /* False */;
60480             }
60481             // Check that type parameter constraints and defaults match. If they do, instantiate the source
60482             // signature with the type parameters of the target signature and continue the comparison.
60483             if (target.typeParameters) {
60484                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
60485                 for (var i = 0; i < target.typeParameters.length; i++) {
60486                     var s = source.typeParameters[i];
60487                     var t = target.typeParameters[i];
60488                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
60489                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
60490                         return 0 /* False */;
60491                     }
60492                 }
60493                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
60494             }
60495             var result = -1 /* True */;
60496             if (!ignoreThisTypes) {
60497                 var sourceThisType = getThisTypeOfSignature(source);
60498                 if (sourceThisType) {
60499                     var targetThisType = getThisTypeOfSignature(target);
60500                     if (targetThisType) {
60501                         var related = compareTypes(sourceThisType, targetThisType);
60502                         if (!related) {
60503                             return 0 /* False */;
60504                         }
60505                         result &= related;
60506                     }
60507                 }
60508             }
60509             var targetLen = getParameterCount(target);
60510             for (var i = 0; i < targetLen; i++) {
60511                 var s = getTypeAtPosition(source, i);
60512                 var t = getTypeAtPosition(target, i);
60513                 var related = compareTypes(t, s);
60514                 if (!related) {
60515                     return 0 /* False */;
60516                 }
60517                 result &= related;
60518             }
60519             if (!ignoreReturnTypes) {
60520                 var sourceTypePredicate = getTypePredicateOfSignature(source);
60521                 var targetTypePredicate = getTypePredicateOfSignature(target);
60522                 result &= sourceTypePredicate || targetTypePredicate ?
60523                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
60524                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
60525             }
60526             return result;
60527         }
60528         function compareTypePredicatesIdentical(source, target, compareTypes) {
60529             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
60530                 source.type === target.type ? -1 /* True */ :
60531                     source.type && target.type ? compareTypes(source.type, target.type) :
60532                         0 /* False */;
60533         }
60534         function literalTypesWithSameBaseType(types) {
60535             var commonBaseType;
60536             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
60537                 var t = types_13[_i];
60538                 var baseType = getBaseTypeOfLiteralType(t);
60539                 if (!commonBaseType) {
60540                     commonBaseType = baseType;
60541                 }
60542                 if (baseType === t || baseType !== commonBaseType) {
60543                     return false;
60544                 }
60545             }
60546             return true;
60547         }
60548         // When the candidate types are all literal types with the same base type, return a union
60549         // of those literal types. Otherwise, return the leftmost type for which no type to the
60550         // right is a supertype.
60551         function getSupertypeOrUnion(types) {
60552             return literalTypesWithSameBaseType(types) ?
60553                 getUnionType(types) :
60554                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
60555         }
60556         function getCommonSupertype(types) {
60557             if (!strictNullChecks) {
60558                 return getSupertypeOrUnion(types);
60559             }
60560             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
60561             return primaryTypes.length ?
60562                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
60563                 getUnionType(types, 2 /* Subtype */);
60564         }
60565         // Return the leftmost type for which no type to the right is a subtype.
60566         function getCommonSubtype(types) {
60567             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
60568         }
60569         function isArrayType(type) {
60570             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
60571         }
60572         function isReadonlyArrayType(type) {
60573             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
60574         }
60575         function isMutableArrayOrTuple(type) {
60576             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
60577         }
60578         function getElementTypeOfArrayType(type) {
60579             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
60580         }
60581         function isArrayLikeType(type) {
60582             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
60583             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
60584             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
60585         }
60586         function isEmptyArrayLiteralType(type) {
60587             var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
60588             return elementType === undefinedWideningType || elementType === implicitNeverType;
60589         }
60590         function isTupleLikeType(type) {
60591             return isTupleType(type) || !!getPropertyOfType(type, "0");
60592         }
60593         function isArrayOrTupleLikeType(type) {
60594             return isArrayLikeType(type) || isTupleLikeType(type);
60595         }
60596         function getTupleElementType(type, index) {
60597             var propType = getTypeOfPropertyOfType(type, "" + index);
60598             if (propType) {
60599                 return propType;
60600             }
60601             if (everyType(type, isTupleType)) {
60602                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
60603             }
60604             return undefined;
60605         }
60606         function isNeitherUnitTypeNorNever(type) {
60607             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
60608         }
60609         function isUnitType(type) {
60610             return !!(type.flags & 109440 /* Unit */);
60611         }
60612         function isLiteralType(type) {
60613             return type.flags & 16 /* Boolean */ ? true :
60614                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
60615                     isUnitType(type);
60616         }
60617         function getBaseTypeOfLiteralType(type) {
60618             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
60619                 type.flags & 128 /* StringLiteral */ ? stringType :
60620                     type.flags & 256 /* NumberLiteral */ ? numberType :
60621                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
60622                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
60623                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
60624                                     type;
60625         }
60626         function getWidenedLiteralType(type) {
60627             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
60628                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
60629                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
60630                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
60631                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
60632                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
60633                                     type;
60634         }
60635         function getWidenedUniqueESSymbolType(type) {
60636             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
60637                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
60638                     type;
60639         }
60640         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
60641             if (!isLiteralOfContextualType(type, contextualType)) {
60642                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
60643             }
60644             return type;
60645         }
60646         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
60647             if (type && isUnitType(type)) {
60648                 var contextualType = !contextualSignatureReturnType ? undefined :
60649                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
60650                         contextualSignatureReturnType;
60651                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
60652             }
60653             return type;
60654         }
60655         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
60656             if (type && isUnitType(type)) {
60657                 var contextualType = !contextualSignatureReturnType ? undefined :
60658                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
60659                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
60660             }
60661             return type;
60662         }
60663         /**
60664          * Check if a Type was written as a tuple type literal.
60665          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
60666          */
60667         function isTupleType(type) {
60668             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
60669         }
60670         function isGenericTupleType(type) {
60671             return isTupleType(type) && !!(type.target.combinedFlags & 8 /* Variadic */);
60672         }
60673         function isSingleElementGenericTupleType(type) {
60674             return isGenericTupleType(type) && type.target.elementFlags.length === 1;
60675         }
60676         function getRestTypeOfTupleType(type) {
60677             return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength);
60678         }
60679         function getRestArrayTypeOfTupleType(type) {
60680             var restType = getRestTypeOfTupleType(type);
60681             return restType && createArrayType(restType);
60682         }
60683         function getEndLengthOfType(type) {
60684             return isTupleType(type) ? getTypeReferenceArity(type) - ts.findLastIndex(type.target.elementFlags, function (f) { return !(f & (1 /* Required */ | 2 /* Optional */)); }) - 1 : 0;
60685         }
60686         function getElementTypeOfSliceOfTupleType(type, index, endSkipCount, writing) {
60687             if (endSkipCount === void 0) { endSkipCount = 0; }
60688             if (writing === void 0) { writing = false; }
60689             var length = getTypeReferenceArity(type) - endSkipCount;
60690             if (index < length) {
60691                 var typeArguments = getTypeArguments(type);
60692                 var elementTypes = [];
60693                 for (var i = index; i < length; i++) {
60694                     var t = typeArguments[i];
60695                     elementTypes.push(type.target.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t);
60696                 }
60697                 return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes);
60698             }
60699             return undefined;
60700         }
60701         function isTupleTypeStructureMatching(t1, t2) {
60702             return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) &&
60703                 ts.every(t1.target.elementFlags, function (f, i) { return (f & 12 /* Variable */) === (t2.target.elementFlags[i] & 12 /* Variable */); });
60704         }
60705         function isZeroBigInt(_a) {
60706             var value = _a.value;
60707             return value.base10Value === "0";
60708         }
60709         function getFalsyFlagsOfTypes(types) {
60710             var result = 0;
60711             for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
60712                 var t = types_14[_i];
60713                 result |= getFalsyFlags(t);
60714             }
60715             return result;
60716         }
60717         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
60718         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
60719         // no flags for all other types (including non-falsy literal types).
60720         function getFalsyFlags(type) {
60721             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
60722                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
60723                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
60724                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
60725                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
60726                                 type.flags & 117724 /* PossiblyFalsy */;
60727         }
60728         function removeDefinitelyFalsyTypes(type) {
60729             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
60730                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
60731                 type;
60732         }
60733         function extractDefinitelyFalsyTypes(type) {
60734             return mapType(type, getDefinitelyFalsyPartOfType);
60735         }
60736         function getDefinitelyFalsyPartOfType(type) {
60737             return type.flags & 4 /* String */ ? emptyStringType :
60738                 type.flags & 8 /* Number */ ? zeroType :
60739                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
60740                         type === regularFalseType ||
60741                             type === falseType ||
60742                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */ | 3 /* AnyOrUnknown */) ||
60743                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
60744                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
60745                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
60746                             neverType;
60747         }
60748         /**
60749          * Add undefined or null or both to a type if they are missing.
60750          * @param type - type to add undefined and/or null to if not present
60751          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
60752          */
60753         function getNullableType(type, flags) {
60754             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
60755             return missing === 0 ? type :
60756                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
60757                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
60758                         getUnionType([type, undefinedType, nullType]);
60759         }
60760         function getOptionalType(type) {
60761             ts.Debug.assert(strictNullChecks);
60762             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
60763         }
60764         function getGlobalNonNullableTypeInstantiation(type) {
60765             if (!deferredGlobalNonNullableTypeAlias) {
60766                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
60767             }
60768             // Use NonNullable global type alias if available to improve quick info/declaration emit
60769             if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
60770                 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
60771             }
60772             return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
60773         }
60774         function getNonNullableType(type) {
60775             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
60776         }
60777         function addOptionalTypeMarker(type) {
60778             return strictNullChecks ? getUnionType([type, optionalType]) : type;
60779         }
60780         function isNotOptionalTypeMarker(type) {
60781             return type !== optionalType;
60782         }
60783         function removeOptionalTypeMarker(type) {
60784             return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
60785         }
60786         function propagateOptionalTypeMarker(type, node, wasOptional) {
60787             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
60788         }
60789         function getOptionalExpressionType(exprType, expression) {
60790             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
60791                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
60792                     exprType;
60793         }
60794         /**
60795          * Is source potentially coercible to target type under `==`.
60796          * Assumes that `source` is a constituent of a union, hence
60797          * the boolean literal flag on the LHS, but not on the RHS.
60798          *
60799          * This does not fully replicate the semantics of `==`. The
60800          * intention is to catch cases that are clearly not right.
60801          *
60802          * Comparing (string | number) to number should not remove the
60803          * string element.
60804          *
60805          * Comparing (string | number) to 1 will remove the string
60806          * element, though this is not sound. This is a pragmatic
60807          * choice.
60808          *
60809          * @see narrowTypeByEquality
60810          *
60811          * @param source
60812          * @param target
60813          */
60814         function isCoercibleUnderDoubleEquals(source, target) {
60815             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
60816                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
60817         }
60818         /**
60819          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
60820          * with no call or construct signatures.
60821          */
60822         function isObjectTypeWithInferableIndex(type) {
60823             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
60824                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
60825                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
60826         }
60827         function createSymbolWithType(source, type) {
60828             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
60829             symbol.declarations = source.declarations;
60830             symbol.parent = source.parent;
60831             symbol.type = type;
60832             symbol.target = source;
60833             if (source.valueDeclaration) {
60834                 symbol.valueDeclaration = source.valueDeclaration;
60835             }
60836             var nameType = getSymbolLinks(source).nameType;
60837             if (nameType) {
60838                 symbol.nameType = nameType;
60839             }
60840             return symbol;
60841         }
60842         function transformTypeOfMembers(type, f) {
60843             var members = ts.createSymbolTable();
60844             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
60845                 var property = _a[_i];
60846                 var original = getTypeOfSymbol(property);
60847                 var updated = f(original);
60848                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
60849             }
60850             return members;
60851         }
60852         /**
60853          * If the the provided object literal is subject to the excess properties check,
60854          * create a new that is exempt. Recursively mark object literal members as exempt.
60855          * Leave signatures alone since they are not subject to the check.
60856          */
60857         function getRegularTypeOfObjectLiteral(type) {
60858             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
60859                 return type;
60860             }
60861             var regularType = type.regularType;
60862             if (regularType) {
60863                 return regularType;
60864             }
60865             var resolved = type;
60866             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
60867             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
60868             regularNew.flags = resolved.flags;
60869             regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
60870             type.regularType = regularNew;
60871             return regularNew;
60872         }
60873         function createWideningContext(parent, propertyName, siblings) {
60874             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
60875         }
60876         function getSiblingsOfContext(context) {
60877             if (!context.siblings) {
60878                 var siblings_1 = [];
60879                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
60880                     var type = _a[_i];
60881                     if (isObjectLiteralType(type)) {
60882                         var prop = getPropertyOfObjectType(type, context.propertyName);
60883                         if (prop) {
60884                             forEachType(getTypeOfSymbol(prop), function (t) {
60885                                 siblings_1.push(t);
60886                             });
60887                         }
60888                     }
60889                 }
60890                 context.siblings = siblings_1;
60891             }
60892             return context.siblings;
60893         }
60894         function getPropertiesOfContext(context) {
60895             if (!context.resolvedProperties) {
60896                 var names = new ts.Map();
60897                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
60898                     var t = _a[_i];
60899                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
60900                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
60901                             var prop = _c[_b];
60902                             names.set(prop.escapedName, prop);
60903                         }
60904                     }
60905                 }
60906                 context.resolvedProperties = ts.arrayFrom(names.values());
60907             }
60908             return context.resolvedProperties;
60909         }
60910         function getWidenedProperty(prop, context) {
60911             if (!(prop.flags & 4 /* Property */)) {
60912                 // Since get accessors already widen their return value there is no need to
60913                 // widen accessor based properties here.
60914                 return prop;
60915             }
60916             var original = getTypeOfSymbol(prop);
60917             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
60918             var widened = getWidenedTypeWithContext(original, propContext);
60919             return widened === original ? prop : createSymbolWithType(prop, widened);
60920         }
60921         function getUndefinedProperty(prop) {
60922             var cached = undefinedProperties.get(prop.escapedName);
60923             if (cached) {
60924                 return cached;
60925             }
60926             var result = createSymbolWithType(prop, undefinedType);
60927             result.flags |= 16777216 /* Optional */;
60928             undefinedProperties.set(prop.escapedName, result);
60929             return result;
60930         }
60931         function getWidenedTypeOfObjectLiteral(type, context) {
60932             var members = ts.createSymbolTable();
60933             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
60934                 var prop = _a[_i];
60935                 members.set(prop.escapedName, getWidenedProperty(prop, context));
60936             }
60937             if (context) {
60938                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
60939                     var prop = _c[_b];
60940                     if (!members.has(prop.escapedName)) {
60941                         members.set(prop.escapedName, getUndefinedProperty(prop));
60942                     }
60943                 }
60944             }
60945             var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
60946             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
60947             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
60948             result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
60949             return result;
60950         }
60951         function getWidenedType(type) {
60952             return getWidenedTypeWithContext(type, /*context*/ undefined);
60953         }
60954         function getWidenedTypeWithContext(type, context) {
60955             if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
60956                 if (context === undefined && type.widened) {
60957                     return type.widened;
60958                 }
60959                 var result = void 0;
60960                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
60961                     result = anyType;
60962                 }
60963                 else if (isObjectLiteralType(type)) {
60964                     result = getWidenedTypeOfObjectLiteral(type, context);
60965                 }
60966                 else if (type.flags & 1048576 /* Union */) {
60967                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
60968                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
60969                     // Widening an empty object literal transitions from a highly restrictive type to
60970                     // a highly inclusive one. For that reason we perform subtype reduction here if the
60971                     // union includes empty object types (e.g. reducing {} | string to just {}).
60972                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
60973                 }
60974                 else if (type.flags & 2097152 /* Intersection */) {
60975                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
60976                 }
60977                 else if (isArrayType(type) || isTupleType(type)) {
60978                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
60979                 }
60980                 if (result && context === undefined) {
60981                     type.widened = result;
60982                 }
60983                 return result || type;
60984             }
60985             return type;
60986         }
60987         /**
60988          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
60989          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
60990          * getWidenedType. But in some cases getWidenedType is called without reporting errors
60991          * (type argument inference is an example).
60992          *
60993          * The return value indicates whether an error was in fact reported. The particular circumstances
60994          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
60995          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
60996          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
60997          */
60998         function reportWideningErrorsInType(type) {
60999             var errorReported = false;
61000             if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
61001                 if (type.flags & 1048576 /* Union */) {
61002                     if (ts.some(type.types, isEmptyObjectType)) {
61003                         errorReported = true;
61004                     }
61005                     else {
61006                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
61007                             var t = _a[_i];
61008                             if (reportWideningErrorsInType(t)) {
61009                                 errorReported = true;
61010                             }
61011                         }
61012                     }
61013                 }
61014                 if (isArrayType(type) || isTupleType(type)) {
61015                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
61016                         var t = _c[_b];
61017                         if (reportWideningErrorsInType(t)) {
61018                             errorReported = true;
61019                         }
61020                     }
61021                 }
61022                 if (isObjectLiteralType(type)) {
61023                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
61024                         var p = _e[_d];
61025                         var t = getTypeOfSymbol(p);
61026                         if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
61027                             if (!reportWideningErrorsInType(t)) {
61028                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
61029                             }
61030                             errorReported = true;
61031                         }
61032                     }
61033                 }
61034             }
61035             return errorReported;
61036         }
61037         function reportImplicitAny(declaration, type, wideningKind) {
61038             var typeAsString = typeToString(getWidenedType(type));
61039             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
61040                 // Only report implicit any errors/suggestions in TS and ts-check JS files
61041                 return;
61042             }
61043             var diagnostic;
61044             switch (declaration.kind) {
61045                 case 216 /* BinaryExpression */:
61046                 case 163 /* PropertyDeclaration */:
61047                 case 162 /* PropertySignature */:
61048                     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;
61049                     break;
61050                 case 160 /* Parameter */:
61051                     var param = declaration;
61052                     if (ts.isIdentifier(param.name) &&
61053                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
61054                         param.parent.parameters.indexOf(param) > -1 &&
61055                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
61056                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
61057                         var newName = "arg" + param.parent.parameters.indexOf(param);
61058                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
61059                         return;
61060                     }
61061                     diagnostic = declaration.dotDotDotToken ?
61062                         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 :
61063                         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;
61064                     break;
61065                 case 198 /* BindingElement */:
61066                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
61067                     if (!noImplicitAny) {
61068                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
61069                         return;
61070                     }
61071                     break;
61072                 case 308 /* JSDocFunctionType */:
61073                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
61074                     return;
61075                 case 251 /* FunctionDeclaration */:
61076                 case 165 /* MethodDeclaration */:
61077                 case 164 /* MethodSignature */:
61078                 case 167 /* GetAccessor */:
61079                 case 168 /* SetAccessor */:
61080                 case 208 /* FunctionExpression */:
61081                 case 209 /* ArrowFunction */:
61082                     if (noImplicitAny && !declaration.name) {
61083                         if (wideningKind === 3 /* GeneratorYield */) {
61084                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
61085                         }
61086                         else {
61087                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
61088                         }
61089                         return;
61090                     }
61091                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
61092                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
61093                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
61094                     break;
61095                 case 190 /* MappedType */:
61096                     if (noImplicitAny) {
61097                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
61098                     }
61099                     return;
61100                 default:
61101                     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;
61102             }
61103             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
61104         }
61105         function reportErrorsFromWidening(declaration, type, wideningKind) {
61106             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
61107                 // Report implicit any error within type if possible, otherwise report error on declaration
61108                 if (!reportWideningErrorsInType(type)) {
61109                     reportImplicitAny(declaration, type, wideningKind);
61110                 }
61111             }
61112         }
61113         function applyToParameterTypes(source, target, callback) {
61114             var sourceCount = getParameterCount(source);
61115             var targetCount = getParameterCount(target);
61116             var sourceRestType = getEffectiveRestType(source);
61117             var targetRestType = getEffectiveRestType(target);
61118             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
61119             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
61120             var sourceThisType = getThisTypeOfSignature(source);
61121             if (sourceThisType) {
61122                 var targetThisType = getThisTypeOfSignature(target);
61123                 if (targetThisType) {
61124                     callback(sourceThisType, targetThisType);
61125                 }
61126             }
61127             for (var i = 0; i < paramCount; i++) {
61128                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
61129             }
61130             if (targetRestType) {
61131                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
61132             }
61133         }
61134         function applyToReturnTypes(source, target, callback) {
61135             var sourceTypePredicate = getTypePredicateOfSignature(source);
61136             var targetTypePredicate = getTypePredicateOfSignature(target);
61137             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
61138                 callback(sourceTypePredicate.type, targetTypePredicate.type);
61139             }
61140             else {
61141                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
61142             }
61143         }
61144         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
61145             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
61146         }
61147         function cloneInferenceContext(context, extraFlags) {
61148             if (extraFlags === void 0) { extraFlags = 0; }
61149             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
61150         }
61151         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
61152             var context = {
61153                 inferences: inferences,
61154                 signature: signature,
61155                 flags: flags,
61156                 compareTypes: compareTypes,
61157                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
61158                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
61159             };
61160             return context;
61161         }
61162         function mapToInferredType(context, t, fix) {
61163             var inferences = context.inferences;
61164             for (var i = 0; i < inferences.length; i++) {
61165                 var inference = inferences[i];
61166                 if (t === inference.typeParameter) {
61167                     if (fix && !inference.isFixed) {
61168                         clearCachedInferences(inferences);
61169                         inference.isFixed = true;
61170                     }
61171                     return getInferredType(context, i);
61172                 }
61173             }
61174             return t;
61175         }
61176         function clearCachedInferences(inferences) {
61177             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
61178                 var inference = inferences_1[_i];
61179                 if (!inference.isFixed) {
61180                     inference.inferredType = undefined;
61181                 }
61182             }
61183         }
61184         function createInferenceInfo(typeParameter) {
61185             return {
61186                 typeParameter: typeParameter,
61187                 candidates: undefined,
61188                 contraCandidates: undefined,
61189                 inferredType: undefined,
61190                 priority: undefined,
61191                 topLevel: true,
61192                 isFixed: false,
61193                 impliedArity: undefined
61194             };
61195         }
61196         function cloneInferenceInfo(inference) {
61197             return {
61198                 typeParameter: inference.typeParameter,
61199                 candidates: inference.candidates && inference.candidates.slice(),
61200                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
61201                 inferredType: inference.inferredType,
61202                 priority: inference.priority,
61203                 topLevel: inference.topLevel,
61204                 isFixed: inference.isFixed,
61205                 impliedArity: inference.impliedArity
61206             };
61207         }
61208         function cloneInferredPartOfContext(context) {
61209             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
61210             return inferences.length ?
61211                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
61212                 undefined;
61213         }
61214         function getMapperFromContext(context) {
61215             return context && context.mapper;
61216         }
61217         // Return true if the given type could possibly reference a type parameter for which
61218         // we perform type inference (i.e. a type parameter of a generic function). We cache
61219         // results for union and intersection types for performance reasons.
61220         function couldContainTypeVariables(type) {
61221             var objectFlags = ts.getObjectFlags(type);
61222             if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
61223                 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
61224             }
61225             var result = !!(type.flags & 465829888 /* Instantiable */ ||
61226                 type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
61227                     objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
61228                     objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) ||
61229                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables));
61230             if (type.flags & 3899393 /* ObjectFlagsType */) {
61231                 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
61232             }
61233             return result;
61234         }
61235         function isNonGenericTopLevelType(type) {
61236             if (type.aliasSymbol && !type.aliasTypeArguments) {
61237                 var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 254 /* TypeAliasDeclaration */);
61238                 return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 297 /* SourceFile */ ? true : n.kind === 256 /* ModuleDeclaration */ ? false : "quit"; }));
61239             }
61240             return false;
61241         }
61242         function isTypeParameterAtTopLevel(type, typeParameter) {
61243             return !!(type === typeParameter ||
61244                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
61245                 type.flags & 16777216 /* Conditional */ && (getTrueTypeFromConditionalType(type) === typeParameter || getFalseTypeFromConditionalType(type) === typeParameter));
61246         }
61247         /** Create an object with properties named in the string literal type. Every property has type `any` */
61248         function createEmptyObjectTypeFromStringLiteral(type) {
61249             var members = ts.createSymbolTable();
61250             forEachType(type, function (t) {
61251                 if (!(t.flags & 128 /* StringLiteral */)) {
61252                     return;
61253                 }
61254                 var name = ts.escapeLeadingUnderscores(t.value);
61255                 var literalProp = createSymbol(4 /* Property */, name);
61256                 literalProp.type = anyType;
61257                 if (t.symbol) {
61258                     literalProp.declarations = t.symbol.declarations;
61259                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
61260                 }
61261                 members.set(name, literalProp);
61262             });
61263             var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
61264             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
61265         }
61266         /**
61267          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
61268          * an object type with the same set of properties as the source type, where the type of each
61269          * property is computed by inferring from the source property type to X for the type
61270          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
61271          */
61272         function inferTypeForHomomorphicMappedType(source, target, constraint) {
61273             if (inInferTypeForHomomorphicMappedType) {
61274                 return undefined;
61275             }
61276             var key = source.id + "," + target.id + "," + constraint.id;
61277             if (reverseMappedCache.has(key)) {
61278                 return reverseMappedCache.get(key);
61279             }
61280             inInferTypeForHomomorphicMappedType = true;
61281             var type = createReverseMappedType(source, target, constraint);
61282             inInferTypeForHomomorphicMappedType = false;
61283             reverseMappedCache.set(key, type);
61284             return type;
61285         }
61286         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
61287         // an object literal type with at least one property of an inferable type. For example, an object
61288         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
61289         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
61290         function isPartiallyInferableType(type) {
61291             return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
61292                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) ||
61293                 isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType);
61294         }
61295         function createReverseMappedType(source, target, constraint) {
61296             // We consider a source type reverse mappable if it has a string index signature or if
61297             // it has one or more properties and is of a partially inferable type.
61298             if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
61299                 return undefined;
61300             }
61301             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
61302             // applied to the element type(s).
61303             if (isArrayType(source)) {
61304                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
61305             }
61306             if (isTupleType(source)) {
61307                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
61308                 var elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
61309                     ts.sameMap(source.target.elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
61310                     source.target.elementFlags;
61311                 return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations);
61312             }
61313             // For all other object types we infer a new object type where the reverse mapping has been
61314             // applied to the type of each property.
61315             var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
61316             reversed.source = source;
61317             reversed.mappedType = target;
61318             reversed.constraintType = constraint;
61319             return reversed;
61320         }
61321         function getTypeOfReverseMappedSymbol(symbol) {
61322             return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
61323         }
61324         function inferReverseMappedType(sourceType, target, constraint) {
61325             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
61326             var templateType = getTemplateTypeFromMappedType(target);
61327             var inference = createInferenceInfo(typeParameter);
61328             inferTypes([inference], sourceType, templateType);
61329             return getTypeFromInference(inference) || unknownType;
61330         }
61331         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
61332             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
61333             return __generator(this, function (_a) {
61334                 switch (_a.label) {
61335                     case 0:
61336                         properties = getPropertiesOfType(target);
61337                         _i = 0, properties_2 = properties;
61338                         _a.label = 1;
61339                     case 1:
61340                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
61341                         targetProp = properties_2[_i];
61342                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
61343                         if (isStaticPrivateIdentifierProperty(targetProp)) {
61344                             return [3 /*break*/, 5];
61345                         }
61346                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
61347                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
61348                         if (!!sourceProp) return [3 /*break*/, 3];
61349                         return [4 /*yield*/, targetProp];
61350                     case 2:
61351                         _a.sent();
61352                         return [3 /*break*/, 5];
61353                     case 3:
61354                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
61355                         targetType = getTypeOfSymbol(targetProp);
61356                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
61357                         sourceType = getTypeOfSymbol(sourceProp);
61358                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
61359                         return [4 /*yield*/, targetProp];
61360                     case 4:
61361                         _a.sent();
61362                         _a.label = 5;
61363                     case 5:
61364                         _i++;
61365                         return [3 /*break*/, 1];
61366                     case 6: return [2 /*return*/];
61367                 }
61368             });
61369         }
61370         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
61371             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
61372             if (!result.done)
61373                 return result.value;
61374         }
61375         function tupleTypesDefinitelyUnrelated(source, target) {
61376             return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength ||
61377                 !target.target.hasRestElement && (source.target.hasRestElement || target.target.fixedLength < source.target.fixedLength);
61378         }
61379         function typesDefinitelyUnrelated(source, target) {
61380             // Two tuple types with incompatible arities are definitely unrelated.
61381             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
61382             return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) :
61383                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
61384                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
61385         }
61386         function getTypeFromInference(inference) {
61387             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
61388                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
61389                     undefined;
61390         }
61391         function hasSkipDirectInferenceFlag(node) {
61392             return !!getNodeLinks(node).skipDirectInference;
61393         }
61394         function isFromInferenceBlockedSource(type) {
61395             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
61396         }
61397         function isValidBigIntString(s) {
61398             var scanner = ts.createScanner(99 /* ESNext */, /*skipTrivia*/ false);
61399             var success = true;
61400             scanner.setOnError(function () { return success = false; });
61401             scanner.setText(s + "n");
61402             var result = scanner.scan();
61403             if (result === 40 /* MinusToken */) {
61404                 result = scanner.scan();
61405             }
61406             var flags = scanner.getTokenFlags();
61407             // validate that
61408             // * scanning proceeded without error
61409             // * a bigint can be scanned, and that when it is scanned, it is
61410             // * the full length of the input string (so the scanner is one character beyond the augmented input length)
61411             // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input)
61412             return success && result === 9 /* BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* ContainsSeparator */);
61413         }
61414         function isStringLiteralTypeValueParsableAsType(s, target) {
61415             if (target.flags & 1048576 /* Union */) {
61416                 return !!forEachType(target, function (t) { return isStringLiteralTypeValueParsableAsType(s, t); });
61417             }
61418             switch (target) {
61419                 case stringType: return true;
61420                 case numberType: return s.value !== "" && isFinite(+(s.value));
61421                 case bigintType: return s.value !== "" && isValidBigIntString(s.value);
61422                 // the next 4 should be handled in `getTemplateLiteralType`, as they are all exactly one value, but are here for completeness, just in case
61423                 // this function is ever used on types which don't come from template literal holes
61424                 case trueType: return s.value === "true";
61425                 case falseType: return s.value === "false";
61426                 case undefinedType: return s.value === "undefined";
61427                 case nullType: return s.value === "null";
61428                 default: return !!(target.flags & 1 /* Any */);
61429             }
61430         }
61431         function inferLiteralsFromTemplateLiteralType(source, target) {
61432             var value = source.value;
61433             var texts = target.texts;
61434             var lastIndex = texts.length - 1;
61435             var startText = texts[0];
61436             var endText = texts[lastIndex];
61437             if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText)))
61438                 return undefined;
61439             var matches = [];
61440             var str = value.slice(startText.length, value.length - endText.length);
61441             var pos = 0;
61442             for (var i = 1; i < lastIndex; i++) {
61443                 var delim = texts[i];
61444                 var delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1;
61445                 if (delimPos < 0)
61446                     return undefined;
61447                 matches.push(getLiteralType(str.slice(pos, delimPos)));
61448                 pos = delimPos + delim.length;
61449             }
61450             matches.push(getLiteralType(str.slice(pos)));
61451             return matches;
61452         }
61453         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
61454             if (priority === void 0) { priority = 0; }
61455             if (contravariant === void 0) { contravariant = false; }
61456             var bivariant = false;
61457             var propagationType;
61458             var inferencePriority = 1024 /* MaxValue */;
61459             var allowComplexConstraintInference = true;
61460             var visited;
61461             var sourceStack;
61462             var targetStack;
61463             var expandingFlags = 0 /* None */;
61464             inferFromTypes(originalSource, originalTarget);
61465             function inferFromTypes(source, target) {
61466                 if (!couldContainTypeVariables(target)) {
61467                     return;
61468                 }
61469                 if (source === wildcardType) {
61470                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
61471                     // referenced in the target type, so we record it as the propagation type and infer from the
61472                     // target to itself. Then, as we find candidates we substitute the propagation type.
61473                     var savePropagationType = propagationType;
61474                     propagationType = source;
61475                     inferFromTypes(target, target);
61476                     propagationType = savePropagationType;
61477                     return;
61478                 }
61479                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
61480                     // Source and target are types originating in the same generic type alias declaration.
61481                     // Simply infer from source type arguments to target type arguments.
61482                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
61483                     return;
61484                 }
61485                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
61486                     // When source and target are the same union or intersection type, just relate each constituent
61487                     // type to itself.
61488                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
61489                         var t = _a[_i];
61490                         inferFromTypes(t, t);
61491                     }
61492                     return;
61493                 }
61494                 if (target.flags & 1048576 /* Union */) {
61495                     // First, infer between identically matching source and target constituents and remove the
61496                     // matching types.
61497                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
61498                     // Next, infer between closely matching source and target constituents and remove
61499                     // the matching types. Types closely match when they are instantiations of the same
61500                     // object type or instantiations of the same type alias.
61501                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
61502                     if (targets.length === 0) {
61503                         return;
61504                     }
61505                     target = getUnionType(targets);
61506                     if (sources.length === 0) {
61507                         // All source constituents have been matched and there is nothing further to infer from.
61508                         // However, simply making no inferences is undesirable because it could ultimately mean
61509                         // inferring a type parameter constraint. Instead, make a lower priority inference from
61510                         // the full source to whatever remains in the target. For example, when inferring from
61511                         // string to 'string | T', make a lower priority inference of string for T.
61512                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
61513                         return;
61514                     }
61515                     source = getUnionType(sources);
61516                 }
61517                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
61518                     // We reduce intersection types only when they contain naked type parameters. For example, when
61519                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
61520                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
61521                     // string[] on the source side and infer string for T.
61522                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
61523                     // in such scenarios.
61524                     if (!(source.flags & 1048576 /* Union */)) {
61525                         // Infer between identically matching source and target constituents and remove the matching types.
61526                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
61527                         if (sources.length === 0 || targets.length === 0) {
61528                             return;
61529                         }
61530                         source = getIntersectionType(sources);
61531                         target = getIntersectionType(targets);
61532                     }
61533                 }
61534                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
61535                     target = getActualTypeVariable(target);
61536                 }
61537                 if (target.flags & 8650752 /* TypeVariable */) {
61538                     // If target is a type parameter, make an inference, unless the source type contains
61539                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
61540                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
61541                     // it as an inference candidate. Hopefully, a better candidate will come along that does
61542                     // not contain anyFunctionType when we come back to this argument for its second round
61543                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
61544                     // when constructing types from type parameters that had no inference candidates).
61545                     if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
61546                         (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
61547                         return;
61548                     }
61549                     var inference = getInferenceInfoForType(target);
61550                     if (inference) {
61551                         if (!inference.isFixed) {
61552                             if (inference.priority === undefined || priority < inference.priority) {
61553                                 inference.candidates = undefined;
61554                                 inference.contraCandidates = undefined;
61555                                 inference.topLevel = true;
61556                                 inference.priority = priority;
61557                             }
61558                             if (priority === inference.priority) {
61559                                 var candidate = propagationType || source;
61560                                 // We make contravariant inferences only if we are in a pure contravariant position,
61561                                 // i.e. only if we have not descended into a bivariant position.
61562                                 if (contravariant && !bivariant) {
61563                                     if (!ts.contains(inference.contraCandidates, candidate)) {
61564                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
61565                                         clearCachedInferences(inferences);
61566                                     }
61567                                 }
61568                                 else if (!ts.contains(inference.candidates, candidate)) {
61569                                     inference.candidates = ts.append(inference.candidates, candidate);
61570                                     clearCachedInferences(inferences);
61571                                 }
61572                             }
61573                             if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
61574                                 inference.topLevel = false;
61575                                 clearCachedInferences(inferences);
61576                             }
61577                         }
61578                         inferencePriority = Math.min(inferencePriority, priority);
61579                         return;
61580                     }
61581                     else {
61582                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
61583                         var simplified = getSimplifiedType(target, /*writing*/ false);
61584                         if (simplified !== target) {
61585                             invokeOnce(source, simplified, inferFromTypes);
61586                         }
61587                         else if (target.flags & 8388608 /* IndexedAccess */) {
61588                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
61589                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
61590                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
61591                             if (indexType.flags & 465829888 /* Instantiable */) {
61592                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
61593                                 if (simplified_1 && simplified_1 !== target) {
61594                                     invokeOnce(source, simplified_1, inferFromTypes);
61595                                 }
61596                             }
61597                         }
61598                     }
61599                 }
61600                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
61601                     !(source.node && target.node)) {
61602                     // If source and target are references to the same generic type, infer from type arguments
61603                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
61604                 }
61605                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
61606                     contravariant = !contravariant;
61607                     inferFromTypes(source.type, target.type);
61608                     contravariant = !contravariant;
61609                 }
61610                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
61611                     var empty = createEmptyObjectTypeFromStringLiteral(source);
61612                     contravariant = !contravariant;
61613                     inferWithPriority(empty, target.type, 128 /* LiteralKeyof */);
61614                     contravariant = !contravariant;
61615                 }
61616                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
61617                     inferFromTypes(source.objectType, target.objectType);
61618                     inferFromTypes(source.indexType, target.indexType);
61619                 }
61620                 else if (source.flags & 268435456 /* StringMapping */ && target.flags & 268435456 /* StringMapping */) {
61621                     if (source.symbol === target.symbol) {
61622                         inferFromTypes(source.type, target.type);
61623                     }
61624                 }
61625                 else if (target.flags & 16777216 /* Conditional */) {
61626                     invokeOnce(source, target, inferToConditionalType);
61627                 }
61628                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
61629                     inferToMultipleTypes(source, target.types, target.flags);
61630                 }
61631                 else if (source.flags & 1048576 /* Union */) {
61632                     // Source is a union or intersection type, infer from each constituent type
61633                     var sourceTypes = source.types;
61634                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
61635                         var sourceType = sourceTypes_2[_e];
61636                         inferFromTypes(sourceType, target);
61637                     }
61638                 }
61639                 else if (target.flags & 134217728 /* TemplateLiteral */) {
61640                     inferToTemplateLiteralType(source, target);
61641                 }
61642                 else {
61643                     source = getReducedType(source);
61644                     if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) {
61645                         var apparentSource = getApparentType(source);
61646                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
61647                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
61648                         // with the simplified source.
61649                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
61650                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
61651                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
61652                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
61653                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
61654                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
61655                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
61656                             // remove this `allowComplexConstraintInference` flag.
61657                             allowComplexConstraintInference = false;
61658                             return inferFromTypes(apparentSource, target);
61659                         }
61660                         source = apparentSource;
61661                     }
61662                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
61663                         invokeOnce(source, target, inferFromObjectTypes);
61664                     }
61665                 }
61666                 if (source.flags & 25165824 /* Simplifiable */) {
61667                     var simplified = getSimplifiedType(source, contravariant);
61668                     if (simplified !== source) {
61669                         inferFromTypes(simplified, target);
61670                     }
61671                 }
61672             }
61673             function inferWithPriority(source, target, newPriority) {
61674                 var savePriority = priority;
61675                 priority |= newPriority;
61676                 inferFromTypes(source, target);
61677                 priority = savePriority;
61678             }
61679             function invokeOnce(source, target, action) {
61680                 var key = source.id + "," + target.id;
61681                 var status = visited && visited.get(key);
61682                 if (status !== undefined) {
61683                     inferencePriority = Math.min(inferencePriority, status);
61684                     return;
61685                 }
61686                 (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */);
61687                 var saveInferencePriority = inferencePriority;
61688                 inferencePriority = 1024 /* MaxValue */;
61689                 // We stop inferring and report a circularity if we encounter duplicate recursion identities on both
61690                 // the source side and the target side.
61691                 var saveExpandingFlags = expandingFlags;
61692                 var sourceIdentity = getRecursionIdentity(source) || source;
61693                 var targetIdentity = getRecursionIdentity(target) || target;
61694                 if (sourceIdentity && ts.contains(sourceStack, sourceIdentity))
61695                     expandingFlags |= 1 /* Source */;
61696                 if (targetIdentity && ts.contains(targetStack, targetIdentity))
61697                     expandingFlags |= 2 /* Target */;
61698                 if (expandingFlags !== 3 /* Both */) {
61699                     if (sourceIdentity)
61700                         (sourceStack || (sourceStack = [])).push(sourceIdentity);
61701                     if (targetIdentity)
61702                         (targetStack || (targetStack = [])).push(targetIdentity);
61703                     action(source, target);
61704                     if (targetIdentity)
61705                         targetStack.pop();
61706                     if (sourceIdentity)
61707                         sourceStack.pop();
61708                 }
61709                 else {
61710                     inferencePriority = -1 /* Circularity */;
61711                 }
61712                 expandingFlags = saveExpandingFlags;
61713                 visited.set(key, inferencePriority);
61714                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
61715             }
61716             function inferFromMatchingTypes(sources, targets, matches) {
61717                 var matchedSources;
61718                 var matchedTargets;
61719                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
61720                     var t = targets_1[_i];
61721                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
61722                         var s = sources_1[_a];
61723                         if (matches(s, t)) {
61724                             inferFromTypes(s, t);
61725                             matchedSources = ts.appendIfUnique(matchedSources, s);
61726                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
61727                         }
61728                     }
61729                 }
61730                 return [
61731                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
61732                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
61733                 ];
61734             }
61735             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
61736                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
61737                 for (var i = 0; i < count; i++) {
61738                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
61739                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
61740                     }
61741                     else {
61742                         inferFromTypes(sourceTypes[i], targetTypes[i]);
61743                     }
61744                 }
61745             }
61746             function inferFromContravariantTypes(source, target) {
61747                 if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) {
61748                     contravariant = !contravariant;
61749                     inferFromTypes(source, target);
61750                     contravariant = !contravariant;
61751                 }
61752                 else {
61753                     inferFromTypes(source, target);
61754                 }
61755             }
61756             function getInferenceInfoForType(type) {
61757                 if (type.flags & 8650752 /* TypeVariable */) {
61758                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
61759                         var inference = inferences_2[_i];
61760                         if (type === inference.typeParameter) {
61761                             return inference;
61762                         }
61763                     }
61764                 }
61765                 return undefined;
61766             }
61767             function getSingleTypeVariableFromIntersectionTypes(types) {
61768                 var typeVariable;
61769                 for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
61770                     var type = types_15[_i];
61771                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
61772                     if (!t || typeVariable && t !== typeVariable) {
61773                         return undefined;
61774                     }
61775                     typeVariable = t;
61776                 }
61777                 return typeVariable;
61778             }
61779             function inferToMultipleTypes(source, targets, targetFlags) {
61780                 var typeVariableCount = 0;
61781                 if (targetFlags & 1048576 /* Union */) {
61782                     var nakedTypeVariable = void 0;
61783                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
61784                     var matched_1 = new Array(sources.length);
61785                     var inferenceCircularity = false;
61786                     // First infer to types that are not naked type variables. For each source type we
61787                     // track whether inferences were made from that particular type to some target with
61788                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
61789                     // parameter.
61790                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
61791                         var t = targets_2[_i];
61792                         if (getInferenceInfoForType(t)) {
61793                             nakedTypeVariable = t;
61794                             typeVariableCount++;
61795                         }
61796                         else {
61797                             for (var i = 0; i < sources.length; i++) {
61798                                 var saveInferencePriority = inferencePriority;
61799                                 inferencePriority = 1024 /* MaxValue */;
61800                                 inferFromTypes(sources[i], t);
61801                                 if (inferencePriority === priority)
61802                                     matched_1[i] = true;
61803                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
61804                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
61805                             }
61806                         }
61807                     }
61808                     if (typeVariableCount === 0) {
61809                         // If every target is an intersection of types containing a single naked type variable,
61810                         // make a lower priority inference to that type variable. This handles inferring from
61811                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
61812                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
61813                         if (intersectionTypeVariable) {
61814                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
61815                         }
61816                         return;
61817                     }
61818                     // If the target has a single naked type variable and no inference circularities were
61819                     // encountered above (meaning we explored the types fully), create a union of the source
61820                     // types from which no inferences have been made so far and infer from that union to the
61821                     // naked type variable.
61822                     if (typeVariableCount === 1 && !inferenceCircularity) {
61823                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
61824                         if (unmatched.length) {
61825                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
61826                             return;
61827                         }
61828                     }
61829                 }
61830                 else {
61831                     // We infer from types that are not naked type variables first so that inferences we
61832                     // make from nested naked type variables and given slightly higher priority by virtue
61833                     // of being first in the candidates array.
61834                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
61835                         var t = targets_3[_a];
61836                         if (getInferenceInfoForType(t)) {
61837                             typeVariableCount++;
61838                         }
61839                         else {
61840                             inferFromTypes(source, t);
61841                         }
61842                     }
61843                 }
61844                 // Inferences directly to naked type variables are given lower priority as they are
61845                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
61846                 // we want to infer string for T, not Promise<string> | string. For intersection types
61847                 // we only infer to single naked type variables.
61848                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
61849                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
61850                         var t = targets_4[_b];
61851                         if (getInferenceInfoForType(t)) {
61852                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
61853                         }
61854                     }
61855                 }
61856             }
61857             function inferToMappedType(source, target, constraintType) {
61858                 if (constraintType.flags & 1048576 /* Union */) {
61859                     var result = false;
61860                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
61861                         var type = _a[_i];
61862                         result = inferToMappedType(source, target, type) || result;
61863                     }
61864                     return result;
61865                 }
61866                 if (constraintType.flags & 4194304 /* Index */) {
61867                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
61868                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
61869                     // type and then make a secondary inference from that type to T. We make a secondary inference
61870                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
61871                     var inference = getInferenceInfoForType(constraintType.type);
61872                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
61873                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
61874                         if (inferredType) {
61875                             // We assign a lower priority to inferences made from types containing non-inferrable
61876                             // types because we may only have a partial result (i.e. we may have failed to make
61877                             // reverse inferences for some properties).
61878                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
61879                                 8 /* PartialHomomorphicMappedType */ :
61880                                 4 /* HomomorphicMappedType */);
61881                         }
61882                     }
61883                     return true;
61884                 }
61885                 if (constraintType.flags & 262144 /* TypeParameter */) {
61886                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
61887                     // parameter. First infer from 'keyof S' to K.
61888                     inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */);
61889                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
61890                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
61891                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
61892                     // Pick<T, K>.
61893                     var extendedConstraint = getConstraintOfType(constraintType);
61894                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
61895                         return true;
61896                     }
61897                     // If no inferences can be made to K's constraint, infer from a union of the property types
61898                     // in the source to the template type X.
61899                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
61900                     var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
61901                     var numberIndexInfo = getNonEnumNumberIndexInfo(source);
61902                     var numberIndexType = numberIndexInfo && numberIndexInfo.type;
61903                     inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
61904                     return true;
61905                 }
61906                 return false;
61907             }
61908             function inferToConditionalType(source, target) {
61909                 if (source.flags & 16777216 /* Conditional */) {
61910                     inferFromTypes(source.checkType, target.checkType);
61911                     inferFromTypes(source.extendsType, target.extendsType);
61912                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
61913                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
61914                 }
61915                 else {
61916                     var savePriority = priority;
61917                     priority |= contravariant ? 32 /* ContravariantConditional */ : 0;
61918                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
61919                     inferToMultipleTypes(source, targetTypes, target.flags);
61920                     priority = savePriority;
61921                 }
61922             }
61923             function inferToTemplateLiteralType(source, target) {
61924                 var matches = source.flags & 128 /* StringLiteral */ ? inferLiteralsFromTemplateLiteralType(source, target) :
61925                     source.flags & 134217728 /* TemplateLiteral */ && ts.arraysEqual(source.texts, target.texts) ? source.types :
61926                         undefined;
61927                 var types = target.types;
61928                 for (var i = 0; i < types.length; i++) {
61929                     inferFromTypes(matches ? matches[i] : neverType, types[i]);
61930                 }
61931             }
61932             function inferFromObjectTypes(source, target) {
61933                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
61934                     // If source and target are references to the same generic type, infer from type arguments
61935                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
61936                     return;
61937                 }
61938                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
61939                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
61940                     // from S to T and from X to Y.
61941                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
61942                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
61943                     var sourceNameType = getNameTypeFromMappedType(source);
61944                     var targetNameType = getNameTypeFromMappedType(target);
61945                     if (sourceNameType && targetNameType)
61946                         inferFromTypes(sourceNameType, targetNameType);
61947                 }
61948                 if (ts.getObjectFlags(target) & 32 /* Mapped */ && !target.declaration.nameType) {
61949                     var constraintType = getConstraintTypeFromMappedType(target);
61950                     if (inferToMappedType(source, target, constraintType)) {
61951                         return;
61952                     }
61953                 }
61954                 // Infer from the members of source and target only if the two types are possibly related
61955                 if (!typesDefinitelyUnrelated(source, target)) {
61956                     if (isArrayType(source) || isTupleType(source)) {
61957                         if (isTupleType(target)) {
61958                             var sourceArity = getTypeReferenceArity(source);
61959                             var targetArity = getTypeReferenceArity(target);
61960                             var elementTypes = getTypeArguments(target);
61961                             var elementFlags = target.target.elementFlags;
61962                             // When source and target are tuple types with the same structure (fixed, variadic, and rest are matched
61963                             // to the same kind in each position), simply infer between the element types.
61964                             if (isTupleType(source) && isTupleTypeStructureMatching(source, target)) {
61965                                 for (var i = 0; i < targetArity; i++) {
61966                                     inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
61967                                 }
61968                                 return;
61969                             }
61970                             var startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0;
61971                             var sourceRestType = !isTupleType(source) || sourceArity > 0 && source.target.elementFlags[sourceArity - 1] & 4 /* Rest */ ?
61972                                 getTypeArguments(source)[sourceArity - 1] : undefined;
61973                             var endLength = !(target.target.combinedFlags & 12 /* Variable */) ? 0 :
61974                                 sourceRestType ? getEndLengthOfType(target) :
61975                                     Math.min(getEndLengthOfType(source), getEndLengthOfType(target));
61976                             var sourceEndLength = sourceRestType ? 0 : endLength;
61977                             // Infer between starting fixed elements.
61978                             for (var i = 0; i < startLength; i++) {
61979                                 inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
61980                             }
61981                             if (sourceRestType && sourceArity - startLength === 1) {
61982                                 // Single rest element remains in source, infer from that to every element in target
61983                                 for (var i = startLength; i < targetArity - endLength; i++) {
61984                                     inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(sourceRestType) : sourceRestType, elementTypes[i]);
61985                                 }
61986                             }
61987                             else {
61988                                 var middleLength = targetArity - startLength - endLength;
61989                                 if (middleLength === 2 && elementFlags[startLength] & elementFlags[startLength + 1] & 8 /* Variadic */ && isTupleType(source)) {
61990                                     // Middle of target is [...T, ...U] and source is tuple type
61991                                     var targetInfo = getInferenceInfoForType(elementTypes[startLength]);
61992                                     if (targetInfo && targetInfo.impliedArity !== undefined) {
61993                                         // Infer slices from source based on implied arity of T.
61994                                         inferFromTypes(sliceTupleType(source, startLength, sourceEndLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]);
61995                                         inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, sourceEndLength), elementTypes[startLength + 1]);
61996                                     }
61997                                 }
61998                                 else if (middleLength === 1 && elementFlags[startLength] & 8 /* Variadic */) {
61999                                     // Middle of target is exactly one variadic element. Infer the slice between the fixed parts in the source.
62000                                     // If target ends in optional element(s), make a lower priority a speculative inference.
62001                                     var endsInOptional = target.target.elementFlags[targetArity - 1] & 2 /* Optional */;
62002                                     var sourceSlice = isTupleType(source) ? sliceTupleType(source, startLength, sourceEndLength) : createArrayType(sourceRestType);
62003                                     inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? 2 /* SpeculativeTuple */ : 0);
62004                                 }
62005                                 else if (middleLength === 1 && elementFlags[startLength] & 4 /* Rest */) {
62006                                     // Middle of target is exactly one rest element. If middle of source is not empty, infer union of middle element types.
62007                                     var restType = isTupleType(source) ? getElementTypeOfSliceOfTupleType(source, startLength, sourceEndLength) : sourceRestType;
62008                                     if (restType) {
62009                                         inferFromTypes(restType, elementTypes[startLength]);
62010                                     }
62011                                 }
62012                             }
62013                             // Infer between ending fixed elements
62014                             for (var i = 0; i < endLength; i++) {
62015                                 inferFromTypes(sourceRestType || getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]);
62016                             }
62017                             return;
62018                         }
62019                         if (isArrayType(target)) {
62020                             inferFromIndexTypes(source, target);
62021                             return;
62022                         }
62023                     }
62024                     inferFromProperties(source, target);
62025                     inferFromSignatures(source, target, 0 /* Call */);
62026                     inferFromSignatures(source, target, 1 /* Construct */);
62027                     inferFromIndexTypes(source, target);
62028                 }
62029             }
62030             function inferFromProperties(source, target) {
62031                 var properties = getPropertiesOfObjectType(target);
62032                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
62033                     var targetProp = properties_3[_i];
62034                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
62035                     if (sourceProp) {
62036                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
62037                     }
62038                 }
62039             }
62040             function inferFromSignatures(source, target, kind) {
62041                 var sourceSignatures = getSignaturesOfType(source, kind);
62042                 var targetSignatures = getSignaturesOfType(target, kind);
62043                 var sourceLen = sourceSignatures.length;
62044                 var targetLen = targetSignatures.length;
62045                 var len = sourceLen < targetLen ? sourceLen : targetLen;
62046                 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
62047                 for (var i = 0; i < len; i++) {
62048                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
62049                 }
62050             }
62051             function inferFromSignature(source, target, skipParameters) {
62052                 if (!skipParameters) {
62053                     var saveBivariant = bivariant;
62054                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
62055                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
62056                     bivariant = bivariant || kind === 165 /* MethodDeclaration */ || kind === 164 /* MethodSignature */ || kind === 166 /* Constructor */;
62057                     applyToParameterTypes(source, target, inferFromContravariantTypes);
62058                     bivariant = saveBivariant;
62059                 }
62060                 applyToReturnTypes(source, target, inferFromTypes);
62061             }
62062             function inferFromIndexTypes(source, target) {
62063                 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
62064                 if (targetStringIndexType) {
62065                     var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
62066                         getImplicitIndexTypeOfType(source, 0 /* String */);
62067                     if (sourceIndexType) {
62068                         inferFromTypes(sourceIndexType, targetStringIndexType);
62069                     }
62070                 }
62071                 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
62072                 if (targetNumberIndexType) {
62073                     var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
62074                         getIndexTypeOfType(source, 0 /* String */) ||
62075                         getImplicitIndexTypeOfType(source, 1 /* Number */);
62076                     if (sourceIndexType) {
62077                         inferFromTypes(sourceIndexType, targetNumberIndexType);
62078                     }
62079                 }
62080             }
62081         }
62082         function isTypeOrBaseIdenticalTo(s, t) {
62083             return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
62084         }
62085         function isTypeCloselyMatchedBy(s, t) {
62086             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
62087                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
62088         }
62089         function hasPrimitiveConstraint(type) {
62090             var constraint = getConstraintOfTypeParameter(type);
62091             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
62092         }
62093         function isObjectLiteralType(type) {
62094             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
62095         }
62096         function isObjectOrArrayLiteralType(type) {
62097             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
62098         }
62099         function unionObjectAndArrayLiteralCandidates(candidates) {
62100             if (candidates.length > 1) {
62101                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
62102                 if (objectLiterals.length) {
62103                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
62104                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
62105                 }
62106             }
62107             return candidates;
62108         }
62109         function getContravariantInference(inference) {
62110             return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
62111         }
62112         function getCovariantInference(inference, signature) {
62113             // Extract all object and array literal types and replace them with a single widened and normalized type.
62114             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
62115             // We widen inferred literal types if
62116             // all inferences were made to top-level occurrences of the type parameter, and
62117             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
62118             // the type parameter was fixed during inference or does not occur at top-level in the return type.
62119             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
62120             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
62121                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
62122             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
62123                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
62124                     candidates;
62125             // If all inferences were made from a position that implies a combined result, infer a union type.
62126             // Otherwise, infer a common supertype.
62127             var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ?
62128                 getUnionType(baseCandidates, 2 /* Subtype */) :
62129                 getCommonSupertype(baseCandidates);
62130             return getWidenedType(unwidenedType);
62131         }
62132         function getInferredType(context, index) {
62133             var inference = context.inferences[index];
62134             if (!inference.inferredType) {
62135                 var inferredType = void 0;
62136                 var signature = context.signature;
62137                 if (signature) {
62138                     var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
62139                     if (inference.contraCandidates) {
62140                         var inferredContravariantType = getContravariantInference(inference);
62141                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
62142                         // unless the co-variant inference is a subtype and not 'never'.
62143                         inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
62144                             isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
62145                             inferredCovariantType : inferredContravariantType;
62146                     }
62147                     else if (inferredCovariantType) {
62148                         inferredType = inferredCovariantType;
62149                     }
62150                     else if (context.flags & 1 /* NoDefault */) {
62151                         // We use silentNeverType as the wildcard that signals no inferences.
62152                         inferredType = silentNeverType;
62153                     }
62154                     else {
62155                         // Infer either the default or the empty object type when no inferences were
62156                         // made. It is important to remember that in this case, inference still
62157                         // succeeds, meaning there is no error for not having inference candidates. An
62158                         // inference error only occurs when there are *conflicting* candidates, i.e.
62159                         // candidates with no common supertype.
62160                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
62161                         if (defaultType) {
62162                             // Instantiate the default type. Any forward reference to a type
62163                             // parameter should be instantiated to the empty object type.
62164                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
62165                         }
62166                     }
62167                 }
62168                 else {
62169                     inferredType = getTypeFromInference(inference);
62170                 }
62171                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
62172                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
62173                 if (constraint) {
62174                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
62175                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
62176                         inference.inferredType = inferredType = instantiatedConstraint;
62177                     }
62178                 }
62179             }
62180             return inference.inferredType;
62181         }
62182         function getDefaultTypeArgumentType(isInJavaScriptFile) {
62183             return isInJavaScriptFile ? anyType : unknownType;
62184         }
62185         function getInferredTypes(context) {
62186             var result = [];
62187             for (var i = 0; i < context.inferences.length; i++) {
62188                 result.push(getInferredType(context, i));
62189             }
62190             return result;
62191         }
62192         // EXPRESSION TYPE CHECKING
62193         function getCannotFindNameDiagnosticForName(node) {
62194             switch (node.escapedText) {
62195                 case "document":
62196                 case "console":
62197                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
62198                 case "$":
62199                     return compilerOptions.types
62200                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
62201                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery;
62202                 case "describe":
62203                 case "suite":
62204                 case "it":
62205                 case "test":
62206                     return compilerOptions.types
62207                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
62208                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha;
62209                 case "process":
62210                 case "require":
62211                 case "Buffer":
62212                 case "module":
62213                     return compilerOptions.types
62214                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
62215                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode;
62216                 case "Map":
62217                 case "Set":
62218                 case "Promise":
62219                 case "Symbol":
62220                 case "WeakMap":
62221                 case "WeakSet":
62222                 case "Iterator":
62223                 case "AsyncIterator":
62224                 case "SharedArrayBuffer":
62225                 case "Atomics":
62226                 case "AsyncIterable":
62227                 case "AsyncIterableIterator":
62228                 case "AsyncGenerator":
62229                 case "AsyncGeneratorFunction":
62230                 case "BigInt":
62231                 case "Reflect":
62232                 case "BigInt64Array":
62233                 case "BigUint64Array":
62234                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later;
62235                 default:
62236                     if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) {
62237                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
62238                     }
62239                     else {
62240                         return ts.Diagnostics.Cannot_find_name_0;
62241                     }
62242             }
62243         }
62244         function getResolvedSymbol(node) {
62245             var links = getNodeLinks(node);
62246             if (!links.resolvedSymbol) {
62247                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
62248                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
62249                     /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
62250             }
62251             return links.resolvedSymbol;
62252         }
62253         function isInTypeQuery(node) {
62254             // TypeScript 1.0 spec (April 2014): 3.6.3
62255             // A type query consists of the keyword typeof followed by an expression.
62256             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
62257             return !!ts.findAncestor(node, function (n) { return n.kind === 176 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 157 /* QualifiedName */ ? false : "quit"; });
62258         }
62259         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
62260         // separated by dots). The key consists of the id of the symbol referenced by the
62261         // leftmost identifier followed by zero or more property names separated by dots.
62262         // The result is undefined if the reference isn't a dotted name. We prefix nodes
62263         // occurring in an apparent type position with '@' because the control flow type
62264         // of such nodes may be based on the apparent type instead of the declared type.
62265         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
62266             switch (node.kind) {
62267                 case 78 /* Identifier */:
62268                     var symbol = getResolvedSymbol(node);
62269                     return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
62270                 case 107 /* ThisKeyword */:
62271                     return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType);
62272                 case 225 /* NonNullExpression */:
62273                 case 207 /* ParenthesizedExpression */:
62274                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
62275                 case 201 /* PropertyAccessExpression */:
62276                 case 202 /* ElementAccessExpression */:
62277                     var propName = getAccessedPropertyName(node);
62278                     if (propName !== undefined) {
62279                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
62280                         return key && key + "." + propName;
62281                     }
62282             }
62283             return undefined;
62284         }
62285         function isMatchingReference(source, target) {
62286             switch (target.kind) {
62287                 case 207 /* ParenthesizedExpression */:
62288                 case 225 /* NonNullExpression */:
62289                     return isMatchingReference(source, target.expression);
62290                 case 216 /* BinaryExpression */:
62291                     return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) ||
62292                         (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right));
62293             }
62294             switch (source.kind) {
62295                 case 78 /* Identifier */:
62296                 case 79 /* PrivateIdentifier */:
62297                     return target.kind === 78 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
62298                         (target.kind === 249 /* VariableDeclaration */ || target.kind === 198 /* BindingElement */) &&
62299                             getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
62300                 case 107 /* ThisKeyword */:
62301                     return target.kind === 107 /* ThisKeyword */;
62302                 case 105 /* SuperKeyword */:
62303                     return target.kind === 105 /* SuperKeyword */;
62304                 case 225 /* NonNullExpression */:
62305                 case 207 /* ParenthesizedExpression */:
62306                     return isMatchingReference(source.expression, target);
62307                 case 201 /* PropertyAccessExpression */:
62308                 case 202 /* ElementAccessExpression */:
62309                     return ts.isAccessExpression(target) &&
62310                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
62311                         isMatchingReference(source.expression, target.expression);
62312             }
62313             return false;
62314         }
62315         // Given a source x, check if target matches x or is an && operation with an operand that matches x.
62316         function containsTruthyCheck(source, target) {
62317             return isMatchingReference(source, target) ||
62318                 (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
62319                     (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
62320         }
62321         function getAccessedPropertyName(access) {
62322             return access.kind === 201 /* PropertyAccessExpression */ ? access.name.escapedText :
62323                 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
62324                     undefined;
62325         }
62326         function containsMatchingReference(source, target) {
62327             while (ts.isAccessExpression(source)) {
62328                 source = source.expression;
62329                 if (isMatchingReference(source, target)) {
62330                     return true;
62331                 }
62332             }
62333             return false;
62334         }
62335         function optionalChainContainsReference(source, target) {
62336             while (ts.isOptionalChain(source)) {
62337                 source = source.expression;
62338                 if (isMatchingReference(source, target)) {
62339                     return true;
62340                 }
62341             }
62342             return false;
62343         }
62344         function isDiscriminantProperty(type, name) {
62345             if (type && type.flags & 1048576 /* Union */) {
62346                 var prop = getUnionOrIntersectionProperty(type, name);
62347                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
62348                     if (prop.isDiscriminantProperty === undefined) {
62349                         prop.isDiscriminantProperty =
62350                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
62351                                 !maybeTypeOfKind(getTypeOfSymbol(prop), 465829888 /* Instantiable */);
62352                     }
62353                     return !!prop.isDiscriminantProperty;
62354                 }
62355             }
62356             return false;
62357         }
62358         function findDiscriminantProperties(sourceProperties, target) {
62359             var result;
62360             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
62361                 var sourceProperty = sourceProperties_2[_i];
62362                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
62363                     if (result) {
62364                         result.push(sourceProperty);
62365                         continue;
62366                     }
62367                     result = [sourceProperty];
62368                 }
62369             }
62370             return result;
62371         }
62372         function isOrContainsMatchingReference(source, target) {
62373             return isMatchingReference(source, target) || containsMatchingReference(source, target);
62374         }
62375         function hasMatchingArgument(callExpression, reference) {
62376             if (callExpression.arguments) {
62377                 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
62378                     var argument = _a[_i];
62379                     if (isOrContainsMatchingReference(reference, argument)) {
62380                         return true;
62381                     }
62382                 }
62383             }
62384             if (callExpression.expression.kind === 201 /* PropertyAccessExpression */ &&
62385                 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
62386                 return true;
62387             }
62388             return false;
62389         }
62390         function getFlowNodeId(flow) {
62391             if (!flow.id || flow.id < 0) {
62392                 flow.id = nextFlowId;
62393                 nextFlowId++;
62394             }
62395             return flow.id;
62396         }
62397         function typeMaybeAssignableTo(source, target) {
62398             if (!(source.flags & 1048576 /* Union */)) {
62399                 return isTypeAssignableTo(source, target);
62400             }
62401             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
62402                 var t = _a[_i];
62403                 if (isTypeAssignableTo(t, target)) {
62404                     return true;
62405                 }
62406             }
62407             return false;
62408         }
62409         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
62410         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
62411         // we remove type string.
62412         function getAssignmentReducedType(declaredType, assignedType) {
62413             if (declaredType !== assignedType) {
62414                 if (assignedType.flags & 131072 /* Never */) {
62415                     return assignedType;
62416                 }
62417                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
62418                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
62419                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
62420                 }
62421                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
62422                 // For now, when that happens, we give up and don't narrow at all.  (This also
62423                 // means we'll never narrow for erroneous assignments where the assigned type
62424                 // is not assignable to the declared type.)
62425                 if (isTypeAssignableTo(assignedType, reducedType)) {
62426                     return reducedType;
62427                 }
62428             }
62429             return declaredType;
62430         }
62431         function getTypeFactsOfTypes(types) {
62432             var result = 0 /* None */;
62433             for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
62434                 var t = types_16[_i];
62435                 result |= getTypeFacts(t);
62436             }
62437             return result;
62438         }
62439         function isFunctionObjectType(type) {
62440             // We do a quick check for a "bind" property before performing the more expensive subtype
62441             // check. This gives us a quicker out in the common case where an object type is not a function.
62442             var resolved = resolveStructuredTypeMembers(type);
62443             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
62444                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
62445         }
62446         function getTypeFacts(type) {
62447             var flags = type.flags;
62448             if (flags & 4 /* String */) {
62449                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
62450             }
62451             if (flags & 128 /* StringLiteral */) {
62452                 var isEmpty = type.value === "";
62453                 return strictNullChecks ?
62454                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
62455                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
62456             }
62457             if (flags & (8 /* Number */ | 32 /* Enum */)) {
62458                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
62459             }
62460             if (flags & 256 /* NumberLiteral */) {
62461                 var isZero = type.value === 0;
62462                 return strictNullChecks ?
62463                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
62464                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
62465             }
62466             if (flags & 64 /* BigInt */) {
62467                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
62468             }
62469             if (flags & 2048 /* BigIntLiteral */) {
62470                 var isZero = isZeroBigInt(type);
62471                 return strictNullChecks ?
62472                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
62473                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
62474             }
62475             if (flags & 16 /* Boolean */) {
62476                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
62477             }
62478             if (flags & 528 /* BooleanLike */) {
62479                 return strictNullChecks ?
62480                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
62481                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
62482             }
62483             if (flags & 524288 /* Object */) {
62484                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
62485                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
62486                     isFunctionObjectType(type) ?
62487                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
62488                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
62489             }
62490             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
62491                 return 9830144 /* UndefinedFacts */;
62492             }
62493             if (flags & 65536 /* Null */) {
62494                 return 9363232 /* NullFacts */;
62495             }
62496             if (flags & 12288 /* ESSymbolLike */) {
62497                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
62498             }
62499             if (flags & 67108864 /* NonPrimitive */) {
62500                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
62501             }
62502             if (flags & 131072 /* Never */) {
62503                 return 0 /* None */;
62504             }
62505             if (flags & 465829888 /* Instantiable */) {
62506                 return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
62507             }
62508             if (flags & 3145728 /* UnionOrIntersection */) {
62509                 return getTypeFactsOfTypes(type.types);
62510             }
62511             return 16777215 /* All */;
62512         }
62513         function getTypeWithFacts(type, include) {
62514             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
62515         }
62516         function getTypeWithDefault(type, defaultExpression) {
62517             if (defaultExpression) {
62518                 var defaultType = getTypeOfExpression(defaultExpression);
62519                 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
62520             }
62521             return type;
62522         }
62523         function getTypeOfDestructuredProperty(type, name) {
62524             var nameType = getLiteralTypeFromPropertyName(name);
62525             if (!isTypeUsableAsPropertyName(nameType))
62526                 return errorType;
62527             var text = getPropertyNameFromType(nameType);
62528             return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
62529                 isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, 1 /* Number */)) ||
62530                 includeUndefinedInIndexSignature(getIndexTypeOfType(type, 0 /* String */)) ||
62531                 errorType;
62532         }
62533         function getTypeOfDestructuredArrayElement(type, index) {
62534             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
62535                 includeUndefinedInIndexSignature(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined)) ||
62536                 errorType;
62537         }
62538         function includeUndefinedInIndexSignature(type) {
62539             if (!type)
62540                 return type;
62541             return compilerOptions.noUncheckedIndexedAccess ?
62542                 getUnionType([type, undefinedType]) :
62543                 type;
62544         }
62545         function getTypeOfDestructuredSpreadExpression(type) {
62546             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
62547         }
62548         function getAssignedTypeOfBinaryExpression(node) {
62549             var isDestructuringDefaultAssignment = node.parent.kind === 199 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
62550                 node.parent.kind === 288 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
62551             return isDestructuringDefaultAssignment ?
62552                 getTypeWithDefault(getAssignedType(node), node.right) :
62553                 getTypeOfExpression(node.right);
62554         }
62555         function isDestructuringAssignmentTarget(parent) {
62556             return parent.parent.kind === 216 /* BinaryExpression */ && parent.parent.left === parent ||
62557                 parent.parent.kind === 239 /* ForOfStatement */ && parent.parent.initializer === parent;
62558         }
62559         function getAssignedTypeOfArrayLiteralElement(node, element) {
62560             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
62561         }
62562         function getAssignedTypeOfSpreadExpression(node) {
62563             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
62564         }
62565         function getAssignedTypeOfPropertyAssignment(node) {
62566             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
62567         }
62568         function getAssignedTypeOfShorthandPropertyAssignment(node) {
62569             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
62570         }
62571         function getAssignedType(node) {
62572             var parent = node.parent;
62573             switch (parent.kind) {
62574                 case 238 /* ForInStatement */:
62575                     return stringType;
62576                 case 239 /* ForOfStatement */:
62577                     return checkRightHandSideOfForOf(parent) || errorType;
62578                 case 216 /* BinaryExpression */:
62579                     return getAssignedTypeOfBinaryExpression(parent);
62580                 case 210 /* DeleteExpression */:
62581                     return undefinedType;
62582                 case 199 /* ArrayLiteralExpression */:
62583                     return getAssignedTypeOfArrayLiteralElement(parent, node);
62584                 case 220 /* SpreadElement */:
62585                     return getAssignedTypeOfSpreadExpression(parent);
62586                 case 288 /* PropertyAssignment */:
62587                     return getAssignedTypeOfPropertyAssignment(parent);
62588                 case 289 /* ShorthandPropertyAssignment */:
62589                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
62590             }
62591             return errorType;
62592         }
62593         function getInitialTypeOfBindingElement(node) {
62594             var pattern = node.parent;
62595             var parentType = getInitialType(pattern.parent);
62596             var type = pattern.kind === 196 /* ObjectBindingPattern */ ?
62597                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
62598                 !node.dotDotDotToken ?
62599                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
62600                     getTypeOfDestructuredSpreadExpression(parentType);
62601             return getTypeWithDefault(type, node.initializer);
62602         }
62603         function getTypeOfInitializer(node) {
62604             // Return the cached type if one is available. If the type of the variable was inferred
62605             // from its initializer, we'll already have cached the type. Otherwise we compute it now
62606             // without caching such that transient types are reflected.
62607             var links = getNodeLinks(node);
62608             return links.resolvedType || getTypeOfExpression(node);
62609         }
62610         function getInitialTypeOfVariableDeclaration(node) {
62611             if (node.initializer) {
62612                 return getTypeOfInitializer(node.initializer);
62613             }
62614             if (node.parent.parent.kind === 238 /* ForInStatement */) {
62615                 return stringType;
62616             }
62617             if (node.parent.parent.kind === 239 /* ForOfStatement */) {
62618                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
62619             }
62620             return errorType;
62621         }
62622         function getInitialType(node) {
62623             return node.kind === 249 /* VariableDeclaration */ ?
62624                 getInitialTypeOfVariableDeclaration(node) :
62625                 getInitialTypeOfBindingElement(node);
62626         }
62627         function isEmptyArrayAssignment(node) {
62628             return node.kind === 249 /* VariableDeclaration */ && node.initializer &&
62629                 isEmptyArrayLiteral(node.initializer) ||
62630                 node.kind !== 198 /* BindingElement */ && node.parent.kind === 216 /* BinaryExpression */ &&
62631                     isEmptyArrayLiteral(node.parent.right);
62632         }
62633         function getReferenceCandidate(node) {
62634             switch (node.kind) {
62635                 case 207 /* ParenthesizedExpression */:
62636                     return getReferenceCandidate(node.expression);
62637                 case 216 /* BinaryExpression */:
62638                     switch (node.operatorToken.kind) {
62639                         case 62 /* EqualsToken */:
62640                         case 74 /* BarBarEqualsToken */:
62641                         case 75 /* AmpersandAmpersandEqualsToken */:
62642                         case 76 /* QuestionQuestionEqualsToken */:
62643                             return getReferenceCandidate(node.left);
62644                         case 27 /* CommaToken */:
62645                             return getReferenceCandidate(node.right);
62646                     }
62647             }
62648             return node;
62649         }
62650         function getReferenceRoot(node) {
62651             var parent = node.parent;
62652             return parent.kind === 207 /* ParenthesizedExpression */ ||
62653                 parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
62654                 parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
62655                 getReferenceRoot(parent) : node;
62656         }
62657         function getTypeOfSwitchClause(clause) {
62658             if (clause.kind === 284 /* CaseClause */) {
62659                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
62660             }
62661             return neverType;
62662         }
62663         function getSwitchClauseTypes(switchStatement) {
62664             var links = getNodeLinks(switchStatement);
62665             if (!links.switchTypes) {
62666                 links.switchTypes = [];
62667                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
62668                     var clause = _a[_i];
62669                     links.switchTypes.push(getTypeOfSwitchClause(clause));
62670                 }
62671             }
62672             return links.switchTypes;
62673         }
62674         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
62675             var witnesses = [];
62676             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
62677                 var clause = _a[_i];
62678                 if (clause.kind === 284 /* CaseClause */) {
62679                     if (ts.isStringLiteralLike(clause.expression)) {
62680                         witnesses.push(clause.expression.text);
62681                         continue;
62682                     }
62683                     return ts.emptyArray;
62684                 }
62685                 if (retainDefault)
62686                     witnesses.push(/*explicitDefaultStatement*/ undefined);
62687             }
62688             return witnesses;
62689         }
62690         function eachTypeContainedIn(source, types) {
62691             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
62692         }
62693         function isTypeSubsetOf(source, target) {
62694             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
62695         }
62696         function isTypeSubsetOfUnion(source, target) {
62697             if (source.flags & 1048576 /* Union */) {
62698                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
62699                     var t = _a[_i];
62700                     if (!containsType(target.types, t)) {
62701                         return false;
62702                     }
62703                 }
62704                 return true;
62705             }
62706             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
62707                 return true;
62708             }
62709             return containsType(target.types, source);
62710         }
62711         function forEachType(type, f) {
62712             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
62713         }
62714         function everyType(type, f) {
62715             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
62716         }
62717         function filterType(type, f) {
62718             if (type.flags & 1048576 /* Union */) {
62719                 var types = type.types;
62720                 var filtered = ts.filter(types, f);
62721                 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
62722             }
62723             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
62724         }
62725         function countTypes(type) {
62726             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
62727         }
62728         function mapType(type, mapper, noReductions) {
62729             if (type.flags & 131072 /* Never */) {
62730                 return type;
62731             }
62732             if (!(type.flags & 1048576 /* Union */)) {
62733                 return mapper(type);
62734             }
62735             var mappedTypes;
62736             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
62737                 var t = _a[_i];
62738                 var mapped = mapper(t);
62739                 if (mapped) {
62740                     if (!mappedTypes) {
62741                         mappedTypes = [mapped];
62742                     }
62743                     else {
62744                         mappedTypes.push(mapped);
62745                     }
62746                 }
62747             }
62748             return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
62749         }
62750         function extractTypesOfKind(type, kind) {
62751             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
62752         }
62753         // Return a new type in which occurrences of the string and number primitive types in
62754         // typeWithPrimitives have been replaced with occurrences of string literals and numeric
62755         // literals in typeWithLiterals, respectively.
62756         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
62757             if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
62758                 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
62759                 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
62760                 return mapType(typeWithPrimitives, function (t) {
62761                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
62762                         t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
62763                             t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
62764                 });
62765             }
62766             return typeWithPrimitives;
62767         }
62768         function isIncomplete(flowType) {
62769             return flowType.flags === 0;
62770         }
62771         function getTypeFromFlowType(flowType) {
62772             return flowType.flags === 0 ? flowType.type : flowType;
62773         }
62774         function createFlowType(type, incomplete) {
62775             return incomplete ? { flags: 0, type: type.flags & 131072 /* Never */ ? silentNeverType : type } : type;
62776         }
62777         // An evolving array type tracks the element types that have so far been seen in an
62778         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
62779         // array types are ultimately converted into manifest array types (using getFinalArrayType)
62780         // and never escape the getFlowTypeOfReference function.
62781         function createEvolvingArrayType(elementType) {
62782             var result = createObjectType(256 /* EvolvingArray */);
62783             result.elementType = elementType;
62784             return result;
62785         }
62786         function getEvolvingArrayType(elementType) {
62787             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
62788         }
62789         // When adding evolving array element types we do not perform subtype reduction. Instead,
62790         // we defer subtype reduction until the evolving array type is finalized into a manifest
62791         // array type.
62792         function addEvolvingArrayElementType(evolvingArrayType, node) {
62793             var elementType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)));
62794             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
62795         }
62796         function createFinalArrayType(elementType) {
62797             return elementType.flags & 131072 /* Never */ ?
62798                 autoArrayType :
62799                 createArrayType(elementType.flags & 1048576 /* Union */ ?
62800                     getUnionType(elementType.types, 2 /* Subtype */) :
62801                     elementType);
62802         }
62803         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
62804         function getFinalArrayType(evolvingArrayType) {
62805             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
62806         }
62807         function finalizeEvolvingArrayType(type) {
62808             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
62809         }
62810         function getElementTypeOfEvolvingArrayType(type) {
62811             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
62812         }
62813         function isEvolvingArrayTypeList(types) {
62814             var hasEvolvingArrayType = false;
62815             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
62816                 var t = types_17[_i];
62817                 if (!(t.flags & 131072 /* Never */)) {
62818                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
62819                         return false;
62820                     }
62821                     hasEvolvingArrayType = true;
62822                 }
62823             }
62824             return hasEvolvingArrayType;
62825         }
62826         // At flow control branch or loop junctions, if the type along every antecedent code path
62827         // is an evolving array type, we construct a combined evolving array type. Otherwise we
62828         // finalize all evolving array types.
62829         function getUnionOrEvolvingArrayType(types, subtypeReduction) {
62830             return isEvolvingArrayTypeList(types) ?
62831                 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
62832                 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
62833         }
62834         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
62835         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
62836         function isEvolvingArrayOperationTarget(node) {
62837             var root = getReferenceRoot(node);
62838             var parent = root.parent;
62839             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
62840                 parent.parent.kind === 203 /* CallExpression */
62841                     && ts.isIdentifier(parent.name)
62842                     && ts.isPushOrUnshiftIdentifier(parent.name));
62843             var isElementAssignment = parent.kind === 202 /* ElementAccessExpression */ &&
62844                 parent.expression === root &&
62845                 parent.parent.kind === 216 /* BinaryExpression */ &&
62846                 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
62847                 parent.parent.left === parent &&
62848                 !ts.isAssignmentTarget(parent.parent) &&
62849                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
62850             return isLengthPushOrUnshift || isElementAssignment;
62851         }
62852         function isDeclarationWithExplicitTypeAnnotation(declaration) {
62853             return (declaration.kind === 249 /* VariableDeclaration */ || declaration.kind === 160 /* Parameter */ ||
62854                 declaration.kind === 163 /* PropertyDeclaration */ || declaration.kind === 162 /* PropertySignature */) &&
62855                 !!ts.getEffectiveTypeAnnotationNode(declaration);
62856         }
62857         function getExplicitTypeOfSymbol(symbol, diagnostic) {
62858             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
62859                 return getTypeOfSymbol(symbol);
62860             }
62861             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
62862                 if (ts.getCheckFlags(symbol) & 262144 /* Mapped */) {
62863                     var origin = symbol.syntheticOrigin;
62864                     if (origin && getExplicitTypeOfSymbol(origin)) {
62865                         return getTypeOfSymbol(symbol);
62866                     }
62867                 }
62868                 var declaration = symbol.valueDeclaration;
62869                 if (declaration) {
62870                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
62871                         return getTypeOfSymbol(symbol);
62872                     }
62873                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) {
62874                         var statement = declaration.parent.parent;
62875                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
62876                         if (expressionType) {
62877                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
62878                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
62879                         }
62880                     }
62881                     if (diagnostic) {
62882                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
62883                     }
62884                 }
62885             }
62886         }
62887         // We require the dotted function name in an assertion expression to be comprised of identifiers
62888         // that reference function, method, class or value module symbols; or variable, property or
62889         // parameter symbols with declarations that have explicit type annotations. Such references are
62890         // resolvable with no possibility of triggering circularities in control flow analysis.
62891         function getTypeOfDottedName(node, diagnostic) {
62892             if (!(node.flags & 16777216 /* InWithStatement */)) {
62893                 switch (node.kind) {
62894                     case 78 /* Identifier */:
62895                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
62896                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
62897                     case 107 /* ThisKeyword */:
62898                         return getExplicitThisType(node);
62899                     case 105 /* SuperKeyword */:
62900                         return checkSuperExpression(node);
62901                     case 201 /* PropertyAccessExpression */:
62902                         var type = getTypeOfDottedName(node.expression, diagnostic);
62903                         var prop = type && getPropertyOfType(type, node.name.escapedText);
62904                         return prop && getExplicitTypeOfSymbol(prop, diagnostic);
62905                     case 207 /* ParenthesizedExpression */:
62906                         return getTypeOfDottedName(node.expression, diagnostic);
62907                 }
62908             }
62909         }
62910         function getEffectsSignature(node) {
62911             var links = getNodeLinks(node);
62912             var signature = links.effectsSignature;
62913             if (signature === undefined) {
62914                 // A call expression parented by an expression statement is a potential assertion. Other call
62915                 // expressions are potential type predicate function calls. In order to avoid triggering
62916                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
62917                 // target expression of an assertion.
62918                 var funcType = void 0;
62919                 if (node.parent.kind === 233 /* ExpressionStatement */) {
62920                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
62921                 }
62922                 else if (node.expression.kind !== 105 /* SuperKeyword */) {
62923                     if (ts.isOptionalChain(node)) {
62924                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
62925                     }
62926                     else {
62927                         funcType = checkNonNullExpression(node.expression);
62928                     }
62929                 }
62930                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
62931                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
62932                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
62933                         undefined;
62934                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
62935             }
62936             return signature === unknownSignature ? undefined : signature;
62937         }
62938         function hasTypePredicateOrNeverReturnType(signature) {
62939             return !!(getTypePredicateOfSignature(signature) ||
62940                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
62941         }
62942         function getTypePredicateArgument(predicate, callExpression) {
62943             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
62944                 return callExpression.arguments[predicate.parameterIndex];
62945             }
62946             var invokedExpression = ts.skipParentheses(callExpression.expression);
62947             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
62948         }
62949         function reportFlowControlError(node) {
62950             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
62951             var sourceFile = ts.getSourceFileOfNode(node);
62952             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
62953             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
62954         }
62955         function isReachableFlowNode(flow) {
62956             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
62957             lastFlowNode = flow;
62958             lastFlowNodeReachable = result;
62959             return result;
62960         }
62961         function isFalseExpression(expr) {
62962             var node = ts.skipParentheses(expr);
62963             return node.kind === 94 /* FalseKeyword */ || node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
62964                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
62965         }
62966         function isReachableFlowNodeWorker(flow, noCacheCheck) {
62967             while (true) {
62968                 if (flow === lastFlowNode) {
62969                     return lastFlowNodeReachable;
62970                 }
62971                 var flags = flow.flags;
62972                 if (flags & 4096 /* Shared */) {
62973                     if (!noCacheCheck) {
62974                         var id = getFlowNodeId(flow);
62975                         var reachable = flowNodeReachable[id];
62976                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
62977                     }
62978                     noCacheCheck = false;
62979                 }
62980                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
62981                     flow = flow.antecedent;
62982                 }
62983                 else if (flags & 512 /* Call */) {
62984                     var signature = getEffectsSignature(flow.node);
62985                     if (signature) {
62986                         var predicate = getTypePredicateOfSignature(signature);
62987                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */ && !predicate.type) {
62988                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
62989                             if (predicateArgument && isFalseExpression(predicateArgument)) {
62990                                 return false;
62991                             }
62992                         }
62993                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
62994                             return false;
62995                         }
62996                     }
62997                     flow = flow.antecedent;
62998                 }
62999                 else if (flags & 4 /* BranchLabel */) {
63000                     // A branching point is reachable if any branch is reachable.
63001                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
63002                 }
63003                 else if (flags & 8 /* LoopLabel */) {
63004                     // A loop is reachable if the control flow path that leads to the top is reachable.
63005                     flow = flow.antecedents[0];
63006                 }
63007                 else if (flags & 128 /* SwitchClause */) {
63008                     // The control flow path representing an unmatched value in a switch statement with
63009                     // no default clause is unreachable if the switch statement is exhaustive.
63010                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
63011                         return false;
63012                     }
63013                     flow = flow.antecedent;
63014                 }
63015                 else if (flags & 1024 /* ReduceLabel */) {
63016                     // Cache is unreliable once we start adjusting labels
63017                     lastFlowNode = undefined;
63018                     var target = flow.target;
63019                     var saveAntecedents = target.antecedents;
63020                     target.antecedents = flow.antecedents;
63021                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
63022                     target.antecedents = saveAntecedents;
63023                     return result;
63024                 }
63025                 else {
63026                     return !(flags & 1 /* Unreachable */);
63027                 }
63028             }
63029         }
63030         // Return true if the given flow node is preceded by a 'super(...)' call in every possible code path
63031         // leading to the node.
63032         function isPostSuperFlowNode(flow, noCacheCheck) {
63033             while (true) {
63034                 var flags = flow.flags;
63035                 if (flags & 4096 /* Shared */) {
63036                     if (!noCacheCheck) {
63037                         var id = getFlowNodeId(flow);
63038                         var postSuper = flowNodePostSuper[id];
63039                         return postSuper !== undefined ? postSuper : (flowNodePostSuper[id] = isPostSuperFlowNode(flow, /*noCacheCheck*/ true));
63040                     }
63041                     noCacheCheck = false;
63042                 }
63043                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 128 /* SwitchClause */)) {
63044                     flow = flow.antecedent;
63045                 }
63046                 else if (flags & 512 /* Call */) {
63047                     if (flow.node.expression.kind === 105 /* SuperKeyword */) {
63048                         return true;
63049                     }
63050                     flow = flow.antecedent;
63051                 }
63052                 else if (flags & 4 /* BranchLabel */) {
63053                     // A branching point is post-super if every branch is post-super.
63054                     return ts.every(flow.antecedents, function (f) { return isPostSuperFlowNode(f, /*noCacheCheck*/ false); });
63055                 }
63056                 else if (flags & 8 /* LoopLabel */) {
63057                     // A loop is post-super if the control flow path that leads to the top is post-super.
63058                     flow = flow.antecedents[0];
63059                 }
63060                 else if (flags & 1024 /* ReduceLabel */) {
63061                     var target = flow.target;
63062                     var saveAntecedents = target.antecedents;
63063                     target.antecedents = flow.antecedents;
63064                     var result = isPostSuperFlowNode(flow.antecedent, /*noCacheCheck*/ false);
63065                     target.antecedents = saveAntecedents;
63066                     return result;
63067                 }
63068                 else {
63069                     // Unreachable nodes are considered post-super to silence errors
63070                     return !!(flags & 1 /* Unreachable */);
63071                 }
63072             }
63073         }
63074         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
63075             if (initialType === void 0) { initialType = declaredType; }
63076             var key;
63077             var isKeySet = false;
63078             var flowDepth = 0;
63079             if (flowAnalysisDisabled) {
63080                 return errorType;
63081             }
63082             if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 536624127 /* Narrowable */)) {
63083                 return declaredType;
63084             }
63085             flowInvocationCount++;
63086             var sharedFlowStart = sharedFlowCount;
63087             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
63088             sharedFlowCount = sharedFlowStart;
63089             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
63090             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
63091             // on empty arrays are possible without implicit any errors and new element types can be inferred without
63092             // type mismatch errors.
63093             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
63094             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 225 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
63095                 return declaredType;
63096             }
63097             return resultType;
63098             function getOrSetCacheKey() {
63099                 if (isKeySet) {
63100                     return key;
63101                 }
63102                 isKeySet = true;
63103                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
63104             }
63105             function getTypeAtFlowNode(flow) {
63106                 if (flowDepth === 2000) {
63107                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
63108                     // and disable further control flow analysis in the containing function or module body.
63109                     ts.tracing.instant("check" /* Check */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id });
63110                     flowAnalysisDisabled = true;
63111                     reportFlowControlError(reference);
63112                     return errorType;
63113                 }
63114                 flowDepth++;
63115                 var sharedFlow;
63116                 while (true) {
63117                     var flags = flow.flags;
63118                     if (flags & 4096 /* Shared */) {
63119                         // We cache results of flow type resolution for shared nodes that were previously visited in
63120                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
63121                         // antecedent of more than one node.
63122                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
63123                             if (sharedFlowNodes[i] === flow) {
63124                                 flowDepth--;
63125                                 return sharedFlowTypes[i];
63126                             }
63127                         }
63128                         sharedFlow = flow;
63129                     }
63130                     var type = void 0;
63131                     if (flags & 16 /* Assignment */) {
63132                         type = getTypeAtFlowAssignment(flow);
63133                         if (!type) {
63134                             flow = flow.antecedent;
63135                             continue;
63136                         }
63137                     }
63138                     else if (flags & 512 /* Call */) {
63139                         type = getTypeAtFlowCall(flow);
63140                         if (!type) {
63141                             flow = flow.antecedent;
63142                             continue;
63143                         }
63144                     }
63145                     else if (flags & 96 /* Condition */) {
63146                         type = getTypeAtFlowCondition(flow);
63147                     }
63148                     else if (flags & 128 /* SwitchClause */) {
63149                         type = getTypeAtSwitchClause(flow);
63150                     }
63151                     else if (flags & 12 /* Label */) {
63152                         if (flow.antecedents.length === 1) {
63153                             flow = flow.antecedents[0];
63154                             continue;
63155                         }
63156                         type = flags & 4 /* BranchLabel */ ?
63157                             getTypeAtFlowBranchLabel(flow) :
63158                             getTypeAtFlowLoopLabel(flow);
63159                     }
63160                     else if (flags & 256 /* ArrayMutation */) {
63161                         type = getTypeAtFlowArrayMutation(flow);
63162                         if (!type) {
63163                             flow = flow.antecedent;
63164                             continue;
63165                         }
63166                     }
63167                     else if (flags & 1024 /* ReduceLabel */) {
63168                         var target = flow.target;
63169                         var saveAntecedents = target.antecedents;
63170                         target.antecedents = flow.antecedents;
63171                         type = getTypeAtFlowNode(flow.antecedent);
63172                         target.antecedents = saveAntecedents;
63173                     }
63174                     else if (flags & 2 /* Start */) {
63175                         // Check if we should continue with the control flow of the containing function.
63176                         var container = flow.node;
63177                         if (container && container !== flowContainer &&
63178                             reference.kind !== 201 /* PropertyAccessExpression */ &&
63179                             reference.kind !== 202 /* ElementAccessExpression */ &&
63180                             reference.kind !== 107 /* ThisKeyword */) {
63181                             flow = container.flowNode;
63182                             continue;
63183                         }
63184                         // At the top of the flow we have the initial type.
63185                         type = initialType;
63186                     }
63187                     else {
63188                         // Unreachable code errors are reported in the binding phase. Here we
63189                         // simply return the non-auto declared type to reduce follow-on errors.
63190                         type = convertAutoToAny(declaredType);
63191                     }
63192                     if (sharedFlow) {
63193                         // Record visited node and the associated type in the cache.
63194                         sharedFlowNodes[sharedFlowCount] = sharedFlow;
63195                         sharedFlowTypes[sharedFlowCount] = type;
63196                         sharedFlowCount++;
63197                     }
63198                     flowDepth--;
63199                     return type;
63200                 }
63201             }
63202             function getInitialOrAssignedType(flow) {
63203                 var node = flow.node;
63204                 return getConstraintForLocation(node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */ ?
63205                     getInitialType(node) :
63206                     getAssignedType(node), reference);
63207             }
63208             function getTypeAtFlowAssignment(flow) {
63209                 var node = flow.node;
63210                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
63211                 // only need to evaluate the assigned type if the declared type is a union type.
63212                 if (isMatchingReference(reference, node)) {
63213                     if (!isReachableFlowNode(flow)) {
63214                         return unreachableNeverType;
63215                     }
63216                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
63217                         var flowType = getTypeAtFlowNode(flow.antecedent);
63218                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
63219                     }
63220                     if (declaredType === autoType || declaredType === autoArrayType) {
63221                         if (isEmptyArrayAssignment(node)) {
63222                             return getEvolvingArrayType(neverType);
63223                         }
63224                         var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow));
63225                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
63226                     }
63227                     if (declaredType.flags & 1048576 /* Union */) {
63228                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
63229                     }
63230                     return declaredType;
63231                 }
63232                 // We didn't have a direct match. However, if the reference is a dotted name, this
63233                 // may be an assignment to a left hand part of the reference. For example, for a
63234                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
63235                 // return the declared type.
63236                 if (containsMatchingReference(reference, node)) {
63237                     if (!isReachableFlowNode(flow)) {
63238                         return unreachableNeverType;
63239                     }
63240                     // A matching dotted name might also be an expando property on a function *expression*,
63241                     // in which case we continue control flow analysis back to the function's declaration
63242                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
63243                         var init = ts.getDeclaredExpandoInitializer(node);
63244                         if (init && (init.kind === 208 /* FunctionExpression */ || init.kind === 209 /* ArrowFunction */)) {
63245                             return getTypeAtFlowNode(flow.antecedent);
63246                         }
63247                     }
63248                     return declaredType;
63249                 }
63250                 // for (const _ in ref) acts as a nonnull on ref
63251                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 238 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
63252                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
63253                 }
63254                 // Assignment doesn't affect reference
63255                 return undefined;
63256             }
63257             function narrowTypeByAssertion(type, expr) {
63258                 var node = ts.skipParentheses(expr);
63259                 if (node.kind === 94 /* FalseKeyword */) {
63260                     return unreachableNeverType;
63261                 }
63262                 if (node.kind === 216 /* BinaryExpression */) {
63263                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
63264                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
63265                     }
63266                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
63267                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
63268                     }
63269                 }
63270                 return narrowType(type, node, /*assumeTrue*/ true);
63271             }
63272             function getTypeAtFlowCall(flow) {
63273                 var signature = getEffectsSignature(flow.node);
63274                 if (signature) {
63275                     var predicate = getTypePredicateOfSignature(signature);
63276                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
63277                         var flowType = getTypeAtFlowNode(flow.antecedent);
63278                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
63279                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
63280                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
63281                                 type;
63282                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
63283                     }
63284                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
63285                         return unreachableNeverType;
63286                     }
63287                 }
63288                 return undefined;
63289             }
63290             function getTypeAtFlowArrayMutation(flow) {
63291                 if (declaredType === autoType || declaredType === autoArrayType) {
63292                     var node = flow.node;
63293                     var expr = node.kind === 203 /* CallExpression */ ?
63294                         node.expression.expression :
63295                         node.left.expression;
63296                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
63297                         var flowType = getTypeAtFlowNode(flow.antecedent);
63298                         var type = getTypeFromFlowType(flowType);
63299                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
63300                             var evolvedType_1 = type;
63301                             if (node.kind === 203 /* CallExpression */) {
63302                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
63303                                     var arg = _a[_i];
63304                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
63305                                 }
63306                             }
63307                             else {
63308                                 // 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)
63309                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
63310                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
63311                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
63312                                 }
63313                             }
63314                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
63315                         }
63316                         return flowType;
63317                     }
63318                 }
63319                 return undefined;
63320             }
63321             function getTypeAtFlowCondition(flow) {
63322                 var flowType = getTypeAtFlowNode(flow.antecedent);
63323                 var type = getTypeFromFlowType(flowType);
63324                 if (type.flags & 131072 /* Never */) {
63325                     return flowType;
63326                 }
63327                 // If we have an antecedent type (meaning we're reachable in some way), we first
63328                 // attempt to narrow the antecedent type. If that produces the never type, and if
63329                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
63330                 // take the type guard as an indication that control *could* reach here once we
63331                 // have the complete type. We proceed by switching to the silent never type which
63332                 // doesn't report errors when operators are applied to it. Note that this is the
63333                 // *only* place a silent never type is ever generated.
63334                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
63335                 var nonEvolvingType = finalizeEvolvingArrayType(type);
63336                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
63337                 if (narrowedType === nonEvolvingType) {
63338                     return flowType;
63339                 }
63340                 return createFlowType(narrowedType, isIncomplete(flowType));
63341             }
63342             function getTypeAtSwitchClause(flow) {
63343                 var expr = flow.switchStatement.expression;
63344                 var flowType = getTypeAtFlowNode(flow.antecedent);
63345                 var type = getTypeFromFlowType(flowType);
63346                 if (isMatchingReference(reference, expr)) {
63347                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
63348                 }
63349                 else if (expr.kind === 211 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
63350                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
63351                 }
63352                 else {
63353                     if (strictNullChecks) {
63354                         if (optionalChainContainsReference(expr, reference)) {
63355                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
63356                         }
63357                         else if (expr.kind === 211 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
63358                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
63359                         }
63360                     }
63361                     if (isMatchingReferenceDiscriminant(expr, type)) {
63362                         type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
63363                     }
63364                 }
63365                 return createFlowType(type, isIncomplete(flowType));
63366             }
63367             function getTypeAtFlowBranchLabel(flow) {
63368                 var antecedentTypes = [];
63369                 var subtypeReduction = false;
63370                 var seenIncomplete = false;
63371                 var bypassFlow;
63372                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
63373                     var antecedent = _a[_i];
63374                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
63375                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
63376                         bypassFlow = antecedent;
63377                         continue;
63378                     }
63379                     var flowType = getTypeAtFlowNode(antecedent);
63380                     var type = getTypeFromFlowType(flowType);
63381                     // If the type at a particular antecedent path is the declared type and the
63382                     // reference is known to always be assigned (i.e. when declared and initial types
63383                     // are the same), there is no reason to process more antecedents since the only
63384                     // possible outcome is subtypes that will be removed in the final union type anyway.
63385                     if (type === declaredType && declaredType === initialType) {
63386                         return type;
63387                     }
63388                     ts.pushIfUnique(antecedentTypes, type);
63389                     // If an antecedent type is not a subset of the declared type, we need to perform
63390                     // subtype reduction. This happens when a "foreign" type is injected into the control
63391                     // flow using the instanceof operator or a user defined type predicate.
63392                     if (!isTypeSubsetOf(type, declaredType)) {
63393                         subtypeReduction = true;
63394                     }
63395                     if (isIncomplete(flowType)) {
63396                         seenIncomplete = true;
63397                     }
63398                 }
63399                 if (bypassFlow) {
63400                     var flowType = getTypeAtFlowNode(bypassFlow);
63401                     var type = getTypeFromFlowType(flowType);
63402                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
63403                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
63404                     // the risk of circularities, we only want to perform them when they make a difference.
63405                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
63406                         if (type === declaredType && declaredType === initialType) {
63407                             return type;
63408                         }
63409                         antecedentTypes.push(type);
63410                         if (!isTypeSubsetOf(type, declaredType)) {
63411                             subtypeReduction = true;
63412                         }
63413                         if (isIncomplete(flowType)) {
63414                             seenIncomplete = true;
63415                         }
63416                     }
63417                 }
63418                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
63419             }
63420             function getTypeAtFlowLoopLabel(flow) {
63421                 // If we have previously computed the control flow type for the reference at
63422                 // this flow loop junction, return the cached type.
63423                 var id = getFlowNodeId(flow);
63424                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = new ts.Map());
63425                 var key = getOrSetCacheKey();
63426                 if (!key) {
63427                     // No cache key is generated when binding patterns are in unnarrowable situations
63428                     return declaredType;
63429                 }
63430                 var cached = cache.get(key);
63431                 if (cached) {
63432                     return cached;
63433                 }
63434                 // If this flow loop junction and reference are already being processed, return
63435                 // the union of the types computed for each branch so far, marked as incomplete.
63436                 // It is possible to see an empty array in cases where loops are nested and the
63437                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
63438                 // In such cases we restart the analysis of the inner loop, which will then see
63439                 // a non-empty in-process array for the outer loop and eventually terminate because
63440                 // the first antecedent of a loop junction is always the non-looping control flow
63441                 // path that leads to the top.
63442                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
63443                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
63444                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
63445                     }
63446                 }
63447                 // Add the flow loop junction and reference to the in-process stack and analyze
63448                 // each antecedent code path.
63449                 var antecedentTypes = [];
63450                 var subtypeReduction = false;
63451                 var firstAntecedentType;
63452                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
63453                     var antecedent = _a[_i];
63454                     var flowType = void 0;
63455                     if (!firstAntecedentType) {
63456                         // The first antecedent of a loop junction is always the non-looping control
63457                         // flow path that leads to the top.
63458                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
63459                     }
63460                     else {
63461                         // All but the first antecedent are the looping control flow paths that lead
63462                         // back to the loop junction. We track these on the flow loop stack.
63463                         flowLoopNodes[flowLoopCount] = flow;
63464                         flowLoopKeys[flowLoopCount] = key;
63465                         flowLoopTypes[flowLoopCount] = antecedentTypes;
63466                         flowLoopCount++;
63467                         var saveFlowTypeCache = flowTypeCache;
63468                         flowTypeCache = undefined;
63469                         flowType = getTypeAtFlowNode(antecedent);
63470                         flowTypeCache = saveFlowTypeCache;
63471                         flowLoopCount--;
63472                         // If we see a value appear in the cache it is a sign that control flow analysis
63473                         // was restarted and completed by checkExpressionCached. We can simply pick up
63474                         // the resulting type and bail out.
63475                         var cached_1 = cache.get(key);
63476                         if (cached_1) {
63477                             return cached_1;
63478                         }
63479                     }
63480                     var type = getTypeFromFlowType(flowType);
63481                     ts.pushIfUnique(antecedentTypes, type);
63482                     // If an antecedent type is not a subset of the declared type, we need to perform
63483                     // subtype reduction. This happens when a "foreign" type is injected into the control
63484                     // flow using the instanceof operator or a user defined type predicate.
63485                     if (!isTypeSubsetOf(type, declaredType)) {
63486                         subtypeReduction = true;
63487                     }
63488                     // If the type at a particular antecedent path is the declared type there is no
63489                     // reason to process more antecedents since the only possible outcome is subtypes
63490                     // that will be removed in the final union type anyway.
63491                     if (type === declaredType) {
63492                         break;
63493                     }
63494                 }
63495                 // The result is incomplete if the first antecedent (the non-looping control flow path)
63496                 // is incomplete.
63497                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
63498                 if (isIncomplete(firstAntecedentType)) {
63499                     return createFlowType(result, /*incomplete*/ true);
63500                 }
63501                 cache.set(key, result);
63502                 return result;
63503             }
63504             function isMatchingReferenceDiscriminant(expr, computedType) {
63505                 var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType;
63506                 if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
63507                     return false;
63508                 }
63509                 var name = getAccessedPropertyName(expr);
63510                 if (name === undefined) {
63511                     return false;
63512                 }
63513                 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name);
63514             }
63515             function narrowTypeByDiscriminant(type, access, narrowType) {
63516                 var propName = getAccessedPropertyName(access);
63517                 if (propName === undefined) {
63518                     return type;
63519                 }
63520                 var propType = getTypeOfPropertyOfType(type, propName);
63521                 if (!propType) {
63522                     return type;
63523                 }
63524                 var narrowedPropType = narrowType(propType);
63525                 return filterType(type, function (t) {
63526                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
63527                     return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
63528                 });
63529             }
63530             function narrowTypeByTruthiness(type, expr, assumeTrue) {
63531                 if (isMatchingReference(reference, expr)) {
63532                     return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
63533                 }
63534                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
63535                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
63536                 }
63537                 if (isMatchingReferenceDiscriminant(expr, type)) {
63538                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
63539                 }
63540                 return type;
63541             }
63542             function isTypePresencePossible(type, propName, assumeTrue) {
63543                 if (getIndexInfoOfType(type, 0 /* String */)) {
63544                     return true;
63545                 }
63546                 var prop = getPropertyOfType(type, propName);
63547                 if (prop) {
63548                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
63549                 }
63550                 return !assumeTrue;
63551             }
63552             function narrowByInKeyword(type, literal, assumeTrue) {
63553                 if (type.flags & (1048576 /* Union */ | 524288 /* Object */)
63554                     || isThisTypeParameter(type)
63555                     || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) {
63556                     var propName_1 = ts.escapeLeadingUnderscores(literal.text);
63557                     return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
63558                 }
63559                 return type;
63560             }
63561             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
63562                 switch (expr.operatorToken.kind) {
63563                     case 62 /* EqualsToken */:
63564                     case 74 /* BarBarEqualsToken */:
63565                     case 75 /* AmpersandAmpersandEqualsToken */:
63566                     case 76 /* QuestionQuestionEqualsToken */:
63567                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
63568                     case 34 /* EqualsEqualsToken */:
63569                     case 35 /* ExclamationEqualsToken */:
63570                     case 36 /* EqualsEqualsEqualsToken */:
63571                     case 37 /* ExclamationEqualsEqualsToken */:
63572                         var operator_1 = expr.operatorToken.kind;
63573                         var left_1 = getReferenceCandidate(expr.left);
63574                         var right_1 = getReferenceCandidate(expr.right);
63575                         if (left_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
63576                             return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
63577                         }
63578                         if (right_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
63579                             return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
63580                         }
63581                         if (isMatchingReference(reference, left_1)) {
63582                             return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
63583                         }
63584                         if (isMatchingReference(reference, right_1)) {
63585                             return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
63586                         }
63587                         if (strictNullChecks) {
63588                             if (optionalChainContainsReference(left_1, reference)) {
63589                                 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
63590                             }
63591                             else if (optionalChainContainsReference(right_1, reference)) {
63592                                 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
63593                             }
63594                         }
63595                         if (isMatchingReferenceDiscriminant(left_1, type)) {
63596                             return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
63597                         }
63598                         if (isMatchingReferenceDiscriminant(right_1, type)) {
63599                             return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
63600                         }
63601                         if (isMatchingConstructorReference(left_1)) {
63602                             return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
63603                         }
63604                         if (isMatchingConstructorReference(right_1)) {
63605                             return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
63606                         }
63607                         break;
63608                     case 101 /* InstanceOfKeyword */:
63609                         return narrowTypeByInstanceof(type, expr, assumeTrue);
63610                     case 100 /* InKeyword */:
63611                         var target = getReferenceCandidate(expr.right);
63612                         if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
63613                             return narrowByInKeyword(type, expr.left, assumeTrue);
63614                         }
63615                         break;
63616                     case 27 /* CommaToken */:
63617                         return narrowType(type, expr.right, assumeTrue);
63618                 }
63619                 return type;
63620             }
63621             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
63622                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
63623                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
63624                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
63625                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
63626                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
63627                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
63628                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
63629                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
63630                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
63631                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
63632                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
63633                 var valueType = getTypeOfExpression(value);
63634                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
63635                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
63636                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
63637                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
63638             }
63639             function narrowTypeByEquality(type, operator, value, assumeTrue) {
63640                 if (type.flags & 1 /* Any */) {
63641                     return type;
63642                 }
63643                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
63644                     assumeTrue = !assumeTrue;
63645                 }
63646                 var valueType = getTypeOfExpression(value);
63647                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
63648                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
63649                         return valueType;
63650                     }
63651                     if (valueType.flags & 524288 /* Object */) {
63652                         return nonPrimitiveType;
63653                     }
63654                     return type;
63655                 }
63656                 if (valueType.flags & 98304 /* Nullable */) {
63657                     if (!strictNullChecks) {
63658                         return type;
63659                     }
63660                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
63661                     var facts = doubleEquals ?
63662                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
63663                         valueType.flags & 65536 /* Null */ ?
63664                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
63665                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
63666                     return getTypeWithFacts(type, facts);
63667                 }
63668                 if (assumeTrue) {
63669                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
63670                         (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
63671                         function (t) { return areTypesComparable(t, valueType); };
63672                     return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType);
63673                 }
63674                 if (isUnitType(valueType)) {
63675                     var regularType_1 = getRegularTypeOfLiteralType(valueType);
63676                     return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
63677                 }
63678                 return type;
63679             }
63680             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
63681                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
63682                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
63683                     assumeTrue = !assumeTrue;
63684                 }
63685                 var target = getReferenceCandidate(typeOfExpr.expression);
63686                 if (!isMatchingReference(reference, target)) {
63687                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
63688                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
63689                     }
63690                     return type;
63691                 }
63692                 if (type.flags & 1 /* Any */ && literal.text === "function") {
63693                     return type;
63694                 }
63695                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
63696                     // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
63697                     // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
63698                     if (typeOfExpr.parent.parent.kind === 216 /* BinaryExpression */) {
63699                         var expr = typeOfExpr.parent.parent;
63700                         if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
63701                             return nonPrimitiveType;
63702                         }
63703                     }
63704                     return getUnionType([nonPrimitiveType, nullType]);
63705                 }
63706                 var facts = assumeTrue ?
63707                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
63708                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
63709                 var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text);
63710                 return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts);
63711             }
63712             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
63713                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
63714                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
63715             }
63716             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
63717                 // We only narrow if all case expressions specify
63718                 // values with unit types, except for the case where
63719                 // `type` is unknown. In this instance we map object
63720                 // types to the nonPrimitive type and narrow with that.
63721                 var switchTypes = getSwitchClauseTypes(switchStatement);
63722                 if (!switchTypes.length) {
63723                     return type;
63724                 }
63725                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
63726                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
63727                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
63728                     var groundClauseTypes = void 0;
63729                     for (var i = 0; i < clauseTypes.length; i += 1) {
63730                         var t = clauseTypes[i];
63731                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
63732                             if (groundClauseTypes !== undefined) {
63733                                 groundClauseTypes.push(t);
63734                             }
63735                         }
63736                         else if (t.flags & 524288 /* Object */) {
63737                             if (groundClauseTypes === undefined) {
63738                                 groundClauseTypes = clauseTypes.slice(0, i);
63739                             }
63740                             groundClauseTypes.push(nonPrimitiveType);
63741                         }
63742                         else {
63743                             return type;
63744                         }
63745                     }
63746                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
63747                 }
63748                 var discriminantType = getUnionType(clauseTypes);
63749                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
63750                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
63751                 if (!hasDefaultClause) {
63752                     return caseType;
63753                 }
63754                 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
63755                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
63756             }
63757             function getImpliedTypeFromTypeofGuard(type, text) {
63758                 switch (text) {
63759                     case "function":
63760                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
63761                     case "object":
63762                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
63763                     default:
63764                         return typeofTypesByName.get(text);
63765                 }
63766             }
63767             // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are
63768             // super-types of the implied guard will be retained in the final type: this is because type-facts only
63769             // filter. Instead, we would like to replace those union constituents with the more precise type implied by
63770             // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not
63771             // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to
63772             // filtering by type-facts.
63773             function narrowUnionMemberByTypeof(candidate) {
63774                 return function (type) {
63775                     if (isTypeSubtypeOf(type, candidate)) {
63776                         return type;
63777                     }
63778                     if (isTypeSubtypeOf(candidate, type)) {
63779                         return candidate;
63780                     }
63781                     if (type.flags & 465829888 /* Instantiable */) {
63782                         var constraint = getBaseConstraintOfType(type) || anyType;
63783                         if (isTypeSubtypeOf(candidate, constraint)) {
63784                             return getIntersectionType([type, candidate]);
63785                         }
63786                     }
63787                     return type;
63788                 };
63789             }
63790             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
63791                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
63792                 if (!switchWitnesses.length) {
63793                     return type;
63794                 }
63795                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
63796                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
63797                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
63798                 var clauseWitnesses;
63799                 var switchFacts;
63800                 if (defaultCaseLocation > -1) {
63801                     // We no longer need the undefined denoting an explicit default case. Remove the undefined and
63802                     // fix-up clauseStart and clauseEnd.  This means that we don't have to worry about undefined in the
63803                     // witness array.
63804                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
63805                     // The adjusted clause start and end after removing the `default` statement.
63806                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
63807                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
63808                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
63809                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
63810                 }
63811                 else {
63812                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
63813                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
63814                 }
63815                 if (hasDefaultClause) {
63816                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
63817                 }
63818                 /*
63819                   The implied type is the raw type suggested by a
63820                   value being caught in this clause.
63821
63822                   When the clause contains a default case we ignore
63823                   the implied type and try to narrow using any facts
63824                   we can learn: see `switchFacts`.
63825
63826                   Example:
63827                   switch (typeof x) {
63828                       case 'number':
63829                       case 'string': break;
63830                       default: break;
63831                       case 'number':
63832                       case 'boolean': break
63833                   }
63834
63835                   In the first clause (case `number` and `string`) the
63836                   implied type is number | string.
63837
63838                   In the default clause we de not compute an implied type.
63839
63840                   In the third clause (case `number` and `boolean`)
63841                   the naive implied type is number | boolean, however
63842                   we use the type facts to narrow the implied type to
63843                   boolean. We know that number cannot be selected
63844                   because it is caught in the first clause.
63845                 */
63846                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts);
63847                 return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts);
63848             }
63849             function isMatchingConstructorReference(expr) {
63850                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
63851                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
63852                     isMatchingReference(reference, expr.expression);
63853             }
63854             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
63855                 // Do not narrow when checking inequality.
63856                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
63857                     return type;
63858                 }
63859                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
63860                 var identifierType = getTypeOfExpression(identifier);
63861                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
63862                     return type;
63863                 }
63864                 // Get the prototype property of the type identifier so we can find out its type.
63865                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
63866                 if (!prototypeProperty) {
63867                     return type;
63868                 }
63869                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
63870                 var prototypeType = getTypeOfSymbol(prototypeProperty);
63871                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
63872                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
63873                     return type;
63874                 }
63875                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
63876                 if (isTypeAny(type)) {
63877                     return candidate;
63878                 }
63879                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
63880                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
63881                 function isConstructedBy(source, target) {
63882                     // If either the source or target type are a class type then we need to check that they are the same exact type.
63883                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
63884                     // that defines the same set of properties as class `A`, in that case they are structurally the same
63885                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
63886                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
63887                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
63888                         return source.symbol === target.symbol;
63889                     }
63890                     // For all other types just check that the `source` type is a subtype of the `target` type.
63891                     return isTypeSubtypeOf(source, target);
63892                 }
63893             }
63894             function narrowTypeByInstanceof(type, expr, assumeTrue) {
63895                 var left = getReferenceCandidate(expr.left);
63896                 if (!isMatchingReference(reference, left)) {
63897                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
63898                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
63899                     }
63900                     return type;
63901                 }
63902                 // Check that right operand is a function type with a prototype property
63903                 var rightType = getTypeOfExpression(expr.right);
63904                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
63905                     return type;
63906                 }
63907                 var targetType;
63908                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
63909                 if (prototypeProperty) {
63910                     // Target type is type of the prototype property
63911                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
63912                     if (!isTypeAny(prototypePropertyType)) {
63913                         targetType = prototypePropertyType;
63914                     }
63915                 }
63916                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
63917                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
63918                     return type;
63919                 }
63920                 if (!targetType) {
63921                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
63922                     targetType = constructSignatures.length ?
63923                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
63924                         emptyObjectType;
63925                 }
63926                 // We can't narrow a union based off instanceof without negated types see #31576 for more info
63927                 if (!assumeTrue && rightType.flags & 1048576 /* Union */) {
63928                     var nonConstructorTypeInUnion = ts.find(rightType.types, function (t) { return !isConstructorType(t); });
63929                     if (!nonConstructorTypeInUnion)
63930                         return type;
63931                 }
63932                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
63933             }
63934             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
63935                 if (!assumeTrue) {
63936                     return filterType(type, function (t) { return !isRelated(t, candidate); });
63937                 }
63938                 // If the current type is a union type, remove all constituents that couldn't be instances of
63939                 // the candidate type. If one or more constituents remain, return a union of those.
63940                 if (type.flags & 1048576 /* Union */) {
63941                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
63942                     if (!(assignableType.flags & 131072 /* Never */)) {
63943                         return assignableType;
63944                     }
63945                 }
63946                 // If the candidate type is a subtype of the target type, narrow to the candidate type,
63947                 // if the target type is a subtype of the candidate type, narrow to the target type,
63948                 // otherwise, narrow to an intersection of the two types.
63949                 return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]);
63950             }
63951             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
63952                 if (hasMatchingArgument(callExpression, reference)) {
63953                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
63954                     var predicate = signature && getTypePredicateOfSignature(signature);
63955                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
63956                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
63957                     }
63958                 }
63959                 return type;
63960             }
63961             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
63962                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
63963                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
63964                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
63965                     if (predicateArgument) {
63966                         if (isMatchingReference(reference, predicateArgument)) {
63967                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
63968                         }
63969                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
63970                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
63971                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
63972                         }
63973                         if (isMatchingReferenceDiscriminant(predicateArgument, type)) {
63974                             return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
63975                         }
63976                     }
63977                 }
63978                 return type;
63979             }
63980             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
63981             // will be a subtype or the same type as the argument.
63982             function narrowType(type, expr, assumeTrue) {
63983                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
63984                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
63985                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
63986                     return narrowTypeByOptionality(type, expr, assumeTrue);
63987                 }
63988                 switch (expr.kind) {
63989                     case 78 /* Identifier */:
63990                     case 107 /* ThisKeyword */:
63991                     case 105 /* SuperKeyword */:
63992                     case 201 /* PropertyAccessExpression */:
63993                     case 202 /* ElementAccessExpression */:
63994                         return narrowTypeByTruthiness(type, expr, assumeTrue);
63995                     case 203 /* CallExpression */:
63996                         return narrowTypeByCallExpression(type, expr, assumeTrue);
63997                     case 207 /* ParenthesizedExpression */:
63998                     case 225 /* NonNullExpression */:
63999                         return narrowType(type, expr.expression, assumeTrue);
64000                     case 216 /* BinaryExpression */:
64001                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
64002                     case 214 /* PrefixUnaryExpression */:
64003                         if (expr.operator === 53 /* ExclamationToken */) {
64004                             return narrowType(type, expr.operand, !assumeTrue);
64005                         }
64006                         break;
64007                 }
64008                 return type;
64009             }
64010             function narrowTypeByOptionality(type, expr, assumePresent) {
64011                 if (isMatchingReference(reference, expr)) {
64012                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
64013                 }
64014                 if (isMatchingReferenceDiscriminant(expr, type)) {
64015                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
64016                 }
64017                 return type;
64018             }
64019         }
64020         function getTypeOfSymbolAtLocation(symbol, location) {
64021             symbol = symbol.exportSymbol || symbol;
64022             // If we have an identifier or a property access at the given location, if the location is
64023             // an dotted name expression, and if the location is not an assignment target, obtain the type
64024             // of the expression (which will reflect control flow analysis). If the expression indeed
64025             // resolved to the given symbol, return the narrowed type.
64026             if (location.kind === 78 /* Identifier */) {
64027                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
64028                     location = location.parent;
64029                 }
64030                 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
64031                     var type = getTypeOfExpression(location);
64032                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
64033                         return type;
64034                     }
64035                 }
64036             }
64037             // The location isn't a reference to the given symbol, meaning we're being asked
64038             // a hypothetical question of what type the symbol would have if there was a reference
64039             // to it at the given location. Since we have no control flow information for the
64040             // hypothetical reference (control flow information is created and attached by the
64041             // binder), we simply return the declared type of the symbol.
64042             return getTypeOfSymbol(symbol);
64043         }
64044         function getControlFlowContainer(node) {
64045             return ts.findAncestor(node.parent, function (node) {
64046                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
64047                     node.kind === 257 /* ModuleBlock */ ||
64048                     node.kind === 297 /* SourceFile */ ||
64049                     node.kind === 163 /* PropertyDeclaration */;
64050             });
64051         }
64052         // Check if a parameter is assigned anywhere within its declaring function.
64053         function isParameterAssigned(symbol) {
64054             var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
64055             var links = getNodeLinks(func);
64056             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
64057                 links.flags |= 8388608 /* AssignmentsMarked */;
64058                 if (!hasParentWithAssignmentsMarked(func)) {
64059                     markParameterAssignments(func);
64060                 }
64061             }
64062             return symbol.isAssigned || false;
64063         }
64064         function hasParentWithAssignmentsMarked(node) {
64065             return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
64066         }
64067         function markParameterAssignments(node) {
64068             if (node.kind === 78 /* Identifier */) {
64069                 if (ts.isAssignmentTarget(node)) {
64070                     var symbol = getResolvedSymbol(node);
64071                     if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 160 /* Parameter */) {
64072                         symbol.isAssigned = true;
64073                     }
64074                 }
64075             }
64076             else {
64077                 ts.forEachChild(node, markParameterAssignments);
64078             }
64079         }
64080         function isConstVariable(symbol) {
64081             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
64082         }
64083         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
64084         function removeOptionalityFromDeclaredType(declaredType, declaration) {
64085             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
64086                 var annotationIncludesUndefined = strictNullChecks &&
64087                     declaration.kind === 160 /* Parameter */ &&
64088                     declaration.initializer &&
64089                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
64090                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
64091                 popTypeResolution();
64092                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
64093             }
64094             else {
64095                 reportCircularityError(declaration.symbol);
64096                 return declaredType;
64097             }
64098         }
64099         function isConstraintPosition(node) {
64100             var parent = node.parent;
64101             return parent.kind === 201 /* PropertyAccessExpression */ ||
64102                 parent.kind === 203 /* CallExpression */ && parent.expression === node ||
64103                 parent.kind === 202 /* ElementAccessExpression */ && parent.expression === node ||
64104                 parent.kind === 198 /* BindingElement */ && parent.name === node && !!parent.initializer;
64105         }
64106         function typeHasNullableConstraint(type) {
64107             return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
64108         }
64109         function getConstraintForLocation(type, node) {
64110             // When a node is the left hand expression of a property access, element access, or call expression,
64111             // and the type of the node includes type variables with constraints that are nullable, we fetch the
64112             // apparent type of the node *before* performing control flow analysis such that narrowings apply to
64113             // the constraint type.
64114             if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
64115                 return mapType(getWidenedType(type), getBaseConstraintOrType);
64116             }
64117             return type;
64118         }
64119         function isExportOrExportExpression(location) {
64120             return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
64121         }
64122         function markAliasReferenced(symbol, location) {
64123             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
64124                 if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
64125                     markAliasSymbolAsReferenced(symbol);
64126                 }
64127                 else {
64128                     markConstEnumAliasAsReferenced(symbol);
64129                 }
64130             }
64131         }
64132         function checkIdentifier(node) {
64133             var symbol = getResolvedSymbol(node);
64134             if (symbol === unknownSymbol) {
64135                 return errorType;
64136             }
64137             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
64138             // Although in down-level emit of arrow function, we emit it using function expression which means that
64139             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
64140             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
64141             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
64142             // can explicitly bound arguments objects
64143             if (symbol === argumentsSymbol) {
64144                 var container = ts.getContainingFunction(node);
64145                 if (languageVersion < 2 /* ES2015 */) {
64146                     if (container.kind === 209 /* ArrowFunction */) {
64147                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
64148                     }
64149                     else if (ts.hasSyntacticModifier(container, 256 /* Async */)) {
64150                         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);
64151                     }
64152                 }
64153                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
64154                 return getTypeOfSymbol(symbol);
64155             }
64156             // We should only mark aliases as referenced if there isn't a local value declaration
64157             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
64158             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
64159                 markAliasReferenced(symbol, node);
64160             }
64161             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
64162             var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol;
64163             if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node.parent, sourceSymbol)) {
64164                 errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText);
64165             }
64166             var declaration = localOrExportSymbol.valueDeclaration;
64167             if (localOrExportSymbol.flags & 32 /* Class */) {
64168                 // Due to the emit for class decorators, any reference to the class from inside of the class body
64169                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
64170                 // behavior of class names in ES6.
64171                 if (declaration.kind === 252 /* ClassDeclaration */
64172                     && ts.nodeIsDecorated(declaration)) {
64173                     var container = ts.getContainingClass(node);
64174                     while (container !== undefined) {
64175                         if (container === declaration && container.name !== node) {
64176                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
64177                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
64178                             break;
64179                         }
64180                         container = ts.getContainingClass(container);
64181                     }
64182                 }
64183                 else if (declaration.kind === 221 /* ClassExpression */) {
64184                     // When we emit a class expression with static members that contain a reference
64185                     // to the constructor in the initializer, we will need to substitute that
64186                     // binding with an alias as the class name is not in scope.
64187                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
64188                     while (container.kind !== 297 /* SourceFile */) {
64189                         if (container.parent === declaration) {
64190                             if (container.kind === 163 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) {
64191                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
64192                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
64193                             }
64194                             break;
64195                         }
64196                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
64197                     }
64198                 }
64199             }
64200             checkNestedBlockScopedBinding(node, symbol);
64201             var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
64202             var assignmentKind = ts.getAssignmentTargetKind(node);
64203             if (assignmentKind) {
64204                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
64205                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
64206                     error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
64207                     return errorType;
64208                 }
64209                 if (isReadonlySymbol(localOrExportSymbol)) {
64210                     if (localOrExportSymbol.flags & 3 /* Variable */) {
64211                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
64212                     }
64213                     else {
64214                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
64215                     }
64216                     return errorType;
64217                 }
64218             }
64219             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
64220             // We only narrow variables and parameters occurring in a non-assignment position. For all other
64221             // entities we simply return the declared type.
64222             if (localOrExportSymbol.flags & 3 /* Variable */) {
64223                 if (assignmentKind === 1 /* Definite */) {
64224                     return type;
64225                 }
64226             }
64227             else if (isAlias) {
64228                 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
64229             }
64230             else {
64231                 return type;
64232             }
64233             if (!declaration) {
64234                 return type;
64235             }
64236             // The declaration container is the innermost function that encloses the declaration of the variable
64237             // or parameter. The flow container is the innermost function starting with which we analyze the control
64238             // flow graph to determine the control flow based type.
64239             var isParameter = ts.getRootDeclaration(declaration).kind === 160 /* Parameter */;
64240             var declarationContainer = getControlFlowContainer(declaration);
64241             var flowContainer = getControlFlowContainer(node);
64242             var isOuterVariable = flowContainer !== declarationContainer;
64243             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
64244             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
64245             // When the control flow originates in a function expression or arrow function and we are referencing
64246             // a const variable or parameter from an outer function, we extend the origin of the control flow
64247             // analysis to include the immediately enclosing function.
64248             while (flowContainer !== declarationContainer && (flowContainer.kind === 208 /* FunctionExpression */ ||
64249                 flowContainer.kind === 209 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
64250                 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
64251                 flowContainer = getControlFlowContainer(flowContainer);
64252             }
64253             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
64254             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
64255             // declaration container are the same).
64256             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
64257                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
64258                     isInTypeQuery(node) || node.parent.kind === 270 /* ExportSpecifier */) ||
64259                 node.parent.kind === 225 /* NonNullExpression */ ||
64260                 declaration.kind === 249 /* VariableDeclaration */ && declaration.exclamationToken ||
64261                 declaration.flags & 8388608 /* Ambient */;
64262             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
64263                 type === autoType || type === autoArrayType ? undefinedType :
64264                     getOptionalType(type);
64265             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
64266             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
64267             // from declaration to use, and when the variable's declared type doesn't include undefined but the
64268             // control flow based type does include undefined.
64269             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
64270                 if (flowType === autoType || flowType === autoArrayType) {
64271                     if (noImplicitAny) {
64272                         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));
64273                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
64274                     }
64275                     return convertAutoToAny(flowType);
64276                 }
64277             }
64278             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
64279                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
64280                 // Return the declared type to reduce follow-on errors
64281                 return type;
64282             }
64283             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
64284         }
64285         function isInsideFunction(node, threshold) {
64286             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
64287         }
64288         function getPartOfForStatementContainingNode(node, container) {
64289             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
64290         }
64291         function checkNestedBlockScopedBinding(node, symbol) {
64292             if (languageVersion >= 2 /* ES2015 */ ||
64293                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
64294                 ts.isSourceFile(symbol.valueDeclaration) ||
64295                 symbol.valueDeclaration.parent.kind === 287 /* CatchClause */) {
64296                 return;
64297             }
64298             // 1. walk from the use site up to the declaration and check
64299             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
64300             // 2. walk from the declaration up to the boundary of lexical environment and check
64301             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
64302             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
64303             var usedInFunction = isInsideFunction(node.parent, container);
64304             var current = container;
64305             var containedInIterationStatement = false;
64306             while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
64307                 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
64308                     containedInIterationStatement = true;
64309                     break;
64310                 }
64311                 current = current.parent;
64312             }
64313             if (containedInIterationStatement) {
64314                 if (usedInFunction) {
64315                     // mark iteration statement as containing block-scoped binding captured in some function
64316                     var capturesBlockScopeBindingInLoopBody = true;
64317                     if (ts.isForStatement(container)) {
64318                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */);
64319                         if (varDeclList && varDeclList.parent === container) {
64320                             var part = getPartOfForStatementContainingNode(node.parent, container);
64321                             if (part) {
64322                                 var links = getNodeLinks(part);
64323                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
64324                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
64325                                 ts.pushIfUnique(capturedBindings, symbol);
64326                                 if (part === container.initializer) {
64327                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
64328                                 }
64329                             }
64330                         }
64331                     }
64332                     if (capturesBlockScopeBindingInLoopBody) {
64333                         getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
64334                     }
64335                 }
64336                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
64337                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
64338                 if (ts.isForStatement(container)) {
64339                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */);
64340                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
64341                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
64342                     }
64343                 }
64344                 // set 'declared inside loop' bit on the block-scoped binding
64345                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
64346             }
64347             if (usedInFunction) {
64348                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
64349             }
64350         }
64351         function isBindingCapturedByNode(node, decl) {
64352             var links = getNodeLinks(node);
64353             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
64354         }
64355         function isAssignedInBodyOfForStatement(node, container) {
64356             // skip parenthesized nodes
64357             var current = node;
64358             while (current.parent.kind === 207 /* ParenthesizedExpression */) {
64359                 current = current.parent;
64360             }
64361             // check if node is used as LHS in some assignment expression
64362             var isAssigned = false;
64363             if (ts.isAssignmentTarget(current)) {
64364                 isAssigned = true;
64365             }
64366             else if ((current.parent.kind === 214 /* PrefixUnaryExpression */ || current.parent.kind === 215 /* PostfixUnaryExpression */)) {
64367                 var expr = current.parent;
64368                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
64369             }
64370             if (!isAssigned) {
64371                 return false;
64372             }
64373             // at this point we know that node is the target of assignment
64374             // now check that modification happens inside the statement part of the ForStatement
64375             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
64376         }
64377         function captureLexicalThis(node, container) {
64378             getNodeLinks(node).flags |= 2 /* LexicalThis */;
64379             if (container.kind === 163 /* PropertyDeclaration */ || container.kind === 166 /* Constructor */) {
64380                 var classNode = container.parent;
64381                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
64382             }
64383             else {
64384                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
64385             }
64386         }
64387         function findFirstSuperCall(node) {
64388             return ts.isSuperCall(node) ? node :
64389                 ts.isFunctionLike(node) ? undefined :
64390                     ts.forEachChild(node, findFirstSuperCall);
64391         }
64392         /**
64393          * Check if the given class-declaration extends null then return true.
64394          * Otherwise, return false
64395          * @param classDecl a class declaration to check if it extends null
64396          */
64397         function classDeclarationExtendsNull(classDecl) {
64398             var classSymbol = getSymbolOfNode(classDecl);
64399             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
64400             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
64401             return baseConstructorType === nullWideningType;
64402         }
64403         function checkThisBeforeSuper(node, container, diagnosticMessage) {
64404             var containingClassDecl = container.parent;
64405             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
64406             // If a containing class does not have extends clause or the class extends null
64407             // skip checking whether super statement is called before "this" accessing.
64408             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
64409                 if (node.flowNode && !isPostSuperFlowNode(node.flowNode, /*noCacheCheck*/ false)) {
64410                     error(node, diagnosticMessage);
64411                 }
64412             }
64413         }
64414         function checkThisExpression(node) {
64415             // Stop at the first arrow function so that we can
64416             // tell whether 'this' needs to be captured.
64417             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
64418             var capturedByArrowFunction = false;
64419             if (container.kind === 166 /* Constructor */) {
64420                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
64421             }
64422             // Now skip arrow functions to get the "real" owner of 'this'.
64423             if (container.kind === 209 /* ArrowFunction */) {
64424                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
64425                 capturedByArrowFunction = true;
64426             }
64427             switch (container.kind) {
64428                 case 256 /* ModuleDeclaration */:
64429                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
64430                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
64431                     break;
64432                 case 255 /* EnumDeclaration */:
64433                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
64434                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
64435                     break;
64436                 case 166 /* Constructor */:
64437                     if (isInConstructorArgumentInitializer(node, container)) {
64438                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
64439                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
64440                     }
64441                     break;
64442                 case 163 /* PropertyDeclaration */:
64443                 case 162 /* PropertySignature */:
64444                     if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
64445                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
64446                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
64447                     }
64448                     break;
64449                 case 158 /* ComputedPropertyName */:
64450                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
64451                     break;
64452             }
64453             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
64454             if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
64455                 captureLexicalThis(node, container);
64456             }
64457             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
64458             if (noImplicitThis) {
64459                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
64460                 if (type === globalThisType_1 && capturedByArrowFunction) {
64461                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
64462                 }
64463                 else if (!type) {
64464                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
64465                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
64466                     if (!ts.isSourceFile(container)) {
64467                         var outsideThis = tryGetThisTypeAt(container);
64468                         if (outsideThis && outsideThis !== globalThisType_1) {
64469                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
64470                         }
64471                     }
64472                 }
64473             }
64474             return type || anyType;
64475         }
64476         function tryGetThisTypeAt(node, includeGlobalThis, container) {
64477             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
64478             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
64479             var isInJS = ts.isInJSFile(node);
64480             if (ts.isFunctionLike(container) &&
64481                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
64482                 var thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container);
64483                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
64484                 // If this is a function in a JS file, it might be a class method.
64485                 if (!thisType) {
64486                     var className = getClassNameFromPrototypeMethod(container);
64487                     if (isInJS && className) {
64488                         var classSymbol = checkExpression(className).symbol;
64489                         if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
64490                             thisType = getDeclaredTypeOfSymbol(classSymbol).thisType;
64491                         }
64492                     }
64493                     else if (isJSConstructor(container)) {
64494                         thisType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
64495                     }
64496                     thisType || (thisType = getContextualThisParameterType(container));
64497                 }
64498                 if (thisType) {
64499                     return getFlowTypeOfReference(node, thisType);
64500                 }
64501             }
64502             if (ts.isClassLike(container.parent)) {
64503                 var symbol = getSymbolOfNode(container.parent);
64504                 var type = ts.hasSyntacticModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
64505                 return getFlowTypeOfReference(node, type);
64506             }
64507             if (ts.isSourceFile(container)) {
64508                 // look up in the source file's locals or exports
64509                 if (container.commonJsModuleIndicator) {
64510                     var fileSymbol = getSymbolOfNode(container);
64511                     return fileSymbol && getTypeOfSymbol(fileSymbol);
64512                 }
64513                 else if (container.externalModuleIndicator) {
64514                     // TODO: Maybe issue a better error than 'object is possibly undefined'
64515                     return undefinedType;
64516                 }
64517                 else if (includeGlobalThis) {
64518                     return getTypeOfSymbol(globalThisSymbol);
64519                 }
64520             }
64521         }
64522         function getExplicitThisType(node) {
64523             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
64524             if (ts.isFunctionLike(container)) {
64525                 var signature = getSignatureFromDeclaration(container);
64526                 if (signature.thisParameter) {
64527                     return getExplicitTypeOfSymbol(signature.thisParameter);
64528                 }
64529             }
64530             if (ts.isClassLike(container.parent)) {
64531                 var symbol = getSymbolOfNode(container.parent);
64532                 return ts.hasSyntacticModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
64533             }
64534         }
64535         function getClassNameFromPrototypeMethod(container) {
64536             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
64537             if (container.kind === 208 /* FunctionExpression */ &&
64538                 ts.isBinaryExpression(container.parent) &&
64539                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
64540                 // Get the 'x' of 'x.prototype.y = container'
64541                 return container.parent // x.prototype.y = container
64542                     .left // x.prototype.y
64543                     .expression // x.prototype
64544                     .expression; // x
64545             }
64546             // x.prototype = { method() { } }
64547             else if (container.kind === 165 /* MethodDeclaration */ &&
64548                 container.parent.kind === 200 /* ObjectLiteralExpression */ &&
64549                 ts.isBinaryExpression(container.parent.parent) &&
64550                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
64551                 return container.parent.parent.left.expression;
64552             }
64553             // x.prototype = { method: function() { } }
64554             else if (container.kind === 208 /* FunctionExpression */ &&
64555                 container.parent.kind === 288 /* PropertyAssignment */ &&
64556                 container.parent.parent.kind === 200 /* ObjectLiteralExpression */ &&
64557                 ts.isBinaryExpression(container.parent.parent.parent) &&
64558                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
64559                 return container.parent.parent.parent.left.expression;
64560             }
64561             // Object.defineProperty(x, "method", { value: function() { } });
64562             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
64563             // Object.defineProperty(x, "method", { get: () => function() { }) });
64564             else if (container.kind === 208 /* FunctionExpression */ &&
64565                 ts.isPropertyAssignment(container.parent) &&
64566                 ts.isIdentifier(container.parent.name) &&
64567                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
64568                 ts.isObjectLiteralExpression(container.parent.parent) &&
64569                 ts.isCallExpression(container.parent.parent.parent) &&
64570                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
64571                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
64572                 return container.parent.parent.parent.arguments[0].expression;
64573             }
64574             // Object.defineProperty(x, "method", { value() { } });
64575             // Object.defineProperty(x, "method", { set(x: () => void) {} });
64576             // Object.defineProperty(x, "method", { get() { return () => {} } });
64577             else if (ts.isMethodDeclaration(container) &&
64578                 ts.isIdentifier(container.name) &&
64579                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
64580                 ts.isObjectLiteralExpression(container.parent) &&
64581                 ts.isCallExpression(container.parent.parent) &&
64582                 container.parent.parent.arguments[2] === container.parent &&
64583                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
64584                 return container.parent.parent.arguments[0].expression;
64585             }
64586         }
64587         function getTypeForThisExpressionFromJSDoc(node) {
64588             var jsdocType = ts.getJSDocType(node);
64589             if (jsdocType && jsdocType.kind === 308 /* JSDocFunctionType */) {
64590                 var jsDocFunctionType = jsdocType;
64591                 if (jsDocFunctionType.parameters.length > 0 &&
64592                     jsDocFunctionType.parameters[0].name &&
64593                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
64594                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
64595                 }
64596             }
64597             var thisTag = ts.getJSDocThisTag(node);
64598             if (thisTag && thisTag.typeExpression) {
64599                 return getTypeFromTypeNode(thisTag.typeExpression);
64600             }
64601         }
64602         function isInConstructorArgumentInitializer(node, constructorDecl) {
64603             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 160 /* Parameter */ && n.parent === constructorDecl; });
64604         }
64605         function checkSuperExpression(node) {
64606             var isCallExpression = node.parent.kind === 203 /* CallExpression */ && node.parent.expression === node;
64607             var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
64608             var container = immediateContainer;
64609             var needToCaptureLexicalThis = false;
64610             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
64611             if (!isCallExpression) {
64612                 while (container && container.kind === 209 /* ArrowFunction */) {
64613                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
64614                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
64615                 }
64616             }
64617             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
64618             var nodeCheckFlag = 0;
64619             if (!canUseSuperExpression) {
64620                 // issue more specific error if super is used in computed property name
64621                 // class A { foo() { return "1" }}
64622                 // class B {
64623                 //     [super.foo()]() {}
64624                 // }
64625                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 158 /* ComputedPropertyName */; });
64626                 if (current && current.kind === 158 /* ComputedPropertyName */) {
64627                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
64628                 }
64629                 else if (isCallExpression) {
64630                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
64631                 }
64632                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */)) {
64633                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
64634                 }
64635                 else {
64636                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
64637                 }
64638                 return errorType;
64639             }
64640             if (!isCallExpression && immediateContainer.kind === 166 /* Constructor */) {
64641                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
64642             }
64643             if (ts.hasSyntacticModifier(container, 32 /* Static */) || isCallExpression) {
64644                 nodeCheckFlag = 512 /* SuperStatic */;
64645             }
64646             else {
64647                 nodeCheckFlag = 256 /* SuperInstance */;
64648             }
64649             getNodeLinks(node).flags |= nodeCheckFlag;
64650             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
64651             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
64652             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
64653             // uses an arrow function, which is permitted to reference `super`.
64654             //
64655             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
64656             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
64657             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
64658             //
64659             // The simplest case is reading a value, in which case we will emit something like the following:
64660             //
64661             //  // ts
64662             //  ...
64663             //  async asyncMethod() {
64664             //    let x = await super.asyncMethod();
64665             //    return x;
64666             //  }
64667             //  ...
64668             //
64669             //  // js
64670             //  ...
64671             //  asyncMethod() {
64672             //      const _super = Object.create(null, {
64673             //        asyncMethod: { get: () => super.asyncMethod },
64674             //      });
64675             //      return __awaiter(this, arguments, Promise, function *() {
64676             //          let x = yield _super.asyncMethod.call(this);
64677             //          return x;
64678             //      });
64679             //  }
64680             //  ...
64681             //
64682             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
64683             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
64684             //
64685             //  // ts
64686             //  ...
64687             //  async asyncMethod(ar: Promise<any[]>) {
64688             //      [super.a, super.b] = await ar;
64689             //  }
64690             //  ...
64691             //
64692             //  // js
64693             //  ...
64694             //  asyncMethod(ar) {
64695             //      const _super = Object.create(null, {
64696             //        a: { get: () => super.a, set: (v) => super.a = v },
64697             //        b: { get: () => super.b, set: (v) => super.b = v }
64698             //      };
64699             //      return __awaiter(this, arguments, Promise, function *() {
64700             //          [_super.a, _super.b] = yield ar;
64701             //      });
64702             //  }
64703             //  ...
64704             //
64705             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
64706             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
64707             //
64708             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
64709             if (container.kind === 165 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) {
64710                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
64711                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
64712                 }
64713                 else {
64714                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
64715                 }
64716             }
64717             if (needToCaptureLexicalThis) {
64718                 // call expressions are allowed only in constructors so they should always capture correct 'this'
64719                 // super property access expressions can also appear in arrow functions -
64720                 // in this case they should also use correct lexical this
64721                 captureLexicalThis(node.parent, container);
64722             }
64723             if (container.parent.kind === 200 /* ObjectLiteralExpression */) {
64724                 if (languageVersion < 2 /* ES2015 */) {
64725                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
64726                     return errorType;
64727                 }
64728                 else {
64729                     // for object literal assume that type of 'super' is 'any'
64730                     return anyType;
64731                 }
64732             }
64733             // at this point the only legal case for parent is ClassLikeDeclaration
64734             var classLikeDeclaration = container.parent;
64735             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
64736                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
64737                 return errorType;
64738             }
64739             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
64740             var baseClassType = classType && getBaseTypes(classType)[0];
64741             if (!baseClassType) {
64742                 return errorType;
64743             }
64744             if (container.kind === 166 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
64745                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
64746                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
64747                 return errorType;
64748             }
64749             return nodeCheckFlag === 512 /* SuperStatic */
64750                 ? getBaseConstructorTypeOfClass(classType)
64751                 : getTypeWithThisArgument(baseClassType, classType.thisType);
64752             function isLegalUsageOfSuperExpression(container) {
64753                 if (!container) {
64754                     return false;
64755                 }
64756                 if (isCallExpression) {
64757                     // TS 1.0 SPEC (April 2014): 4.8.1
64758                     // Super calls are only permitted in constructors of derived classes
64759                     return container.kind === 166 /* Constructor */;
64760                 }
64761                 else {
64762                     // TS 1.0 SPEC (April 2014)
64763                     // 'super' property access is allowed
64764                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
64765                     // - In a static member function or static member accessor
64766                     // topmost container must be something that is directly nested in the class declaration\object literal expression
64767                     if (ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */) {
64768                         if (ts.hasSyntacticModifier(container, 32 /* Static */)) {
64769                             return container.kind === 165 /* MethodDeclaration */ ||
64770                                 container.kind === 164 /* MethodSignature */ ||
64771                                 container.kind === 167 /* GetAccessor */ ||
64772                                 container.kind === 168 /* SetAccessor */;
64773                         }
64774                         else {
64775                             return container.kind === 165 /* MethodDeclaration */ ||
64776                                 container.kind === 164 /* MethodSignature */ ||
64777                                 container.kind === 167 /* GetAccessor */ ||
64778                                 container.kind === 168 /* SetAccessor */ ||
64779                                 container.kind === 163 /* PropertyDeclaration */ ||
64780                                 container.kind === 162 /* PropertySignature */ ||
64781                                 container.kind === 166 /* Constructor */;
64782                         }
64783                     }
64784                 }
64785                 return false;
64786             }
64787         }
64788         function getContainingObjectLiteral(func) {
64789             return (func.kind === 165 /* MethodDeclaration */ ||
64790                 func.kind === 167 /* GetAccessor */ ||
64791                 func.kind === 168 /* SetAccessor */) && func.parent.kind === 200 /* ObjectLiteralExpression */ ? func.parent :
64792                 func.kind === 208 /* FunctionExpression */ && func.parent.kind === 288 /* PropertyAssignment */ ? func.parent.parent :
64793                     undefined;
64794         }
64795         function getThisTypeArgument(type) {
64796             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
64797         }
64798         function getThisTypeFromContextualType(type) {
64799             return mapType(type, function (t) {
64800                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
64801             });
64802         }
64803         function getContextualThisParameterType(func) {
64804             if (func.kind === 209 /* ArrowFunction */) {
64805                 return undefined;
64806             }
64807             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
64808                 var contextualSignature = getContextualSignature(func);
64809                 if (contextualSignature) {
64810                     var thisParameter = contextualSignature.thisParameter;
64811                     if (thisParameter) {
64812                         return getTypeOfSymbol(thisParameter);
64813                     }
64814                 }
64815             }
64816             var inJs = ts.isInJSFile(func);
64817             if (noImplicitThis || inJs) {
64818                 var containingLiteral = getContainingObjectLiteral(func);
64819                 if (containingLiteral) {
64820                     // We have an object literal method. Check if the containing object literal has a contextual type
64821                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
64822                     // any directly enclosing object literals.
64823                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
64824                     var literal = containingLiteral;
64825                     var type = contextualType;
64826                     while (type) {
64827                         var thisType = getThisTypeFromContextualType(type);
64828                         if (thisType) {
64829                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
64830                         }
64831                         if (literal.parent.kind !== 288 /* PropertyAssignment */) {
64832                             break;
64833                         }
64834                         literal = literal.parent.parent;
64835                         type = getApparentTypeOfContextualType(literal);
64836                     }
64837                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
64838                     // for 'this' is the non-null form of the contextual type for the containing object literal or
64839                     // the type of the object literal itself.
64840                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
64841                 }
64842                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
64843                 // contextual type for 'this' is 'obj'.
64844                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
64845                 if (parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
64846                     var target = parent.left;
64847                     if (ts.isAccessExpression(target)) {
64848                         var expression = target.expression;
64849                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
64850                         if (inJs && ts.isIdentifier(expression)) {
64851                             var sourceFile = ts.getSourceFileOfNode(parent);
64852                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
64853                                 return undefined;
64854                             }
64855                         }
64856                         return getWidenedType(checkExpressionCached(expression));
64857                     }
64858                 }
64859             }
64860             return undefined;
64861         }
64862         // Return contextual type of parameter or undefined if no contextual type is available
64863         function getContextuallyTypedParameterType(parameter) {
64864             var func = parameter.parent;
64865             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
64866                 return undefined;
64867             }
64868             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
64869             if (iife && iife.arguments) {
64870                 var args = getEffectiveCallArguments(iife);
64871                 var indexOfParameter = func.parameters.indexOf(parameter);
64872                 if (parameter.dotDotDotToken) {
64873                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined, 0 /* Normal */);
64874                 }
64875                 var links = getNodeLinks(iife);
64876                 var cached = links.resolvedSignature;
64877                 links.resolvedSignature = anySignature;
64878                 var type = indexOfParameter < args.length ?
64879                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
64880                     parameter.initializer ? undefined : undefinedWideningType;
64881                 links.resolvedSignature = cached;
64882                 return type;
64883             }
64884             var contextualSignature = getContextualSignature(func);
64885             if (contextualSignature) {
64886                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
64887                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
64888                     getRestTypeAtPosition(contextualSignature, index) :
64889                     tryGetTypeAtPosition(contextualSignature, index);
64890             }
64891         }
64892         function getContextualTypeForVariableLikeDeclaration(declaration) {
64893             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
64894             if (typeNode) {
64895                 return getTypeFromTypeNode(typeNode);
64896             }
64897             switch (declaration.kind) {
64898                 case 160 /* Parameter */:
64899                     return getContextuallyTypedParameterType(declaration);
64900                 case 198 /* BindingElement */:
64901                     return getContextualTypeForBindingElement(declaration);
64902                 case 163 /* PropertyDeclaration */:
64903                     if (ts.hasSyntacticModifier(declaration, 32 /* Static */)) {
64904                         return getContextualTypeForStaticPropertyDeclaration(declaration);
64905                     }
64906                 // By default, do nothing and return undefined - only the above cases have context implied by a parent
64907             }
64908         }
64909         function getContextualTypeForBindingElement(declaration) {
64910             var parent = declaration.parent.parent;
64911             var name = declaration.propertyName || declaration.name;
64912             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
64913                 parent.kind !== 198 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
64914             if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name))
64915                 return undefined;
64916             if (parent.name.kind === 197 /* ArrayBindingPattern */) {
64917                 var index = ts.indexOfNode(declaration.parent.elements, declaration);
64918                 if (index < 0)
64919                     return undefined;
64920                 return getContextualTypeForElementExpression(parentType, index);
64921             }
64922             var nameType = getLiteralTypeFromPropertyName(name);
64923             if (isTypeUsableAsPropertyName(nameType)) {
64924                 var text = getPropertyNameFromType(nameType);
64925                 return getTypeOfPropertyOfType(parentType, text);
64926             }
64927         }
64928         function getContextualTypeForStaticPropertyDeclaration(declaration) {
64929             var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent);
64930             if (!parentType)
64931                 return undefined;
64932             return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName);
64933         }
64934         // In a variable, parameter or property declaration with a type annotation,
64935         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
64936         // Otherwise, in a parameter declaration of a contextually typed function expression,
64937         //   the contextual type of an initializer expression is the contextual type of the parameter.
64938         // Otherwise, in a variable or parameter declaration with a binding pattern name,
64939         //   the contextual type of an initializer expression is the type implied by the binding pattern.
64940         // Otherwise, in a binding pattern inside a variable or parameter declaration,
64941         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
64942         function getContextualTypeForInitializerExpression(node, contextFlags) {
64943             var declaration = node.parent;
64944             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
64945                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
64946                 if (result) {
64947                     return result;
64948                 }
64949                 if (!(contextFlags & 8 /* SkipBindingPatterns */) && ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
64950                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
64951                 }
64952             }
64953             return undefined;
64954         }
64955         function getContextualTypeForReturnExpression(node) {
64956             var func = ts.getContainingFunction(node);
64957             if (func) {
64958                 var contextualReturnType = getContextualReturnType(func);
64959                 if (contextualReturnType) {
64960                     var functionFlags = ts.getFunctionFlags(func);
64961                     if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
64962                         var use = functionFlags & 2 /* Async */ ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
64963                         var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined);
64964                         if (!iterationTypes) {
64965                             return undefined;
64966                         }
64967                         contextualReturnType = iterationTypes.returnType;
64968                         // falls through to unwrap Promise for AsyncGenerators
64969                     }
64970                     if (functionFlags & 2 /* Async */) { // Async function or AsyncGenerator function
64971                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedType);
64972                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
64973                     }
64974                     return contextualReturnType; // Regular function or Generator function
64975                 }
64976             }
64977             return undefined;
64978         }
64979         function getContextualTypeForAwaitOperand(node, contextFlags) {
64980             var contextualType = getContextualType(node, contextFlags);
64981             if (contextualType) {
64982                 var contextualAwaitedType = getAwaitedType(contextualType);
64983                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
64984             }
64985             return undefined;
64986         }
64987         function getContextualTypeForYieldOperand(node) {
64988             var func = ts.getContainingFunction(node);
64989             if (func) {
64990                 var functionFlags = ts.getFunctionFlags(func);
64991                 var contextualReturnType = getContextualReturnType(func);
64992                 if (contextualReturnType) {
64993                     return node.asteriskToken
64994                         ? contextualReturnType
64995                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
64996                 }
64997             }
64998             return undefined;
64999         }
65000         function isInParameterInitializerBeforeContainingFunction(node) {
65001             var inBindingInitializer = false;
65002             while (node.parent && !ts.isFunctionLike(node.parent)) {
65003                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
65004                     return true;
65005                 }
65006                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
65007                     inBindingInitializer = true;
65008                 }
65009                 node = node.parent;
65010             }
65011             return false;
65012         }
65013         function getContextualIterationType(kind, functionDecl) {
65014             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
65015             var contextualReturnType = getContextualReturnType(functionDecl);
65016             if (contextualReturnType) {
65017                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
65018                     || undefined;
65019             }
65020             return undefined;
65021         }
65022         function getContextualReturnType(functionDecl) {
65023             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
65024             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
65025             var returnType = getReturnTypeFromAnnotation(functionDecl);
65026             if (returnType) {
65027                 return returnType;
65028             }
65029             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
65030             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
65031             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
65032             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
65033                 return getReturnTypeOfSignature(signature);
65034             }
65035             return undefined;
65036         }
65037         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
65038         function getContextualTypeForArgument(callTarget, arg) {
65039             var args = getEffectiveCallArguments(callTarget);
65040             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
65041             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
65042         }
65043         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
65044             // If we're already in the process of resolving the given signature, don't resolve again as
65045             // that could cause infinite recursion. Instead, return anySignature.
65046             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
65047             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
65048                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
65049             }
65050             return getTypeAtPosition(signature, argIndex);
65051         }
65052         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
65053             if (template.parent.kind === 205 /* TaggedTemplateExpression */) {
65054                 return getContextualTypeForArgument(template.parent, substitutionExpression);
65055             }
65056             return undefined;
65057         }
65058         function getContextualTypeForBinaryOperand(node, contextFlags) {
65059             var binaryExpression = node.parent;
65060             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
65061             switch (operatorToken.kind) {
65062                 case 62 /* EqualsToken */:
65063                 case 75 /* AmpersandAmpersandEqualsToken */:
65064                 case 74 /* BarBarEqualsToken */:
65065                 case 76 /* QuestionQuestionEqualsToken */:
65066                     return node === right ? getContextualTypeForAssignmentDeclaration(binaryExpression) : undefined;
65067                 case 56 /* BarBarToken */:
65068                 case 60 /* QuestionQuestionToken */:
65069                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
65070                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
65071                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
65072                     // by the type of the left operand, except for the special case of Javascript declarations of the form
65073                     // `namespace.prop = namespace.prop || {}`.
65074                     var type = getContextualType(binaryExpression, contextFlags);
65075                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
65076                         getTypeOfExpression(left) : type;
65077                 case 55 /* AmpersandAmpersandToken */:
65078                 case 27 /* CommaToken */:
65079                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
65080                 default:
65081                     return undefined;
65082             }
65083         }
65084         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
65085         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
65086         function getContextualTypeForAssignmentDeclaration(binaryExpression) {
65087             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
65088             switch (kind) {
65089                 case 0 /* None */:
65090                     return getTypeOfExpression(binaryExpression.left);
65091                 case 5 /* Property */:
65092                 case 1 /* ExportsProperty */:
65093                 case 6 /* Prototype */:
65094                 case 3 /* PrototypeProperty */:
65095                     if (isPossiblyAliasedThisProperty(binaryExpression, kind)) {
65096                         return getContextualTypeForThisPropertyAssignment(binaryExpression, kind);
65097                     }
65098                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
65099                     // See `bindStaticPropertyAssignment` in `binder.ts`.
65100                     else if (!binaryExpression.left.symbol) {
65101                         return getTypeOfExpression(binaryExpression.left);
65102                     }
65103                     else {
65104                         var decl = binaryExpression.left.symbol.valueDeclaration;
65105                         if (!decl) {
65106                             return undefined;
65107                         }
65108                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
65109                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
65110                         if (overallAnnotation) {
65111                             return getTypeFromTypeNode(overallAnnotation);
65112                         }
65113                         else if (ts.isIdentifier(lhs.expression)) {
65114                             var id = lhs.expression;
65115                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
65116                             if (parentSymbol) {
65117                                 var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
65118                                 if (annotated) {
65119                                     var nameStr = ts.getElementOrPropertyAccessName(lhs);
65120                                     if (nameStr !== undefined) {
65121                                         return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr);
65122                                     }
65123                                 }
65124                                 return undefined;
65125                             }
65126                         }
65127                         return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left);
65128                     }
65129                 case 2 /* ModuleExports */:
65130                 case 4 /* ThisProperty */:
65131                     return getContextualTypeForThisPropertyAssignment(binaryExpression, kind);
65132                 case 7 /* ObjectDefinePropertyValue */:
65133                 case 8 /* ObjectDefinePropertyExports */:
65134                 case 9 /* ObjectDefinePrototypeProperty */:
65135                     return ts.Debug.fail("Does not apply");
65136                 default:
65137                     return ts.Debug.assertNever(kind);
65138             }
65139         }
65140         function isPossiblyAliasedThisProperty(declaration, kind) {
65141             if (kind === void 0) { kind = ts.getAssignmentDeclarationKind(declaration); }
65142             if (kind === 4 /* ThisProperty */) {
65143                 return true;
65144             }
65145             if (!ts.isInJSFile(declaration) || kind !== 5 /* Property */ || !ts.isIdentifier(declaration.left.expression)) {
65146                 return false;
65147             }
65148             var name = declaration.left.expression.escapedText;
65149             var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true);
65150             return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration);
65151         }
65152         function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) {
65153             if (!binaryExpression.symbol)
65154                 return getTypeOfExpression(binaryExpression.left);
65155             if (binaryExpression.symbol.valueDeclaration) {
65156                 var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
65157                 if (annotated) {
65158                     var type = getTypeFromTypeNode(annotated);
65159                     if (type) {
65160                         return type;
65161                     }
65162                 }
65163             }
65164             if (kind === 2 /* ModuleExports */)
65165                 return undefined;
65166             var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
65167             if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
65168                 return undefined;
65169             }
65170             var thisType = checkThisExpression(thisAccess.expression);
65171             var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
65172             return nameStr !== undefined && getTypeOfPropertyOfContextualType(thisType, nameStr) || undefined;
65173         }
65174         function isCircularMappedProperty(symbol) {
65175             return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
65176         }
65177         function getTypeOfPropertyOfContextualType(type, name) {
65178             return mapType(type, function (t) {
65179                 if (isGenericMappedType(t)) {
65180                     var constraint = getConstraintTypeFromMappedType(t);
65181                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
65182                     var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
65183                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
65184                         return substituteIndexedMappedType(t, propertyNameType);
65185                     }
65186                 }
65187                 else if (t.flags & 3670016 /* StructuredType */) {
65188                     var prop = getPropertyOfType(t, name);
65189                     if (prop) {
65190                         return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
65191                     }
65192                     if (isTupleType(t)) {
65193                         var restType = getRestTypeOfTupleType(t);
65194                         if (restType && isNumericLiteralName(name) && +name >= 0) {
65195                             return restType;
65196                         }
65197                     }
65198                     return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
65199                         getIndexTypeOfContextualType(t, 0 /* String */);
65200                 }
65201                 return undefined;
65202             }, /*noReductions*/ true);
65203         }
65204         function getIndexTypeOfContextualType(type, kind) {
65205             return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
65206         }
65207         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
65208         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
65209         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
65210         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
65211             ts.Debug.assert(ts.isObjectLiteralMethod(node));
65212             if (node.flags & 16777216 /* InWithStatement */) {
65213                 // We cannot answer semantic questions within a with block, do not proceed any further
65214                 return undefined;
65215             }
65216             return getContextualTypeForObjectLiteralElement(node, contextFlags);
65217         }
65218         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
65219             var objectLiteral = element.parent;
65220             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
65221             if (type) {
65222                 if (!hasNonBindableDynamicName(element)) {
65223                     // For a (non-symbol) computed property, there is no reason to look up the name
65224                     // in the type. It will just be "__computed", which does not appear in any
65225                     // SymbolTable.
65226                     var symbolName_3 = getSymbolOfNode(element).escapedName;
65227                     var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
65228                     if (propertyType) {
65229                         return propertyType;
65230                     }
65231                 }
65232                 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
65233                     getIndexTypeOfContextualType(type, 0 /* String */);
65234             }
65235             return undefined;
65236         }
65237         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
65238         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
65239         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
65240         // type of T.
65241         function getContextualTypeForElementExpression(arrayContextualType, index) {
65242             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
65243                 || mapType(arrayContextualType, function (t) { return getIteratedTypeOrElementType(1 /* Element */, t, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false); }, 
65244                 /*noReductions*/ true));
65245         }
65246         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
65247         function getContextualTypeForConditionalOperand(node, contextFlags) {
65248             var conditional = node.parent;
65249             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
65250         }
65251         function getContextualTypeForChildJsxExpression(node, child) {
65252             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
65253             // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
65254             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
65255             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
65256                 return undefined;
65257             }
65258             var realChildren = ts.getSemanticJsxChildren(node.children);
65259             var childIndex = realChildren.indexOf(child);
65260             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
65261             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
65262                 if (isArrayLikeType(t)) {
65263                     return getIndexedAccessType(t, getLiteralType(childIndex));
65264                 }
65265                 else {
65266                     return t;
65267                 }
65268             }, /*noReductions*/ true));
65269         }
65270         function getContextualTypeForJsxExpression(node) {
65271             var exprParent = node.parent;
65272             return ts.isJsxAttributeLike(exprParent)
65273                 ? getContextualType(node)
65274                 : ts.isJsxElement(exprParent)
65275                     ? getContextualTypeForChildJsxExpression(exprParent, node)
65276                     : undefined;
65277         }
65278         function getContextualTypeForJsxAttribute(attribute) {
65279             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
65280             // which is a type of the parameter of the signature we are trying out.
65281             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
65282             if (ts.isJsxAttribute(attribute)) {
65283                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
65284                 if (!attributesType || isTypeAny(attributesType)) {
65285                     return undefined;
65286                 }
65287                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
65288             }
65289             else {
65290                 return getContextualType(attribute.parent);
65291             }
65292         }
65293         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
65294         // expressions we check to those that don't depend on their contextual type in order not to cause
65295         // recursive (and possibly infinite) invocations of getContextualType.
65296         function isPossiblyDiscriminantValue(node) {
65297             switch (node.kind) {
65298                 case 10 /* StringLiteral */:
65299                 case 8 /* NumericLiteral */:
65300                 case 9 /* BigIntLiteral */:
65301                 case 14 /* NoSubstitutionTemplateLiteral */:
65302                 case 109 /* TrueKeyword */:
65303                 case 94 /* FalseKeyword */:
65304                 case 103 /* NullKeyword */:
65305                 case 78 /* Identifier */:
65306                 case 150 /* UndefinedKeyword */:
65307                     return true;
65308                 case 201 /* PropertyAccessExpression */:
65309                 case 207 /* ParenthesizedExpression */:
65310                     return isPossiblyDiscriminantValue(node.expression);
65311                 case 283 /* JsxExpression */:
65312                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
65313             }
65314             return false;
65315         }
65316         function discriminateContextualTypeByObjectMembers(node, contextualType) {
65317             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 288 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
65318         }
65319         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
65320             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 280 /* 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);
65321         }
65322         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
65323         // be "pushed" onto a node using the contextualType property.
65324         function getApparentTypeOfContextualType(node, contextFlags) {
65325             var contextualType = ts.isObjectLiteralMethod(node) ?
65326                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
65327                 getContextualType(node, contextFlags);
65328             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
65329             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
65330                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
65331                 if (apparentType.flags & 1048576 /* Union */) {
65332                     if (ts.isObjectLiteralExpression(node)) {
65333                         return discriminateContextualTypeByObjectMembers(node, apparentType);
65334                     }
65335                     else if (ts.isJsxAttributes(node)) {
65336                         return discriminateContextualTypeByJSXAttributes(node, apparentType);
65337                     }
65338                 }
65339                 return apparentType;
65340             }
65341         }
65342         // If the given contextual type contains instantiable types and if a mapper representing
65343         // return type inferences is available, instantiate those types using that mapper.
65344         function instantiateContextualType(contextualType, node, contextFlags) {
65345             if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* Instantiable */)) {
65346                 var inferenceContext = getInferenceContext(node);
65347                 // If no inferences have been made, nothing is gained from instantiating as type parameters
65348                 // would just be replaced with their defaults similar to the apparent type.
65349                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
65350                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
65351                     // types as well as arguments to the left in a function call.
65352                     if (contextFlags && contextFlags & 1 /* Signature */) {
65353                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
65354                     }
65355                     // For other purposes (e.g. determining whether to produce literal types) we only
65356                     // incorporate inferences made from the return type in a function call.
65357                     if (inferenceContext.returnMapper) {
65358                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
65359                     }
65360                 }
65361             }
65362             return contextualType;
65363         }
65364         // This function is similar to instantiateType, except that (a) it only instantiates types that
65365         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
65366         // no reductions on instantiated union types.
65367         function instantiateInstantiableTypes(type, mapper) {
65368             if (type.flags & 465829888 /* Instantiable */) {
65369                 return instantiateType(type, mapper);
65370             }
65371             if (type.flags & 1048576 /* Union */) {
65372                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
65373             }
65374             if (type.flags & 2097152 /* Intersection */) {
65375                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
65376             }
65377             return type;
65378         }
65379         /**
65380          * Whoa! Do you really want to use this function?
65381          *
65382          * Unless you're trying to get the *non-apparent* type for a
65383          * value-literal type or you're authoring relevant portions of this algorithm,
65384          * you probably meant to use 'getApparentTypeOfContextualType'.
65385          * Otherwise this may not be very useful.
65386          *
65387          * In cases where you *are* working on this function, you should understand
65388          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
65389          *
65390          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
65391          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
65392          *
65393          * @param node the expression whose contextual type will be returned.
65394          * @returns the contextual type of an expression.
65395          */
65396         function getContextualType(node, contextFlags) {
65397             if (node.flags & 16777216 /* InWithStatement */) {
65398                 // We cannot answer semantic questions within a with block, do not proceed any further
65399                 return undefined;
65400             }
65401             if (node.contextualType) {
65402                 return node.contextualType;
65403             }
65404             var parent = node.parent;
65405             switch (parent.kind) {
65406                 case 249 /* VariableDeclaration */:
65407                 case 160 /* Parameter */:
65408                 case 163 /* PropertyDeclaration */:
65409                 case 162 /* PropertySignature */:
65410                 case 198 /* BindingElement */:
65411                     return getContextualTypeForInitializerExpression(node, contextFlags);
65412                 case 209 /* ArrowFunction */:
65413                 case 242 /* ReturnStatement */:
65414                     return getContextualTypeForReturnExpression(node);
65415                 case 219 /* YieldExpression */:
65416                     return getContextualTypeForYieldOperand(parent);
65417                 case 213 /* AwaitExpression */:
65418                     return getContextualTypeForAwaitOperand(parent, contextFlags);
65419                 case 203 /* CallExpression */:
65420                     if (parent.expression.kind === 99 /* ImportKeyword */) {
65421                         return stringType;
65422                     }
65423                 /* falls through */
65424                 case 204 /* NewExpression */:
65425                     return getContextualTypeForArgument(parent, node);
65426                 case 206 /* TypeAssertionExpression */:
65427                 case 224 /* AsExpression */:
65428                     return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type);
65429                 case 216 /* BinaryExpression */:
65430                     return getContextualTypeForBinaryOperand(node, contextFlags);
65431                 case 288 /* PropertyAssignment */:
65432                 case 289 /* ShorthandPropertyAssignment */:
65433                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
65434                 case 290 /* SpreadAssignment */:
65435                     return getApparentTypeOfContextualType(parent.parent, contextFlags);
65436                 case 199 /* ArrayLiteralExpression */: {
65437                     var arrayLiteral = parent;
65438                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
65439                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
65440                 }
65441                 case 217 /* ConditionalExpression */:
65442                     return getContextualTypeForConditionalOperand(node, contextFlags);
65443                 case 228 /* TemplateSpan */:
65444                     ts.Debug.assert(parent.parent.kind === 218 /* TemplateExpression */);
65445                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
65446                 case 207 /* ParenthesizedExpression */: {
65447                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
65448                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
65449                     return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
65450                 }
65451                 case 283 /* JsxExpression */:
65452                     return getContextualTypeForJsxExpression(parent);
65453                 case 280 /* JsxAttribute */:
65454                 case 282 /* JsxSpreadAttribute */:
65455                     return getContextualTypeForJsxAttribute(parent);
65456                 case 275 /* JsxOpeningElement */:
65457                 case 274 /* JsxSelfClosingElement */:
65458                     return getContextualJsxElementAttributesType(parent, contextFlags);
65459             }
65460             return undefined;
65461             function tryFindWhenConstTypeReference(node) {
65462                 if (ts.isCallLikeExpression(node.parent)) {
65463                     return getContextualTypeForArgument(node.parent, node);
65464                 }
65465                 return undefined;
65466             }
65467         }
65468         function getInferenceContext(node) {
65469             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
65470             return ancestor && ancestor.inferenceContext;
65471         }
65472         function getContextualJsxElementAttributesType(node, contextFlags) {
65473             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
65474                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
65475                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
65476                 // (as below) instead!
65477                 return node.parent.contextualType;
65478             }
65479             return getContextualTypeForArgumentAtIndex(node, 0);
65480         }
65481         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
65482             return getJsxReferenceKind(node) !== 0 /* Component */
65483                 ? getJsxPropsTypeFromCallSignature(signature, node)
65484                 : getJsxPropsTypeFromClassType(signature, node);
65485         }
65486         function getJsxPropsTypeFromCallSignature(sig, context) {
65487             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
65488             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
65489             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
65490             if (intrinsicAttribs !== errorType) {
65491                 propsType = intersectTypes(intrinsicAttribs, propsType);
65492             }
65493             return propsType;
65494         }
65495         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
65496             if (sig.unionSignatures) {
65497                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
65498                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
65499                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
65500                 // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input.
65501                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
65502                 var results = [];
65503                 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
65504                     var signature = _a[_i];
65505                     var instance = getReturnTypeOfSignature(signature);
65506                     if (isTypeAny(instance)) {
65507                         return instance;
65508                     }
65509                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
65510                     if (!propType) {
65511                         return;
65512                     }
65513                     results.push(propType);
65514                 }
65515                 return getIntersectionType(results);
65516             }
65517             var instanceType = getReturnTypeOfSignature(sig);
65518             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
65519         }
65520         function getStaticTypeOfReferencedJsxConstructor(context) {
65521             if (isJsxIntrinsicIdentifier(context.tagName)) {
65522                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
65523                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
65524                 return getOrCreateTypeFromSignature(fakeSignature);
65525             }
65526             var tagType = checkExpressionCached(context.tagName);
65527             if (tagType.flags & 128 /* StringLiteral */) {
65528                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
65529                 if (!result) {
65530                     return errorType;
65531                 }
65532                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
65533                 return getOrCreateTypeFromSignature(fakeSignature);
65534             }
65535             return tagType;
65536         }
65537         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
65538             var managedSym = getJsxLibraryManagedAttributes(ns);
65539             if (managedSym) {
65540                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
65541                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
65542                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
65543                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
65544                     return createTypeReference(declaredManagedType, args);
65545                 }
65546                 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
65547                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
65548                     return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
65549                 }
65550             }
65551             return attributesType;
65552         }
65553         function getJsxPropsTypeFromClassType(sig, context) {
65554             var ns = getJsxNamespaceAt(context);
65555             var forcedLookupLocation = getJsxElementPropertiesName(ns);
65556             var attributesType = forcedLookupLocation === undefined
65557                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
65558                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
65559                 : forcedLookupLocation === ""
65560                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
65561                     ? getReturnTypeOfSignature(sig)
65562                     // Otherwise get the type of the property on the signature return type
65563                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
65564             if (!attributesType) {
65565                 // There is no property named 'props' on this instance type
65566                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
65567                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
65568                 }
65569                 return unknownType;
65570             }
65571             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
65572             if (isTypeAny(attributesType)) {
65573                 // Props is of type 'any' or unknown
65574                 return attributesType;
65575             }
65576             else {
65577                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
65578                 var apparentAttributesType = attributesType;
65579                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
65580                 if (intrinsicClassAttribs !== errorType) {
65581                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
65582                     var hostClassType = getReturnTypeOfSignature(sig);
65583                     apparentAttributesType = intersectTypes(typeParams
65584                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
65585                         : intrinsicClassAttribs, apparentAttributesType);
65586                 }
65587                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
65588                 if (intrinsicAttribs !== errorType) {
65589                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
65590                 }
65591                 return apparentAttributesType;
65592             }
65593         }
65594         // If the given type is an object or union type with a single signature, and if that signature has at
65595         // least as many parameters as the given function, return the signature. Otherwise return undefined.
65596         function getContextualCallSignature(type, node) {
65597             var signatures = getSignaturesOfType(type, 0 /* Call */);
65598             if (signatures.length === 1) {
65599                 var signature = signatures[0];
65600                 if (!isAritySmaller(signature, node)) {
65601                     return signature;
65602                 }
65603             }
65604         }
65605         /** If the contextual signature has fewer parameters than the function expression, do not use it */
65606         function isAritySmaller(signature, target) {
65607             var targetParameterCount = 0;
65608             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
65609                 var param = target.parameters[targetParameterCount];
65610                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
65611                     break;
65612                 }
65613             }
65614             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
65615                 targetParameterCount--;
65616             }
65617             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
65618         }
65619         function isFunctionExpressionOrArrowFunction(node) {
65620             return node.kind === 208 /* FunctionExpression */ || node.kind === 209 /* ArrowFunction */;
65621         }
65622         function getContextualSignatureForFunctionLikeDeclaration(node) {
65623             // Only function expressions, arrow functions, and object literal methods are contextually typed.
65624             return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
65625                 ? getContextualSignature(node)
65626                 : undefined;
65627         }
65628         // Return the contextual signature for a given expression node. A contextual type provides a
65629         // contextual signature if it has a single call signature and if that call signature is non-generic.
65630         // If the contextual type is a union type, get the signature from each type possible and if they are
65631         // all identical ignoring their return type, the result is same signature but with return type as
65632         // union type of return types from these signatures
65633         function getContextualSignature(node) {
65634             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
65635             var typeTagSignature = getSignatureOfTypeTag(node);
65636             if (typeTagSignature) {
65637                 return typeTagSignature;
65638             }
65639             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
65640             if (!type) {
65641                 return undefined;
65642             }
65643             if (!(type.flags & 1048576 /* Union */)) {
65644                 return getContextualCallSignature(type, node);
65645             }
65646             var signatureList;
65647             var types = type.types;
65648             for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
65649                 var current = types_18[_i];
65650                 var signature = getContextualCallSignature(current, node);
65651                 if (signature) {
65652                     if (!signatureList) {
65653                         // This signature will contribute to contextual union signature
65654                         signatureList = [signature];
65655                     }
65656                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
65657                         // Signatures aren't identical, do not use
65658                         return undefined;
65659                     }
65660                     else {
65661                         // Use this signature for contextual union signature
65662                         signatureList.push(signature);
65663                     }
65664                 }
65665             }
65666             // Result is union of signatures collected (return type is union of return types of this signature set)
65667             if (signatureList) {
65668                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
65669             }
65670         }
65671         function checkSpreadExpression(node, checkMode) {
65672             if (languageVersion < 2 /* ES2015 */) {
65673                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
65674             }
65675             var arrayOrIterableType = checkExpression(node.expression, checkMode);
65676             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
65677         }
65678         function checkSyntheticExpression(node) {
65679             return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type;
65680         }
65681         function hasDefaultValue(node) {
65682             return (node.kind === 198 /* BindingElement */ && !!node.initializer) ||
65683                 (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
65684         }
65685         function checkArrayLiteral(node, checkMode, forceTuple) {
65686             var elements = node.elements;
65687             var elementCount = elements.length;
65688             var elementTypes = [];
65689             var elementFlags = [];
65690             var contextualType = getApparentTypeOfContextualType(node);
65691             var inDestructuringPattern = ts.isAssignmentTarget(node);
65692             var inConstContext = isConstContext(node);
65693             for (var i = 0; i < elementCount; i++) {
65694                 var e = elements[i];
65695                 if (e.kind === 220 /* SpreadElement */) {
65696                     if (languageVersion < 2 /* ES2015 */) {
65697                         checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
65698                     }
65699                     var spreadType = checkExpression(e.expression, checkMode, forceTuple);
65700                     if (isArrayLikeType(spreadType)) {
65701                         elementTypes.push(spreadType);
65702                         elementFlags.push(8 /* Variadic */);
65703                     }
65704                     else if (inDestructuringPattern) {
65705                         // Given the following situation:
65706                         //    var c: {};
65707                         //    [...c] = ["", 0];
65708                         //
65709                         // c is represented in the tree as a spread element in an array literal.
65710                         // But c really functions as a rest element, and its purpose is to provide
65711                         // a contextual type for the right hand side of the assignment. Therefore,
65712                         // instead of calling checkExpression on "...c", which will give an error
65713                         // if c is not iterable/array-like, we need to act as if we are trying to
65714                         // get the contextual element type from it. So we do something similar to
65715                         // getContextualTypeForElementExpression, which will crucially not error
65716                         // if there is no index type / iterated type.
65717                         var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
65718                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false) ||
65719                             unknownType;
65720                         elementTypes.push(restElementType);
65721                         elementFlags.push(4 /* Rest */);
65722                     }
65723                     else {
65724                         elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, e.expression));
65725                         elementFlags.push(4 /* Rest */);
65726                     }
65727                 }
65728                 else {
65729                     var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
65730                     var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
65731                     elementTypes.push(type);
65732                     elementFlags.push(1 /* Required */);
65733                 }
65734             }
65735             if (inDestructuringPattern) {
65736                 return createTupleType(elementTypes, elementFlags);
65737             }
65738             if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) {
65739                 return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext));
65740             }
65741             return createArrayLiteralType(createArrayType(elementTypes.length ?
65742                 getUnionType(ts.sameMap(elementTypes, function (t, i) { return elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t; }), 2 /* Subtype */) :
65743                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
65744         }
65745         function createArrayLiteralType(type) {
65746             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
65747                 return type;
65748             }
65749             var literalType = type.literalType;
65750             if (!literalType) {
65751                 literalType = type.literalType = cloneTypeReference(type);
65752                 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
65753             }
65754             return literalType;
65755         }
65756         function isNumericName(name) {
65757             switch (name.kind) {
65758                 case 158 /* ComputedPropertyName */:
65759                     return isNumericComputedName(name);
65760                 case 78 /* Identifier */:
65761                     return isNumericLiteralName(name.escapedText);
65762                 case 8 /* NumericLiteral */:
65763                 case 10 /* StringLiteral */:
65764                     return isNumericLiteralName(name.text);
65765                 default:
65766                     return false;
65767             }
65768         }
65769         function isNumericComputedName(name) {
65770             // It seems odd to consider an expression of type Any to result in a numeric name,
65771             // but this behavior is consistent with checkIndexedAccess
65772             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
65773         }
65774         function isInfinityOrNaNString(name) {
65775             return name === "Infinity" || name === "-Infinity" || name === "NaN";
65776         }
65777         function isNumericLiteralName(name) {
65778             // The intent of numeric names is that
65779             //     - they are names with text in a numeric form, and that
65780             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
65781             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
65782             //
65783             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
65784             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
65785             //
65786             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
65787             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
65788             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
65789             // because their 'ToString' representation is not equal to their original text.
65790             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
65791             //
65792             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
65793             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
65794             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
65795             //
65796             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
65797             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
65798             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
65799             return (+name).toString() === name;
65800         }
65801         function checkComputedPropertyName(node) {
65802             var links = getNodeLinks(node.expression);
65803             if (!links.resolvedType) {
65804                 links.resolvedType = checkExpression(node.expression);
65805                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
65806                 // type, and any union of these types (like string | number).
65807                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
65808                     !isTypeAssignableToKind(links.resolvedType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
65809                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
65810                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
65811                 }
65812                 else {
65813                     checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
65814                 }
65815             }
65816             return links.resolvedType;
65817         }
65818         function isSymbolWithNumericName(symbol) {
65819             var _a;
65820             var firstDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0];
65821             return isNumericLiteralName(symbol.escapedName) || (firstDecl && ts.isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name));
65822         }
65823         function getObjectLiteralIndexInfo(node, offset, properties, kind) {
65824             var propTypes = [];
65825             for (var i = offset; i < properties.length; i++) {
65826                 if (kind === 0 /* String */ || isSymbolWithNumericName(properties[i])) {
65827                     propTypes.push(getTypeOfSymbol(properties[i]));
65828                 }
65829             }
65830             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
65831             return createIndexInfo(unionType, isConstContext(node));
65832         }
65833         function getImmediateAliasedSymbol(symbol) {
65834             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
65835             var links = getSymbolLinks(symbol);
65836             if (!links.immediateTarget) {
65837                 var node = getDeclarationOfAliasSymbol(symbol);
65838                 if (!node)
65839                     return ts.Debug.fail();
65840                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
65841             }
65842             return links.immediateTarget;
65843         }
65844         function checkObjectLiteral(node, checkMode) {
65845             var inDestructuringPattern = ts.isAssignmentTarget(node);
65846             // Grammar checking
65847             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
65848             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
65849             var propertiesTable = ts.createSymbolTable();
65850             var propertiesArray = [];
65851             var spread = emptyObjectType;
65852             var contextualType = getApparentTypeOfContextualType(node);
65853             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
65854                 (contextualType.pattern.kind === 196 /* ObjectBindingPattern */ || contextualType.pattern.kind === 200 /* ObjectLiteralExpression */);
65855             var inConstContext = isConstContext(node);
65856             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
65857             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
65858             var enumTag = ts.getJSDocEnumTag(node);
65859             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
65860             var objectFlags = freshObjectLiteralFlag;
65861             var patternWithComputedProperties = false;
65862             var hasComputedStringProperty = false;
65863             var hasComputedNumberProperty = false;
65864             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
65865             // As otherwise they may not be checked until exports for the type at this position are retrieved,
65866             // which may never occur.
65867             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
65868                 var elem = _a[_i];
65869                 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
65870                     checkComputedPropertyName(elem.name);
65871                 }
65872             }
65873             var offset = 0;
65874             for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
65875                 var memberDecl = _c[_b];
65876                 var member = getSymbolOfNode(memberDecl);
65877                 var computedNameType = memberDecl.name && memberDecl.name.kind === 158 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
65878                     checkComputedPropertyName(memberDecl.name) : undefined;
65879                 if (memberDecl.kind === 288 /* PropertyAssignment */ ||
65880                     memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ||
65881                     ts.isObjectLiteralMethod(memberDecl)) {
65882                     var type = memberDecl.kind === 288 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
65883                         // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring
65884                         // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`.
65885                         // we don't want to say "could not find 'a'".
65886                         memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) :
65887                             checkObjectLiteralMethod(memberDecl, checkMode);
65888                     if (isInJavascript) {
65889                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
65890                         if (jsDocType) {
65891                             checkTypeAssignableTo(type, jsDocType, memberDecl);
65892                             type = jsDocType;
65893                         }
65894                         else if (enumTag && enumTag.typeExpression) {
65895                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
65896                         }
65897                     }
65898                     objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
65899                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
65900                     var prop = nameType ?
65901                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
65902                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
65903                     if (nameType) {
65904                         prop.nameType = nameType;
65905                     }
65906                     if (inDestructuringPattern) {
65907                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
65908                         // for the property, make the property optional.
65909                         var isOptional = (memberDecl.kind === 288 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
65910                             (memberDecl.kind === 289 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
65911                         if (isOptional) {
65912                             prop.flags |= 16777216 /* Optional */;
65913                         }
65914                     }
65915                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
65916                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
65917                         // binding pattern specifies a default value for the property, make the property optional.
65918                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
65919                         if (impliedProp) {
65920                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
65921                         }
65922                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
65923                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
65924                         }
65925                     }
65926                     prop.declarations = member.declarations;
65927                     prop.parent = member.parent;
65928                     if (member.valueDeclaration) {
65929                         prop.valueDeclaration = member.valueDeclaration;
65930                     }
65931                     prop.type = type;
65932                     prop.target = member;
65933                     member = prop;
65934                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
65935                 }
65936                 else if (memberDecl.kind === 290 /* SpreadAssignment */) {
65937                     if (languageVersion < 2 /* ES2015 */) {
65938                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
65939                     }
65940                     if (propertiesArray.length > 0) {
65941                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
65942                         propertiesArray = [];
65943                         propertiesTable = ts.createSymbolTable();
65944                         hasComputedStringProperty = false;
65945                         hasComputedNumberProperty = false;
65946                     }
65947                     var type = getReducedType(checkExpression(memberDecl.expression));
65948                     if (!isValidSpreadType(type)) {
65949                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
65950                         return errorType;
65951                     }
65952                     if (allPropertiesTable) {
65953                         checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
65954                     }
65955                     spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
65956                     offset = propertiesArray.length;
65957                     continue;
65958                 }
65959                 else {
65960                     // TypeScript 1.0 spec (April 2014)
65961                     // A get accessor declaration is processed in the same manner as
65962                     // an ordinary function declaration(section 6.1) with no parameters.
65963                     // A set accessor declaration is processed in the same manner
65964                     // as an ordinary function declaration with a single parameter and a Void return type.
65965                     ts.Debug.assert(memberDecl.kind === 167 /* GetAccessor */ || memberDecl.kind === 168 /* SetAccessor */);
65966                     checkNodeDeferred(memberDecl);
65967                 }
65968                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
65969                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
65970                         if (isTypeAssignableTo(computedNameType, numberType)) {
65971                             hasComputedNumberProperty = true;
65972                         }
65973                         else {
65974                             hasComputedStringProperty = true;
65975                         }
65976                         if (inDestructuringPattern) {
65977                             patternWithComputedProperties = true;
65978                         }
65979                     }
65980                 }
65981                 else {
65982                     propertiesTable.set(member.escapedName, member);
65983                 }
65984                 propertiesArray.push(member);
65985             }
65986             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
65987             // type with those properties for which the binding pattern specifies a default value.
65988             // If the object literal is spread into another object literal, skip this step and let the top-level object
65989             // literal handle it instead.
65990             if (contextualTypeHasPattern && node.parent.kind !== 290 /* SpreadAssignment */) {
65991                 for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) {
65992                     var prop = _e[_d];
65993                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
65994                         if (!(prop.flags & 16777216 /* Optional */)) {
65995                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
65996                         }
65997                         propertiesTable.set(prop.escapedName, prop);
65998                         propertiesArray.push(prop);
65999                     }
66000                 }
66001             }
66002             if (spread !== emptyObjectType) {
66003                 if (propertiesArray.length > 0) {
66004                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
66005                     propertiesArray = [];
66006                     propertiesTable = ts.createSymbolTable();
66007                     hasComputedStringProperty = false;
66008                     hasComputedNumberProperty = false;
66009                 }
66010                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
66011                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
66012             }
66013             return createObjectLiteralType();
66014             function createObjectLiteralType() {
66015                 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
66016                 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
66017                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
66018                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
66019                 if (isJSObjectLiteral) {
66020                     result.objectFlags |= 16384 /* JSLiteral */;
66021                 }
66022                 if (patternWithComputedProperties) {
66023                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
66024                 }
66025                 if (inDestructuringPattern) {
66026                     result.pattern = node;
66027                 }
66028                 return result;
66029             }
66030         }
66031         function isValidSpreadType(type) {
66032             if (type.flags & 465829888 /* Instantiable */) {
66033                 var constraint = getBaseConstraintOfType(type);
66034                 if (constraint !== undefined) {
66035                     return isValidSpreadType(constraint);
66036                 }
66037             }
66038             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
66039                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
66040                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
66041         }
66042         function checkJsxSelfClosingElementDeferred(node) {
66043             checkJsxOpeningLikeElementOrOpeningFragment(node);
66044         }
66045         function checkJsxSelfClosingElement(node, _checkMode) {
66046             checkNodeDeferred(node);
66047             return getJsxElementTypeAt(node) || anyType;
66048         }
66049         function checkJsxElementDeferred(node) {
66050             // Check attributes
66051             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
66052             // Perform resolution on the closing tag so that rename/go to definition/etc work
66053             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
66054                 getIntrinsicTagSymbol(node.closingElement);
66055             }
66056             else {
66057                 checkExpression(node.closingElement.tagName);
66058             }
66059             checkJsxChildren(node);
66060         }
66061         function checkJsxElement(node, _checkMode) {
66062             checkNodeDeferred(node);
66063             return getJsxElementTypeAt(node) || anyType;
66064         }
66065         function checkJsxFragment(node) {
66066             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
66067             // by default, jsx:'react' will use jsxFactory = React.createElement and jsxFragmentFactory = React.Fragment
66068             // if jsxFactory compiler option is provided, ensure jsxFragmentFactory compiler option or @jsxFrag pragma is provided too
66069             var nodeSourceFile = ts.getSourceFileOfNode(node);
66070             if (ts.getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx"))
66071                 && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) {
66072                 error(node, compilerOptions.jsxFactory
66073                     ? ts.Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option
66074                     : ts.Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments);
66075             }
66076             checkJsxChildren(node);
66077             return getJsxElementTypeAt(node) || anyType;
66078         }
66079         /**
66080          * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
66081          */
66082         function isUnhyphenatedJsxName(name) {
66083             // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
66084             return !ts.stringContains(name, "-");
66085         }
66086         /**
66087          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
66088          */
66089         function isJsxIntrinsicIdentifier(tagName) {
66090             return tagName.kind === 78 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
66091         }
66092         function checkJsxAttribute(node, checkMode) {
66093             return node.initializer
66094                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
66095                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
66096         }
66097         /**
66098          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
66099          *
66100          * @param openingLikeElement a JSX opening-like element
66101          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
66102          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
66103          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
66104          * which also calls getSpreadType.
66105          */
66106         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
66107             var attributes = openingLikeElement.attributes;
66108             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
66109             var attributesTable = ts.createSymbolTable();
66110             var spread = emptyJsxObjectType;
66111             var hasSpreadAnyType = false;
66112             var typeToIntersect;
66113             var explicitlySpecifyChildrenAttribute = false;
66114             var objectFlags = 4096 /* JsxAttributes */;
66115             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
66116             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
66117                 var attributeDecl = _a[_i];
66118                 var member = attributeDecl.symbol;
66119                 if (ts.isJsxAttribute(attributeDecl)) {
66120                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
66121                     objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
66122                     var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName);
66123                     attributeSymbol.declarations = member.declarations;
66124                     attributeSymbol.parent = member.parent;
66125                     if (member.valueDeclaration) {
66126                         attributeSymbol.valueDeclaration = member.valueDeclaration;
66127                     }
66128                     attributeSymbol.type = exprType;
66129                     attributeSymbol.target = member;
66130                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
66131                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
66132                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
66133                         explicitlySpecifyChildrenAttribute = true;
66134                     }
66135                 }
66136                 else {
66137                     ts.Debug.assert(attributeDecl.kind === 282 /* JsxSpreadAttribute */);
66138                     if (attributesTable.size > 0) {
66139                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
66140                         attributesTable = ts.createSymbolTable();
66141                     }
66142                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
66143                     if (isTypeAny(exprType)) {
66144                         hasSpreadAnyType = true;
66145                     }
66146                     if (isValidSpreadType(exprType)) {
66147                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
66148                         if (allAttributesTable) {
66149                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
66150                         }
66151                     }
66152                     else {
66153                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
66154                     }
66155                 }
66156             }
66157             if (!hasSpreadAnyType) {
66158                 if (attributesTable.size > 0) {
66159                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
66160                 }
66161             }
66162             // Handle children attribute
66163             var parent = openingLikeElement.parent.kind === 273 /* JsxElement */ ? openingLikeElement.parent : undefined;
66164             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
66165             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
66166                 var childrenTypes = checkJsxChildren(parent, checkMode);
66167                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
66168                     // Error if there is a attribute named "children" explicitly specified and children element.
66169                     // This is because children element will overwrite the value from attributes.
66170                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
66171                     if (explicitlySpecifyChildrenAttribute) {
66172                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
66173                     }
66174                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
66175                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
66176                     // 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
66177                     var childrenPropSymbol = createSymbol(4 /* Property */, jsxChildrenPropertyName);
66178                     childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] :
66179                         childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) :
66180                             createArrayType(getUnionType(childrenTypes));
66181                     // Fake up a property declaration for the children
66182                     childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined);
66183                     ts.setParent(childrenPropSymbol.valueDeclaration, attributes);
66184                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
66185                     var childPropMap = ts.createSymbolTable();
66186                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
66187                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
66188                 }
66189             }
66190             if (hasSpreadAnyType) {
66191                 return anyType;
66192             }
66193             if (typeToIntersect && spread !== emptyJsxObjectType) {
66194                 return getIntersectionType([typeToIntersect, spread]);
66195             }
66196             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
66197             /**
66198              * Create anonymous type from given attributes symbol table.
66199              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
66200              * @param attributesTable a symbol table of attributes property
66201              */
66202             function createJsxAttributesType() {
66203                 objectFlags |= freshObjectLiteralFlag;
66204                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
66205                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
66206                 return result;
66207             }
66208         }
66209         function checkJsxChildren(node, checkMode) {
66210             var childrenTypes = [];
66211             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
66212                 var child = _a[_i];
66213                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
66214                 // because then type of children property will have constituent of string type.
66215                 if (child.kind === 11 /* JsxText */) {
66216                     if (!child.containsOnlyTriviaWhiteSpaces) {
66217                         childrenTypes.push(stringType);
66218                     }
66219                 }
66220                 else if (child.kind === 283 /* JsxExpression */ && !child.expression) {
66221                     continue; // empty jsx expressions don't *really* count as present children
66222                 }
66223                 else {
66224                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
66225                 }
66226             }
66227             return childrenTypes;
66228         }
66229         function checkSpreadPropOverrides(type, props, spread) {
66230             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
66231                 var right = _a[_i];
66232                 var left = props.get(right.escapedName);
66233                 var rightType = getTypeOfSymbol(right);
66234                 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
66235                     var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
66236                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
66237                 }
66238             }
66239         }
66240         /**
66241          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
66242          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
66243          * @param node a JSXAttributes to be resolved of its type
66244          */
66245         function checkJsxAttributes(node, checkMode) {
66246             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
66247         }
66248         function getJsxType(name, location) {
66249             var namespace = getJsxNamespaceAt(location);
66250             var exports = namespace && getExportsOfSymbol(namespace);
66251             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
66252             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
66253         }
66254         /**
66255          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
66256          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
66257          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
66258          * May also return unknownSymbol if both of these lookups fail.
66259          */
66260         function getIntrinsicTagSymbol(node) {
66261             var links = getNodeLinks(node);
66262             if (!links.resolvedSymbol) {
66263                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
66264                 if (intrinsicElementsType !== errorType) {
66265                     // Property case
66266                     if (!ts.isIdentifier(node.tagName))
66267                         return ts.Debug.fail();
66268                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
66269                     if (intrinsicProp) {
66270                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
66271                         return links.resolvedSymbol = intrinsicProp;
66272                     }
66273                     // Intrinsic string indexer case
66274                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
66275                     if (indexSignatureType) {
66276                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
66277                         return links.resolvedSymbol = intrinsicElementsType.symbol;
66278                     }
66279                     // Wasn't found
66280                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
66281                     return links.resolvedSymbol = unknownSymbol;
66282                 }
66283                 else {
66284                     if (noImplicitAny) {
66285                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
66286                     }
66287                     return links.resolvedSymbol = unknownSymbol;
66288                 }
66289             }
66290             return links.resolvedSymbol;
66291         }
66292         function getJsxNamespaceContainerForImplicitImport(location) {
66293             var file = location && ts.getSourceFileOfNode(location);
66294             var links = file && getNodeLinks(file);
66295             if (links && links.jsxImplicitImportContainer === false) {
66296                 return undefined;
66297             }
66298             if (links && links.jsxImplicitImportContainer) {
66299                 return links.jsxImplicitImportContainer;
66300             }
66301             var runtimeImportSpecifier = ts.getJSXRuntimeImport(ts.getJSXImplicitImportBase(compilerOptions, file), compilerOptions);
66302             if (!runtimeImportSpecifier) {
66303                 return undefined;
66304             }
66305             var isClassic = ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Classic;
66306             var errorMessage = isClassic
66307                 ? ts.Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
66308                 : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
66309             var mod = resolveExternalModule(location, runtimeImportSpecifier, errorMessage, location);
66310             var result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : undefined;
66311             if (links) {
66312                 links.jsxImplicitImportContainer = result || false;
66313             }
66314             return result;
66315         }
66316         function getJsxNamespaceAt(location) {
66317             var links = location && getNodeLinks(location);
66318             if (links && links.jsxNamespace) {
66319                 return links.jsxNamespace;
66320             }
66321             if (!links || links.jsxNamespace !== false) {
66322                 var resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location);
66323                 if (!resolvedNamespace || resolvedNamespace === unknownSymbol) {
66324                     var namespaceName = getJsxNamespace(location);
66325                     resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
66326                 }
66327                 if (resolvedNamespace) {
66328                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
66329                     if (candidate && candidate !== unknownSymbol) {
66330                         if (links) {
66331                             links.jsxNamespace = candidate;
66332                         }
66333                         return candidate;
66334                     }
66335                 }
66336                 if (links) {
66337                     links.jsxNamespace = false;
66338                 }
66339             }
66340             // JSX global fallback
66341             var s = resolveSymbol(getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined));
66342             if (s === unknownSymbol) {
66343                 return undefined; // TODO: GH#18217
66344             }
66345             return s; // TODO: GH#18217
66346         }
66347         /**
66348          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
66349          * Get a single property from that container if existed. Report an error if there are more than one property.
66350          *
66351          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
66352          *          if other string is given or the container doesn't exist, return undefined.
66353          */
66354         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
66355             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
66356             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
66357             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
66358             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
66359             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
66360             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
66361             if (propertiesOfJsxElementAttribPropInterface) {
66362                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
66363                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
66364                     return "";
66365                 }
66366                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
66367                 // property of the class instance type
66368                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
66369                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
66370                 }
66371                 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
66372                     // More than one property on ElementAttributesProperty is an error
66373                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
66374                 }
66375             }
66376             return undefined;
66377         }
66378         function getJsxLibraryManagedAttributes(jsxNamespace) {
66379             // JSX.LibraryManagedAttributes [symbol]
66380             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
66381         }
66382         /// e.g. "props" for React.d.ts,
66383         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
66384         ///     non-intrinsic elements' attributes type is 'any'),
66385         /// or '' if it has 0 properties (which means every
66386         ///     non-intrinsic elements' attributes type is the element instance type)
66387         function getJsxElementPropertiesName(jsxNamespace) {
66388             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
66389         }
66390         function getJsxElementChildrenPropertyName(jsxNamespace) {
66391             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
66392         }
66393         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
66394             if (elementType.flags & 4 /* String */) {
66395                 return [anySignature];
66396             }
66397             else if (elementType.flags & 128 /* StringLiteral */) {
66398                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
66399                 if (!intrinsicType) {
66400                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
66401                     return ts.emptyArray;
66402                 }
66403                 else {
66404                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
66405                     return [fakeSignature];
66406                 }
66407             }
66408             var apparentElemType = getApparentType(elementType);
66409             // Resolve the signatures, preferring constructor
66410             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
66411             if (signatures.length === 0) {
66412                 // No construct signatures, try call signatures
66413                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
66414             }
66415             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
66416                 // If each member has some combination of new/call signatures; make a union signature list for those
66417                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
66418             }
66419             return signatures;
66420         }
66421         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
66422             // 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
66423             // For example:
66424             //      var CustomTag: "h1" = "h1";
66425             //      <CustomTag> Hello World </CustomTag>
66426             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
66427             if (intrinsicElementsType !== errorType) {
66428                 var stringLiteralTypeName = type.value;
66429                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
66430                 if (intrinsicProp) {
66431                     return getTypeOfSymbol(intrinsicProp);
66432                 }
66433                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
66434                 if (indexSignatureType) {
66435                     return indexSignatureType;
66436                 }
66437                 return undefined;
66438             }
66439             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
66440             return anyType;
66441         }
66442         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
66443             if (refKind === 1 /* Function */) {
66444                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
66445                 if (sfcReturnConstraint) {
66446                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
66447                 }
66448             }
66449             else if (refKind === 0 /* Component */) {
66450                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
66451                 if (classConstraint) {
66452                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
66453                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
66454                 }
66455             }
66456             else { // Mixed
66457                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
66458                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
66459                 if (!sfcReturnConstraint || !classConstraint) {
66460                     return;
66461                 }
66462                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
66463                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
66464             }
66465             function generateInitialErrorChain() {
66466                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
66467                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
66468             }
66469         }
66470         /**
66471          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
66472          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
66473          * @param node an intrinsic JSX opening-like element
66474          */
66475         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
66476             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
66477             var links = getNodeLinks(node);
66478             if (!links.resolvedJsxElementAttributesType) {
66479                 var symbol = getIntrinsicTagSymbol(node);
66480                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
66481                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
66482                 }
66483                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
66484                     return links.resolvedJsxElementAttributesType =
66485                         getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
66486                 }
66487                 else {
66488                     return links.resolvedJsxElementAttributesType = errorType;
66489                 }
66490             }
66491             return links.resolvedJsxElementAttributesType;
66492         }
66493         function getJsxElementClassTypeAt(location) {
66494             var type = getJsxType(JsxNames.ElementClass, location);
66495             if (type === errorType)
66496                 return undefined;
66497             return type;
66498         }
66499         function getJsxElementTypeAt(location) {
66500             return getJsxType(JsxNames.Element, location);
66501         }
66502         function getJsxStatelessElementTypeAt(location) {
66503             var jsxElementType = getJsxElementTypeAt(location);
66504             if (jsxElementType) {
66505                 return getUnionType([jsxElementType, nullType]);
66506             }
66507         }
66508         /**
66509          * Returns all the properties of the Jsx.IntrinsicElements interface
66510          */
66511         function getJsxIntrinsicTagNamesAt(location) {
66512             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
66513             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
66514         }
66515         function checkJsxPreconditions(errorNode) {
66516             // Preconditions for using JSX
66517             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
66518                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
66519             }
66520             if (getJsxElementTypeAt(errorNode) === undefined) {
66521                 if (noImplicitAny) {
66522                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
66523                 }
66524             }
66525         }
66526         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
66527             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
66528             if (isNodeOpeningLikeElement) {
66529                 checkGrammarJsxElement(node);
66530             }
66531             checkJsxPreconditions(node);
66532             if (!getJsxNamespaceContainerForImplicitImport(node)) {
66533                 // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
66534                 // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
66535                 var jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
66536                 var jsxFactoryNamespace = getJsxNamespace(node);
66537                 var jsxFactoryLocation = isNodeOpeningLikeElement ? node.tagName : node;
66538                 // allow null as jsxFragmentFactory
66539                 var jsxFactorySym = void 0;
66540                 if (!(ts.isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) {
66541                     jsxFactorySym = resolveName(jsxFactoryLocation, jsxFactoryNamespace, 111551 /* Value */, jsxFactoryRefErr, jsxFactoryNamespace, /*isUse*/ true);
66542                 }
66543                 if (jsxFactorySym) {
66544                     // Mark local symbol as referenced here because it might not have been marked
66545                     // if jsx emit was not jsxFactory as there wont be error being emitted
66546                     jsxFactorySym.isReferenced = 67108863 /* All */;
66547                     // If react/jsxFactory symbol is alias, mark it as refereced
66548                     if (jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) {
66549                         markAliasSymbolAsReferenced(jsxFactorySym);
66550                     }
66551                 }
66552             }
66553             if (isNodeOpeningLikeElement) {
66554                 var jsxOpeningLikeNode = node;
66555                 var sig = getResolvedSignature(jsxOpeningLikeNode);
66556                 checkDeprecatedSignature(sig, node);
66557                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
66558             }
66559         }
66560         /**
66561          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
66562          * is considered known if
66563          * 1. the object type is empty and the check is for assignability, or
66564          * 2. if the object type has index signatures, or
66565          * 3. if the property is actually declared in the object type
66566          *    (this means that 'toString', for example, is not usually a known property).
66567          * 4. In a union or intersection type,
66568          *    a property is considered known if it is known in any constituent type.
66569          * @param targetType a type to search a given name in
66570          * @param name a property name to search
66571          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
66572          */
66573         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
66574             if (targetType.flags & 524288 /* Object */) {
66575                 var resolved = resolveStructuredTypeMembers(targetType);
66576                 if (resolved.stringIndexInfo ||
66577                     resolved.numberIndexInfo && isNumericLiteralName(name) ||
66578                     getPropertyOfObjectType(targetType, name) ||
66579                     isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
66580                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
66581                     return true;
66582                 }
66583             }
66584             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
66585                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
66586                     var t = _a[_i];
66587                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
66588                         return true;
66589                     }
66590                 }
66591             }
66592             return false;
66593         }
66594         function isExcessPropertyCheckTarget(type) {
66595             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
66596                 type.flags & 67108864 /* NonPrimitive */ ||
66597                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
66598                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
66599         }
66600         function checkJsxExpression(node, checkMode) {
66601             checkGrammarJsxExpression(node);
66602             if (node.expression) {
66603                 var type = checkExpression(node.expression, checkMode);
66604                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
66605                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
66606                 }
66607                 return type;
66608             }
66609             else {
66610                 return errorType;
66611             }
66612         }
66613         function getDeclarationNodeFlagsFromSymbol(s) {
66614             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
66615         }
66616         /**
66617          * Return whether this symbol is a member of a prototype somewhere
66618          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
66619          */
66620         function isPrototypeProperty(symbol) {
66621             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
66622                 return true;
66623             }
66624             if (ts.isInJSFile(symbol.valueDeclaration)) {
66625                 var parent = symbol.valueDeclaration.parent;
66626                 return parent && ts.isBinaryExpression(parent) &&
66627                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
66628             }
66629         }
66630         /**
66631          * Check whether the requested property access is valid.
66632          * Returns true if node is a valid property access, and false otherwise.
66633          * @param node The node to be checked.
66634          * @param isSuper True if the access is from `super.`.
66635          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
66636          * @param prop The symbol for the property being accessed.
66637          */
66638         function checkPropertyAccessibility(node, isSuper, type, prop) {
66639             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
66640             var errorNode = node.kind === 157 /* QualifiedName */ ? node.right : node.kind === 195 /* ImportType */ ? node : node.name;
66641             if (isSuper) {
66642                 // TS 1.0 spec (April 2014): 4.8.2
66643                 // - In a constructor, instance member function, instance member accessor, or
66644                 //   instance member variable initializer where this references a derived class instance,
66645                 //   a super property access is permitted and must specify a public instance member function of the base class.
66646                 // - In a static member function or static member accessor
66647                 //   where this references the constructor function object of a derived class,
66648                 //   a super property access is permitted and must specify a public static member function of the base class.
66649                 if (languageVersion < 2 /* ES2015 */) {
66650                     if (symbolHasNonMethodDeclaration(prop)) {
66651                         error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
66652                         return false;
66653                     }
66654                 }
66655                 if (flags & 128 /* Abstract */) {
66656                     // A method cannot be accessed in a super property access if the method is abstract.
66657                     // This error could mask a private property access error. But, a member
66658                     // cannot simultaneously be private and abstract, so this will trigger an
66659                     // additional error elsewhere.
66660                     error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
66661                     return false;
66662                 }
66663             }
66664             // Referencing abstract properties within their own constructors is not allowed
66665             if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
66666                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
66667                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
66668                     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
66669                     return false;
66670                 }
66671             }
66672             if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
66673                 if (!ts.getContainingClass(node)) {
66674                     error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
66675                     return false;
66676                 }
66677                 return true;
66678             }
66679             // Public properties are otherwise accessible.
66680             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
66681                 return true;
66682             }
66683             // Property is known to be private or protected at this point
66684             // Private property is accessible if the property is within the declaring class
66685             if (flags & 8 /* Private */) {
66686                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
66687                 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
66688                     error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
66689                     return false;
66690                 }
66691                 return true;
66692             }
66693             // Property is known to be protected at this point
66694             // All protected properties of a supertype are accessible in a super access
66695             if (isSuper) {
66696                 return true;
66697             }
66698             // Find the first enclosing class that has the declaring classes of the protected constituents
66699             // of the property as base classes
66700             var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
66701                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
66702                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
66703             });
66704             // A protected property is accessible if the property is within the declaring class or classes derived from it
66705             if (!enclosingClass) {
66706                 // allow PropertyAccessibility if context is in function with this parameter
66707                 // static member access is disallow
66708                 var thisParameter = void 0;
66709                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
66710                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
66711                     return false;
66712                 }
66713                 var thisType = getTypeFromTypeNode(thisParameter.type);
66714                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
66715             }
66716             // No further restrictions for static properties
66717             if (flags & 32 /* Static */) {
66718                 return true;
66719             }
66720             if (type.flags & 262144 /* TypeParameter */) {
66721                 // get the original type -- represented as the type constraint of the 'this' type
66722                 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
66723             }
66724             if (!type || !hasBaseType(type, enclosingClass)) {
66725                 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
66726                 return false;
66727             }
66728             return true;
66729         }
66730         function getThisParameterFromNodeContext(node) {
66731             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
66732             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
66733         }
66734         function symbolHasNonMethodDeclaration(symbol) {
66735             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
66736         }
66737         function checkNonNullExpression(node) {
66738             return checkNonNullType(checkExpression(node), node);
66739         }
66740         function isNullableType(type) {
66741             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
66742         }
66743         function getNonNullableTypeIfNeeded(type) {
66744             return isNullableType(type) ? getNonNullableType(type) : type;
66745         }
66746         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
66747             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
66748                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
66749                 ts.Diagnostics.Object_is_possibly_undefined :
66750                 ts.Diagnostics.Object_is_possibly_null);
66751         }
66752         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
66753             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
66754                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
66755                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
66756                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
66757         }
66758         function checkNonNullTypeWithReporter(type, node, reportError) {
66759             if (strictNullChecks && type.flags & 2 /* Unknown */) {
66760                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
66761                 return errorType;
66762             }
66763             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
66764             if (kind) {
66765                 reportError(node, kind);
66766                 var t = getNonNullableType(type);
66767                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
66768             }
66769             return type;
66770         }
66771         function checkNonNullType(type, node) {
66772             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
66773         }
66774         function checkNonNullNonVoidType(type, node) {
66775             var nonNullType = checkNonNullType(type, node);
66776             if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
66777                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
66778             }
66779             return nonNullType;
66780         }
66781         function checkPropertyAccessExpression(node) {
66782             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
66783                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
66784         }
66785         function checkPropertyAccessChain(node) {
66786             var leftType = checkExpression(node.expression);
66787             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
66788             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
66789         }
66790         function checkQualifiedName(node) {
66791             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
66792         }
66793         function isMethodAccessForCall(node) {
66794             while (node.parent.kind === 207 /* ParenthesizedExpression */) {
66795                 node = node.parent;
66796             }
66797             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
66798         }
66799         // Lookup the private identifier lexically.
66800         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
66801             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
66802                 var symbol = containingClass.symbol;
66803                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
66804                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
66805                 if (prop) {
66806                     return prop;
66807                 }
66808             }
66809         }
66810         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
66811             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
66812         }
66813         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
66814             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
66815             // Find a private identifier with the same description on the type.
66816             var propertyOnType;
66817             var properties = getPropertiesOfType(leftType);
66818             if (properties) {
66819                 ts.forEach(properties, function (symbol) {
66820                     var decl = symbol.valueDeclaration;
66821                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
66822                         propertyOnType = symbol;
66823                         return true;
66824                     }
66825                 });
66826             }
66827             var diagName = diagnosticName(right);
66828             if (propertyOnType) {
66829                 var typeValueDecl = propertyOnType.valueDeclaration;
66830                 var typeClass_1 = ts.getContainingClass(typeValueDecl);
66831                 ts.Debug.assert(!!typeClass_1);
66832                 // We found a private identifier property with the same description.
66833                 // Either:
66834                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
66835                 // - It is an attempt to access the private identifier outside of the class.
66836                 if (lexicallyScopedIdentifier) {
66837                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
66838                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
66839                     ts.Debug.assert(!!lexicalClass);
66840                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
66841                         var diagnostic = error(right, ts.Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling, diagName, typeToString(leftType));
66842                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(lexicalValueDecl, ts.Diagnostics.The_shadowing_declaration_of_0_is_defined_here, diagName), ts.createDiagnosticForNode(typeValueDecl, ts.Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here, diagName));
66843                         return true;
66844                     }
66845                 }
66846                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
66847                 return true;
66848             }
66849             return false;
66850         }
66851         function isThisPropertyAccessInConstructor(node, prop) {
66852             return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop))
66853                 && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop);
66854         }
66855         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
66856             var parentSymbol = getNodeLinks(left).resolvedSymbol;
66857             var assignmentKind = ts.getAssignmentTargetKind(node);
66858             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
66859             if (ts.isPrivateIdentifier(right)) {
66860                 checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldGet */);
66861             }
66862             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
66863             var prop;
66864             if (ts.isPrivateIdentifier(right)) {
66865                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
66866                 if (isAnyLike) {
66867                     if (lexicallyScopedSymbol) {
66868                         return apparentType;
66869                     }
66870                     if (!ts.getContainingClass(right)) {
66871                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
66872                         return anyType;
66873                     }
66874                 }
66875                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
66876                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
66877                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
66878                     return errorType;
66879                 }
66880             }
66881             else {
66882                 if (isAnyLike) {
66883                     if (ts.isIdentifier(left) && parentSymbol) {
66884                         markAliasReferenced(parentSymbol, node);
66885                     }
66886                     return apparentType;
66887                 }
66888                 prop = getPropertyOfType(apparentType, right.escapedText);
66889             }
66890             if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
66891                 markAliasReferenced(parentSymbol, node);
66892             }
66893             var propType;
66894             if (!prop) {
66895                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
66896                 if (!(indexInfo && indexInfo.type)) {
66897                     if (isJSLiteralType(leftType)) {
66898                         return anyType;
66899                     }
66900                     if (leftType.symbol === globalThisSymbol) {
66901                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
66902                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
66903                         }
66904                         else if (noImplicitAny) {
66905                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
66906                         }
66907                         return anyType;
66908                     }
66909                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
66910                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
66911                     }
66912                     return errorType;
66913                 }
66914                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
66915                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
66916                 }
66917                 propType = (compilerOptions.noUncheckedIndexedAccess && !ts.isAssignmentTarget(node)) ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
66918             }
66919             else {
66920                 if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) {
66921                     errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText);
66922                 }
66923                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
66924                 markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */);
66925                 getNodeLinks(node).resolvedSymbol = prop;
66926                 checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, apparentType, prop);
66927                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
66928                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
66929                     return errorType;
66930                 }
66931                 propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node);
66932             }
66933             return getFlowTypeOfAccessExpression(node, prop, propType, right);
66934         }
66935         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
66936             // Only compute control flow type if this is a property access expression that isn't an
66937             // assignment target, and the referenced property was declared as a variable, property,
66938             // accessor, or optional method.
66939             var assignmentKind = ts.getAssignmentTargetKind(node);
66940             if (!ts.isAccessExpression(node) ||
66941                 assignmentKind === 1 /* Definite */ ||
66942                 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
66943                 return propType;
66944             }
66945             if (propType === autoType) {
66946                 return getFlowTypeOfProperty(node, prop);
66947             }
66948             // If strict null checks and strict property initialization checks are enabled, if we have
66949             // a this.xxx property access, if the property is an instance property without an initializer,
66950             // and if we are in a constructor of the same class as the property declaration, assume that
66951             // the property is uninitialized at the top of the control flow.
66952             var assumeUninitialized = false;
66953             if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) {
66954                 var declaration = prop && prop.valueDeclaration;
66955                 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
66956                     var flowContainer = getControlFlowContainer(node);
66957                     if (flowContainer.kind === 166 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
66958                         assumeUninitialized = true;
66959                     }
66960                 }
66961             }
66962             else if (strictNullChecks && prop && prop.valueDeclaration &&
66963                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
66964                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
66965                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
66966                 assumeUninitialized = true;
66967             }
66968             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
66969             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
66970                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
66971                 // Return the declared type to reduce follow-on errors
66972                 return propType;
66973             }
66974             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
66975         }
66976         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
66977             var valueDeclaration = prop.valueDeclaration;
66978             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
66979                 return;
66980             }
66981             var diagnosticMessage;
66982             var declarationName = ts.idText(right);
66983             if (isInPropertyInitializer(node)
66984                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
66985                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
66986                 && !isPropertyDeclaredInAncestorClass(prop)) {
66987                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
66988             }
66989             else if (valueDeclaration.kind === 252 /* ClassDeclaration */ &&
66990                 node.parent.kind !== 173 /* TypeReference */ &&
66991                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
66992                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
66993                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
66994             }
66995             if (diagnosticMessage) {
66996                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
66997             }
66998         }
66999         function isInPropertyInitializer(node) {
67000             return !!ts.findAncestor(node, function (node) {
67001                 switch (node.kind) {
67002                     case 163 /* PropertyDeclaration */:
67003                         return true;
67004                     case 288 /* PropertyAssignment */:
67005                     case 165 /* MethodDeclaration */:
67006                     case 167 /* GetAccessor */:
67007                     case 168 /* SetAccessor */:
67008                     case 290 /* SpreadAssignment */:
67009                     case 158 /* ComputedPropertyName */:
67010                     case 228 /* TemplateSpan */:
67011                     case 283 /* JsxExpression */:
67012                     case 280 /* JsxAttribute */:
67013                     case 281 /* JsxAttributes */:
67014                     case 282 /* JsxSpreadAttribute */:
67015                     case 275 /* JsxOpeningElement */:
67016                     case 223 /* ExpressionWithTypeArguments */:
67017                     case 286 /* HeritageClause */:
67018                         return false;
67019                     default:
67020                         return ts.isExpressionNode(node) ? false : "quit";
67021                 }
67022             });
67023         }
67024         /**
67025          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
67026          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
67027          */
67028         function isPropertyDeclaredInAncestorClass(prop) {
67029             if (!(prop.parent.flags & 32 /* Class */)) {
67030                 return false;
67031             }
67032             var classType = getTypeOfSymbol(prop.parent);
67033             while (true) {
67034                 classType = classType.symbol && getSuperClass(classType);
67035                 if (!classType) {
67036                     return false;
67037                 }
67038                 var superProperty = getPropertyOfType(classType, prop.escapedName);
67039                 if (superProperty && superProperty.valueDeclaration) {
67040                     return true;
67041                 }
67042             }
67043         }
67044         function getSuperClass(classType) {
67045             var x = getBaseTypes(classType);
67046             if (x.length === 0) {
67047                 return undefined;
67048             }
67049             return getIntersectionType(x);
67050         }
67051         function reportNonexistentProperty(propNode, containingType) {
67052             var errorInfo;
67053             var relatedInfo;
67054             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
67055                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
67056                     var subtype = _a[_i];
67057                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
67058                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
67059                         break;
67060                     }
67061                 }
67062             }
67063             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
67064                 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
67065             }
67066             else {
67067                 var promisedType = getPromisedTypeOfPromise(containingType);
67068                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
67069                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
67070                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
67071                 }
67072                 else {
67073                     var missingProperty = ts.declarationNameToString(propNode);
67074                     var container = typeToString(containingType);
67075                     var libSuggestion = getSuggestedLibForNonExistentProperty(missingProperty, containingType);
67076                     if (libSuggestion !== undefined) {
67077                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later, missingProperty, container, libSuggestion);
67078                     }
67079                     else {
67080                         var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
67081                         if (suggestion !== undefined) {
67082                             var suggestedName = ts.symbolName(suggestion);
67083                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, missingProperty, container, suggestedName);
67084                             relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
67085                         }
67086                         else {
67087                             errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container);
67088                         }
67089                     }
67090                 }
67091             }
67092             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
67093             if (relatedInfo) {
67094                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
67095             }
67096             diagnostics.add(resultDiagnostic);
67097         }
67098         function typeHasStaticProperty(propName, containingType) {
67099             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
67100             return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */);
67101         }
67102         function getSuggestedLibForNonExistentName(name) {
67103             var missingName = diagnosticName(name);
67104             var allFeatures = ts.getScriptTargetFeatures();
67105             var libTargets = ts.getOwnKeys(allFeatures);
67106             for (var _i = 0, libTargets_1 = libTargets; _i < libTargets_1.length; _i++) {
67107                 var libTarget = libTargets_1[_i];
67108                 var containingTypes = ts.getOwnKeys(allFeatures[libTarget]);
67109                 if (containingTypes !== undefined && ts.contains(containingTypes, missingName)) {
67110                     return libTarget;
67111                 }
67112             }
67113         }
67114         function getSuggestedLibForNonExistentProperty(missingProperty, containingType) {
67115             var container = getApparentType(containingType).symbol;
67116             if (!container) {
67117                 return undefined;
67118             }
67119             var allFeatures = ts.getScriptTargetFeatures();
67120             var libTargets = ts.getOwnKeys(allFeatures);
67121             for (var _i = 0, libTargets_2 = libTargets; _i < libTargets_2.length; _i++) {
67122                 var libTarget = libTargets_2[_i];
67123                 var featuresOfLib = allFeatures[libTarget];
67124                 var featuresOfContainingType = featuresOfLib[ts.symbolName(container)];
67125                 if (featuresOfContainingType !== undefined && ts.contains(featuresOfContainingType, missingProperty)) {
67126                     return libTarget;
67127                 }
67128             }
67129         }
67130         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
67131             return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
67132         }
67133         function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) {
67134             var strName = ts.isString(name) ? name : ts.idText(name);
67135             var properties = getPropertiesOfType(containingType);
67136             var jsxSpecific = strName === "for" ? ts.find(properties, function (x) { return ts.symbolName(x) === "htmlFor"; })
67137                 : strName === "class" ? ts.find(properties, function (x) { return ts.symbolName(x) === "className"; })
67138                     : undefined;
67139             return jsxSpecific !== null && jsxSpecific !== void 0 ? jsxSpecific : getSpellingSuggestionForName(strName, properties, 111551 /* Value */);
67140         }
67141         function getSuggestionForNonexistentProperty(name, containingType) {
67142             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
67143             return suggestion && ts.symbolName(suggestion);
67144         }
67145         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
67146             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
67147             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
67148                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
67149                 var symbol = getSymbol(symbols, name, meaning);
67150                 // 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
67151                 // So the table *contains* `x` but `x` isn't actually in scope.
67152                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
67153                 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
67154             });
67155             return result;
67156         }
67157         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
67158             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
67159             return symbolResult && ts.symbolName(symbolResult);
67160         }
67161         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
67162             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
67163         }
67164         function getSuggestionForNonexistentExport(name, targetModule) {
67165             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
67166             return suggestion && ts.symbolName(suggestion);
67167         }
67168         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
67169             // check if object type has setter or getter
67170             function hasProp(name) {
67171                 var prop = getPropertyOfObjectType(objectType, name);
67172                 if (prop) {
67173                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
67174                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
67175                 }
67176                 return false;
67177             }
67178             ;
67179             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
67180             if (!hasProp(suggestedMethod)) {
67181                 return undefined;
67182             }
67183             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
67184             if (suggestion === undefined) {
67185                 suggestion = suggestedMethod;
67186             }
67187             else {
67188                 suggestion += "." + suggestedMethod;
67189             }
67190             return suggestion;
67191         }
67192         /**
67193          * 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.
67194          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
67195          *
67196          * If there is a candidate that's the same except for case, return that.
67197          * If there is a candidate that's within one edit of the name, return that.
67198          * Otherwise, return the candidate with the smallest Levenshtein distance,
67199          *    except for candidates:
67200          *      * With no name
67201          *      * Whose meaning doesn't match the `meaning` parameter.
67202          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
67203          *      * Whose levenshtein distance is more than 0.4 of the length of the name
67204          *        (0.4 allows 1 substitution/transposition for every 5 characters,
67205          *         and 1 insertion/deletion at 3 characters)
67206          */
67207         function getSpellingSuggestionForName(name, symbols, meaning) {
67208             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
67209             function getCandidateName(candidate) {
67210                 var candidateName = ts.symbolName(candidate);
67211                 if (ts.startsWith(candidateName, "\"")) {
67212                     return undefined;
67213                 }
67214                 if (candidate.flags & meaning) {
67215                     return candidateName;
67216                 }
67217                 if (candidate.flags & 2097152 /* Alias */) {
67218                     var alias = tryResolveAlias(candidate);
67219                     if (alias && alias.flags & meaning) {
67220                         return candidateName;
67221                     }
67222                 }
67223                 return undefined;
67224             }
67225         }
67226         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
67227             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
67228             if (!valueDeclaration) {
67229                 return;
67230             }
67231             var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */);
67232             var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
67233             if (!hasPrivateModifier && !hasPrivateIdentifier) {
67234                 return;
67235             }
67236             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
67237                 return;
67238             }
67239             if (isThisAccess) {
67240                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
67241                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
67242                 if (containingMethod && containingMethod.symbol === prop) {
67243                     return;
67244                 }
67245             }
67246             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
67247         }
67248         function isValidPropertyAccess(node, propertyName) {
67249             switch (node.kind) {
67250                 case 201 /* PropertyAccessExpression */:
67251                     return isValidPropertyAccessWithType(node, node.expression.kind === 105 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
67252                 case 157 /* QualifiedName */:
67253                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
67254                 case 195 /* ImportType */:
67255                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
67256             }
67257         }
67258         function isValidPropertyAccessForCompletions(node, type, property) {
67259             return isValidPropertyAccessWithType(node, node.kind === 201 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type);
67260             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
67261         }
67262         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
67263             if (type === errorType || isTypeAny(type)) {
67264                 return true;
67265             }
67266             var prop = getPropertyOfType(type, propertyName);
67267             if (prop) {
67268                 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
67269                     var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
67270                     return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
67271                 }
67272                 return checkPropertyAccessibility(node, isSuper, type, prop);
67273             }
67274             // In js files properties of unions are allowed in completion
67275             return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
67276         }
67277         /**
67278          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
67279          */
67280         function getForInVariableSymbol(node) {
67281             var initializer = node.initializer;
67282             if (initializer.kind === 250 /* VariableDeclarationList */) {
67283                 var variable = initializer.declarations[0];
67284                 if (variable && !ts.isBindingPattern(variable.name)) {
67285                     return getSymbolOfNode(variable);
67286                 }
67287             }
67288             else if (initializer.kind === 78 /* Identifier */) {
67289                 return getResolvedSymbol(initializer);
67290             }
67291             return undefined;
67292         }
67293         /**
67294          * Return true if the given type is considered to have numeric property names.
67295          */
67296         function hasNumericPropertyNames(type) {
67297             return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
67298         }
67299         /**
67300          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
67301          * that references a for-in variable for an object with numeric property names.
67302          */
67303         function isForInVariableForNumericPropertyNames(expr) {
67304             var e = ts.skipParentheses(expr);
67305             if (e.kind === 78 /* Identifier */) {
67306                 var symbol = getResolvedSymbol(e);
67307                 if (symbol.flags & 3 /* Variable */) {
67308                     var child = expr;
67309                     var node = expr.parent;
67310                     while (node) {
67311                         if (node.kind === 238 /* ForInStatement */ &&
67312                             child === node.statement &&
67313                             getForInVariableSymbol(node) === symbol &&
67314                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
67315                             return true;
67316                         }
67317                         child = node;
67318                         node = node.parent;
67319                     }
67320                 }
67321             }
67322             return false;
67323         }
67324         function checkIndexedAccess(node) {
67325             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
67326                 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
67327         }
67328         function checkElementAccessChain(node) {
67329             var exprType = checkExpression(node.expression);
67330             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
67331             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
67332         }
67333         function checkElementAccessExpression(node, exprType) {
67334             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
67335             var indexExpression = node.argumentExpression;
67336             var indexType = checkExpression(indexExpression);
67337             if (objectType === errorType || objectType === silentNeverType) {
67338                 return objectType;
67339             }
67340             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
67341                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
67342                 return errorType;
67343             }
67344             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
67345             var accessFlags = ts.isAssignmentTarget(node) ?
67346                 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
67347                 0 /* None */;
67348             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | 16 /* ExpressionPosition */) || errorType;
67349             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
67350         }
67351         function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
67352             if (expressionType === errorType) {
67353                 // There is already an error, so no need to report one.
67354                 return false;
67355             }
67356             if (!ts.isWellKnownSymbolSyntactically(expression)) {
67357                 return false;
67358             }
67359             // Make sure the property type is the primitive symbol type
67360             if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
67361                 if (reportError) {
67362                     error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
67363                 }
67364                 return false;
67365             }
67366             // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
67367             // global Symbol object
67368             var leftHandSide = expression.expression;
67369             var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
67370             if (!leftHandSideSymbol) {
67371                 return false;
67372             }
67373             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
67374             if (!globalESSymbol) {
67375                 // Already errored when we tried to look up the symbol
67376                 return false;
67377             }
67378             if (leftHandSideSymbol !== globalESSymbol) {
67379                 if (reportError) {
67380                     error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
67381                 }
67382                 return false;
67383             }
67384             return true;
67385         }
67386         function callLikeExpressionMayHaveTypeArguments(node) {
67387             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
67388         }
67389         function resolveUntypedCall(node) {
67390             if (callLikeExpressionMayHaveTypeArguments(node)) {
67391                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
67392                 // This gets us diagnostics for the type arguments and marks them as referenced.
67393                 ts.forEach(node.typeArguments, checkSourceElement);
67394             }
67395             if (node.kind === 205 /* TaggedTemplateExpression */) {
67396                 checkExpression(node.template);
67397             }
67398             else if (ts.isJsxOpeningLikeElement(node)) {
67399                 checkExpression(node.attributes);
67400             }
67401             else if (node.kind !== 161 /* Decorator */) {
67402                 ts.forEach(node.arguments, function (argument) {
67403                     checkExpression(argument);
67404                 });
67405             }
67406             return anySignature;
67407         }
67408         function resolveErrorCall(node) {
67409             resolveUntypedCall(node);
67410             return unknownSignature;
67411         }
67412         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
67413         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
67414         // A nit here is that we reorder only signatures that belong to the same symbol,
67415         // so order how inherited signatures are processed is still preserved.
67416         // interface A { (x: string): void }
67417         // interface B extends A { (x: 'foo'): string }
67418         // const b: B;
67419         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
67420         function reorderCandidates(signatures, result, callChainFlags) {
67421             var lastParent;
67422             var lastSymbol;
67423             var cutoffIndex = 0;
67424             var index;
67425             var specializedIndex = -1;
67426             var spliceIndex;
67427             ts.Debug.assert(!result.length);
67428             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
67429                 var signature = signatures_7[_i];
67430                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
67431                 var parent = signature.declaration && signature.declaration.parent;
67432                 if (!lastSymbol || symbol === lastSymbol) {
67433                     if (lastParent && parent === lastParent) {
67434                         index = index + 1;
67435                     }
67436                     else {
67437                         lastParent = parent;
67438                         index = cutoffIndex;
67439                     }
67440                 }
67441                 else {
67442                     // current declaration belongs to a different symbol
67443                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
67444                     index = cutoffIndex = result.length;
67445                     lastParent = parent;
67446                 }
67447                 lastSymbol = symbol;
67448                 // specialized signatures always need to be placed before non-specialized signatures regardless
67449                 // of the cutoff position; see GH#1133
67450                 if (signatureHasLiteralTypes(signature)) {
67451                     specializedIndex++;
67452                     spliceIndex = specializedIndex;
67453                     // The cutoff index always needs to be greater than or equal to the specialized signature index
67454                     // in order to prevent non-specialized signatures from being added before a specialized
67455                     // signature.
67456                     cutoffIndex++;
67457                 }
67458                 else {
67459                     spliceIndex = index;
67460                 }
67461                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
67462             }
67463         }
67464         function isSpreadArgument(arg) {
67465             return !!arg && (arg.kind === 220 /* SpreadElement */ || arg.kind === 227 /* SyntheticExpression */ && arg.isSpread);
67466         }
67467         function getSpreadArgumentIndex(args) {
67468             return ts.findIndex(args, isSpreadArgument);
67469         }
67470         function acceptsVoid(t) {
67471             return !!(t.flags & 16384 /* Void */);
67472         }
67473         function acceptsVoidUndefinedUnknownOrAny(t) {
67474             return !!(t.flags & (16384 /* Void */ | 32768 /* Undefined */ | 2 /* Unknown */ | 1 /* Any */));
67475         }
67476         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
67477             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
67478             var argCount;
67479             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
67480             var effectiveParameterCount = getParameterCount(signature);
67481             var effectiveMinimumArguments = getMinArgumentCount(signature);
67482             if (node.kind === 205 /* TaggedTemplateExpression */) {
67483                 argCount = args.length;
67484                 if (node.template.kind === 218 /* TemplateExpression */) {
67485                     // If a tagged template expression lacks a tail literal, the call is incomplete.
67486                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
67487                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
67488                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
67489                 }
67490                 else {
67491                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
67492                     // then this might actually turn out to be a TemplateHead in the future;
67493                     // so we consider the call to be incomplete.
67494                     var templateLiteral = node.template;
67495                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
67496                     callIsIncomplete = !!templateLiteral.isUnterminated;
67497                 }
67498             }
67499             else if (node.kind === 161 /* Decorator */) {
67500                 argCount = getDecoratorArgumentCount(node, signature);
67501             }
67502             else if (ts.isJsxOpeningLikeElement(node)) {
67503                 callIsIncomplete = node.attributes.end === node.end;
67504                 if (callIsIncomplete) {
67505                     return true;
67506                 }
67507                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
67508                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
67509                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
67510             }
67511             else if (!node.arguments) {
67512                 // This only happens when we have something of the form: 'new C'
67513                 ts.Debug.assert(node.kind === 204 /* NewExpression */);
67514                 return getMinArgumentCount(signature) === 0;
67515             }
67516             else {
67517                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
67518                 // If we are missing the close parenthesis, the call is incomplete.
67519                 callIsIncomplete = node.arguments.end === node.end;
67520                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
67521                 var spreadArgIndex = getSpreadArgumentIndex(args);
67522                 if (spreadArgIndex >= 0) {
67523                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
67524                 }
67525             }
67526             // Too many arguments implies incorrect arity.
67527             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
67528                 return false;
67529             }
67530             // If the call is incomplete, we should skip the lower bound check.
67531             // JSX signatures can have extra parameters provided by the library which we don't check
67532             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
67533                 return true;
67534             }
67535             for (var i = argCount; i < effectiveMinimumArguments; i++) {
67536                 var type = getTypeAtPosition(signature, i);
67537                 if (filterType(type, ts.isInJSFile(node) && !strictNullChecks ? acceptsVoidUndefinedUnknownOrAny : acceptsVoid).flags & 131072 /* Never */) {
67538                     return false;
67539                 }
67540             }
67541             return true;
67542         }
67543         function hasCorrectTypeArgumentArity(signature, typeArguments) {
67544             // If the user supplied type arguments, but the number of type arguments does not match
67545             // the declared number of type parameters, the call has an incorrect arity.
67546             var numTypeParameters = ts.length(signature.typeParameters);
67547             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
67548             return !ts.some(typeArguments) ||
67549                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
67550         }
67551         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
67552         function getSingleCallSignature(type) {
67553             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
67554         }
67555         function getSingleCallOrConstructSignature(type) {
67556             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
67557                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
67558         }
67559         function getSingleSignature(type, kind, allowMembers) {
67560             if (type.flags & 524288 /* Object */) {
67561                 var resolved = resolveStructuredTypeMembers(type);
67562                 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
67563                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
67564                         return resolved.callSignatures[0];
67565                     }
67566                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
67567                         return resolved.constructSignatures[0];
67568                     }
67569                 }
67570             }
67571             return undefined;
67572         }
67573         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
67574         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
67575             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
67576             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
67577             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
67578             // for T but leave it possible to later infer '[any]' back to A.
67579             var restType = getEffectiveRestType(contextualSignature);
67580             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
67581             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
67582             applyToParameterTypes(sourceSignature, signature, function (source, target) {
67583                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
67584                 inferTypes(context.inferences, source, target);
67585             });
67586             if (!inferenceContext) {
67587                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
67588                     inferTypes(context.inferences, source, target, 64 /* ReturnType */);
67589                 });
67590             }
67591             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
67592         }
67593         function inferJsxTypeArguments(node, signature, checkMode, context) {
67594             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
67595             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
67596             inferTypes(context.inferences, checkAttrType, paramType);
67597             return getInferredTypes(context);
67598         }
67599         function inferTypeArguments(node, signature, args, checkMode, context) {
67600             if (ts.isJsxOpeningLikeElement(node)) {
67601                 return inferJsxTypeArguments(node, signature, checkMode, context);
67602             }
67603             // If a contextual type is available, infer from that type to the return type of the call expression. For
67604             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
67605             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
67606             // return type of 'wrap'.
67607             if (node.kind !== 161 /* Decorator */) {
67608                 var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */);
67609                 if (contextualType) {
67610                     // We clone the inference context to avoid disturbing a resolution in progress for an
67611                     // outer call expression. Effectively we just want a snapshot of whatever has been
67612                     // inferred for any outer call expression so far.
67613                     var outerContext = getInferenceContext(node);
67614                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
67615                     var instantiatedType = instantiateType(contextualType, outerMapper);
67616                     // If the contextual type is a generic function type with a single call signature, we
67617                     // instantiate the type with its own type parameters and type arguments. This ensures that
67618                     // the type parameters are not erased to type any during type inference such that they can
67619                     // be inferred as actual types from the contextual type. For example:
67620                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
67621                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
67622                     // Above, the type of the 'value' parameter is inferred to be 'A'.
67623                     var contextualSignature = getSingleCallSignature(instantiatedType);
67624                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
67625                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
67626                         instantiatedType;
67627                     var inferenceTargetType = getReturnTypeOfSignature(signature);
67628                     // Inferences made from return types have lower priority than all other inferences.
67629                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */);
67630                     // Create a type mapper for instantiating generic contextual types using the inferences made
67631                     // from the return type. We need a separate inference pass here because (a) instantiation of
67632                     // the source type uses the outer context's return mapper (which excludes inferences made from
67633                     // outer arguments), and (b) we don't want any further inferences going into this context.
67634                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
67635                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
67636                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
67637                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
67638                 }
67639             }
67640             var restType = getNonArrayRestType(signature);
67641             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
67642             if (restType && restType.flags & 262144 /* TypeParameter */) {
67643                 var info = ts.find(context.inferences, function (info) { return info.typeParameter === restType; });
67644                 if (info) {
67645                     info.impliedArity = ts.findIndex(args, isSpreadArgument, argCount) < 0 ? args.length - argCount : undefined;
67646                 }
67647             }
67648             var thisType = getThisTypeOfSignature(signature);
67649             if (thisType) {
67650                 var thisArgumentNode = getThisArgumentOfCall(node);
67651                 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
67652                 inferTypes(context.inferences, thisArgumentType, thisType);
67653             }
67654             for (var i = 0; i < argCount; i++) {
67655                 var arg = args[i];
67656                 if (arg.kind !== 222 /* OmittedExpression */) {
67657                     var paramType = getTypeAtPosition(signature, i);
67658                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
67659                     inferTypes(context.inferences, argType, paramType);
67660                 }
67661             }
67662             if (restType) {
67663                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context, checkMode);
67664                 inferTypes(context.inferences, spreadType, restType);
67665             }
67666             return getInferredTypes(context);
67667         }
67668         function getMutableArrayOrTupleType(type) {
67669             return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) :
67670                 type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type :
67671                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.elementFlags, /*readonly*/ false, type.target.labeledElementDeclarations) :
67672                         createTupleType([type], [8 /* Variadic */]);
67673         }
67674         function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) {
67675             if (index >= argCount - 1) {
67676                 var arg = args[argCount - 1];
67677                 if (isSpreadArgument(arg)) {
67678                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
67679                     // and the argument are ...x forms.
67680                     return getMutableArrayOrTupleType(arg.kind === 227 /* SyntheticExpression */ ? arg.type :
67681                         checkExpressionWithContextualType(arg.expression, restType, context, checkMode));
67682                 }
67683             }
67684             var types = [];
67685             var flags = [];
67686             var names = [];
67687             for (var i = index; i < argCount; i++) {
67688                 var arg = args[i];
67689                 if (isSpreadArgument(arg)) {
67690                     var spreadType = arg.kind === 227 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression);
67691                     if (isArrayLikeType(spreadType)) {
67692                         types.push(spreadType);
67693                         flags.push(8 /* Variadic */);
67694                     }
67695                     else {
67696                         types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 220 /* SpreadElement */ ? arg.expression : arg));
67697                         flags.push(4 /* Rest */);
67698                     }
67699                 }
67700                 else {
67701                     var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
67702                     var argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode);
67703                     var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
67704                     types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
67705                     flags.push(1 /* Required */);
67706                 }
67707                 if (arg.kind === 227 /* SyntheticExpression */ && arg.tupleNameSource) {
67708                     names.push(arg.tupleNameSource);
67709                 }
67710             }
67711             return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
67712         }
67713         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
67714             var isJavascript = ts.isInJSFile(signature.declaration);
67715             var typeParameters = signature.typeParameters;
67716             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
67717             var mapper;
67718             for (var i = 0; i < typeArgumentNodes.length; i++) {
67719                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
67720                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
67721                 if (constraint) {
67722                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
67723                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
67724                     if (!mapper) {
67725                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
67726                     }
67727                     var typeArgument = typeArgumentTypes[i];
67728                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
67729                         return undefined;
67730                     }
67731                 }
67732             }
67733             return typeArgumentTypes;
67734         }
67735         function getJsxReferenceKind(node) {
67736             if (isJsxIntrinsicIdentifier(node.tagName)) {
67737                 return 2 /* Mixed */;
67738             }
67739             var tagType = getApparentType(checkExpression(node.tagName));
67740             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
67741                 return 0 /* Component */;
67742             }
67743             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
67744                 return 1 /* Function */;
67745             }
67746             return 2 /* Mixed */;
67747         }
67748         /**
67749          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
67750          * @param node a JSX opening-like element we are trying to figure its call signature
67751          * @param signature a candidate signature we are trying whether it is a call signature
67752          * @param relation a relationship to check parameter and argument type
67753          */
67754         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
67755             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
67756             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
67757             // can be specified by users through attributes property.
67758             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
67759             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
67760             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
67761             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
67762             function checkTagNameDoesNotExpectTooManyArguments() {
67763                 var _a;
67764                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
67765                 if (!tagType) {
67766                     return true;
67767                 }
67768                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
67769                 if (!ts.length(tagCallSignatures)) {
67770                     return true;
67771                 }
67772                 var factory = getJsxFactoryEntity(node);
67773                 if (!factory) {
67774                     return true;
67775                 }
67776                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
67777                 if (!factorySymbol) {
67778                     return true;
67779                 }
67780                 var factoryType = getTypeOfSymbol(factorySymbol);
67781                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
67782                 if (!ts.length(callSignatures)) {
67783                     return true;
67784                 }
67785                 var hasFirstParamSignatures = false;
67786                 var maxParamCount = 0;
67787                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
67788                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
67789                     var sig = callSignatures_1[_i];
67790                     var firstparam = getTypeAtPosition(sig, 0);
67791                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
67792                     if (!ts.length(signaturesOfParam))
67793                         continue;
67794                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
67795                         var paramSig = signaturesOfParam_1[_b];
67796                         hasFirstParamSignatures = true;
67797                         if (hasEffectiveRestParameter(paramSig)) {
67798                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
67799                         }
67800                         var paramCount = getParameterCount(paramSig);
67801                         if (paramCount > maxParamCount) {
67802                             maxParamCount = paramCount;
67803                         }
67804                     }
67805                 }
67806                 if (!hasFirstParamSignatures) {
67807                     // Not a single signature had a first parameter which expected a signature - for back compat, and
67808                     // to guard against generic factories which won't have signatures directly, do not error
67809                     return true;
67810                 }
67811                 var absoluteMinArgCount = Infinity;
67812                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
67813                     var tagSig = tagCallSignatures_1[_c];
67814                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
67815                     if (tagRequiredArgCount < absoluteMinArgCount) {
67816                         absoluteMinArgCount = tagRequiredArgCount;
67817                     }
67818                 }
67819                 if (absoluteMinArgCount <= maxParamCount) {
67820                     return true; // some signature accepts the number of arguments the function component provides
67821                 }
67822                 if (reportErrors) {
67823                     var diag = ts.createDiagnosticForNode(node.tagName, ts.Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, ts.entityNameToString(node.tagName), absoluteMinArgCount, ts.entityNameToString(factory), maxParamCount);
67824                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
67825                     if (tagNameDeclaration) {
67826                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
67827                     }
67828                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
67829                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
67830                     }
67831                     if (!errorOutputContainer.skipLogging) {
67832                         diagnostics.add(diag);
67833                     }
67834                 }
67835                 return false;
67836             }
67837         }
67838         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
67839             var errorOutputContainer = { errors: undefined, skipLogging: true };
67840             if (ts.isJsxOpeningLikeElement(node)) {
67841                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
67842                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
67843                     return errorOutputContainer.errors || ts.emptyArray;
67844                 }
67845                 return undefined;
67846             }
67847             var thisType = getThisTypeOfSignature(signature);
67848             if (thisType && thisType !== voidType && node.kind !== 204 /* NewExpression */) {
67849                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
67850                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
67851                 // If the expression is a new expression, then the check is skipped.
67852                 var thisArgumentNode = getThisArgumentOfCall(node);
67853                 var thisArgumentType = void 0;
67854                 if (thisArgumentNode) {
67855                     thisArgumentType = checkExpression(thisArgumentNode);
67856                     if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
67857                         thisArgumentType = getNonNullableType(thisArgumentType);
67858                     }
67859                     else if (ts.isOptionalChain(thisArgumentNode.parent)) {
67860                         thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
67861                     }
67862                 }
67863                 else {
67864                     thisArgumentType = voidType;
67865                 }
67866                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
67867                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
67868                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
67869                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
67870                     return errorOutputContainer.errors || ts.emptyArray;
67871                 }
67872             }
67873             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
67874             var restType = getNonArrayRestType(signature);
67875             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
67876             for (var i = 0; i < argCount; i++) {
67877                 var arg = args[i];
67878                 if (arg.kind !== 222 /* OmittedExpression */) {
67879                     var paramType = getTypeAtPosition(signature, i);
67880                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
67881                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
67882                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
67883                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
67884                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
67885                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
67886                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
67887                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
67888                         return errorOutputContainer.errors || ts.emptyArray;
67889                     }
67890                 }
67891             }
67892             if (restType) {
67893                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined, checkMode);
67894                 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
67895                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
67896                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
67897                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
67898                     return errorOutputContainer.errors || ts.emptyArray;
67899                 }
67900             }
67901             return undefined;
67902             function maybeAddMissingAwaitInfo(errorNode, source, target) {
67903                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
67904                     // Bail if target is Promise-like---something else is wrong
67905                     if (getAwaitedTypeOfPromise(target)) {
67906                         return;
67907                     }
67908                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
67909                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
67910                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
67911                     }
67912                 }
67913             }
67914         }
67915         /**
67916          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
67917          */
67918         function getThisArgumentOfCall(node) {
67919             if (node.kind === 203 /* CallExpression */) {
67920                 var callee = ts.skipOuterExpressions(node.expression);
67921                 if (ts.isAccessExpression(callee)) {
67922                     return callee.expression;
67923                 }
67924             }
67925         }
67926         function createSyntheticExpression(parent, type, isSpread, tupleNameSource) {
67927             var result = ts.parseNodeFactory.createSyntheticExpression(type, isSpread, tupleNameSource);
67928             ts.setTextRange(result, parent);
67929             ts.setParent(result, parent);
67930             return result;
67931         }
67932         /**
67933          * Returns the effective arguments for an expression that works like a function invocation.
67934          */
67935         function getEffectiveCallArguments(node) {
67936             if (node.kind === 205 /* TaggedTemplateExpression */) {
67937                 var template = node.template;
67938                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
67939                 if (template.kind === 218 /* TemplateExpression */) {
67940                     ts.forEach(template.templateSpans, function (span) {
67941                         args_3.push(span.expression);
67942                     });
67943                 }
67944                 return args_3;
67945             }
67946             if (node.kind === 161 /* Decorator */) {
67947                 return getEffectiveDecoratorArguments(node);
67948             }
67949             if (ts.isJsxOpeningLikeElement(node)) {
67950                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
67951             }
67952             var args = node.arguments || ts.emptyArray;
67953             var spreadIndex = getSpreadArgumentIndex(args);
67954             if (spreadIndex >= 0) {
67955                 // Create synthetic arguments from spreads of tuple types.
67956                 var effectiveArgs_1 = args.slice(0, spreadIndex);
67957                 var _loop_20 = function (i) {
67958                     var arg = args[i];
67959                     // We can call checkExpressionCached because spread expressions never have a contextual type.
67960                     var spreadType = arg.kind === 220 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression));
67961                     if (spreadType && isTupleType(spreadType)) {
67962                         ts.forEach(getTypeArguments(spreadType), function (t, i) {
67963                             var _a;
67964                             var flags = spreadType.target.elementFlags[i];
67965                             var syntheticArg = createSyntheticExpression(arg, flags & 4 /* Rest */ ? createArrayType(t) : t, !!(flags & 12 /* Variable */), (_a = spreadType.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]);
67966                             effectiveArgs_1.push(syntheticArg);
67967                         });
67968                     }
67969                     else {
67970                         effectiveArgs_1.push(arg);
67971                     }
67972                 };
67973                 for (var i = spreadIndex; i < args.length; i++) {
67974                     _loop_20(i);
67975                 }
67976                 return effectiveArgs_1;
67977             }
67978             return args;
67979         }
67980         /**
67981          * Returns the synthetic argument list for a decorator invocation.
67982          */
67983         function getEffectiveDecoratorArguments(node) {
67984             var parent = node.parent;
67985             var expr = node.expression;
67986             switch (parent.kind) {
67987                 case 252 /* ClassDeclaration */:
67988                 case 221 /* ClassExpression */:
67989                     // For a class decorator, the `target` is the type of the class (e.g. the
67990                     // "static" or "constructor" side of the class).
67991                     return [
67992                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
67993                     ];
67994                 case 160 /* Parameter */:
67995                     // A parameter declaration decorator will have three arguments (see
67996                     // `ParameterDecorator` in core.d.ts).
67997                     var func = parent.parent;
67998                     return [
67999                         createSyntheticExpression(expr, parent.parent.kind === 166 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
68000                         createSyntheticExpression(expr, anyType),
68001                         createSyntheticExpression(expr, numberType)
68002                     ];
68003                 case 163 /* PropertyDeclaration */:
68004                 case 165 /* MethodDeclaration */:
68005                 case 167 /* GetAccessor */:
68006                 case 168 /* SetAccessor */:
68007                     // A method or accessor declaration decorator will have two or three arguments (see
68008                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
68009                     // for ES3, we will only pass two arguments.
68010                     var hasPropDesc = parent.kind !== 163 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
68011                     return [
68012                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
68013                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
68014                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
68015                     ];
68016             }
68017             return ts.Debug.fail();
68018         }
68019         /**
68020          * Returns the argument count for a decorator node that works like a function invocation.
68021          */
68022         function getDecoratorArgumentCount(node, signature) {
68023             switch (node.parent.kind) {
68024                 case 252 /* ClassDeclaration */:
68025                 case 221 /* ClassExpression */:
68026                     return 1;
68027                 case 163 /* PropertyDeclaration */:
68028                     return 2;
68029                 case 165 /* MethodDeclaration */:
68030                 case 167 /* GetAccessor */:
68031                 case 168 /* SetAccessor */:
68032                     // For ES3 or decorators with only two parameters we supply only two arguments
68033                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
68034                 case 160 /* Parameter */:
68035                     return 3;
68036                 default:
68037                     return ts.Debug.fail();
68038             }
68039         }
68040         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
68041             var start;
68042             var length;
68043             var sourceFile = ts.getSourceFileOfNode(node);
68044             if (ts.isPropertyAccessExpression(node.expression)) {
68045                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
68046                 start = nameSpan.start;
68047                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
68048             }
68049             else {
68050                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
68051                 start = expressionSpan.start;
68052                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
68053             }
68054             return { start: start, length: length, sourceFile: sourceFile };
68055         }
68056         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
68057             if (ts.isCallExpression(node)) {
68058                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
68059                 return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
68060             }
68061             else {
68062                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
68063             }
68064         }
68065         function isPromiseResolveArityError(node) {
68066             if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression))
68067                 return false;
68068             var symbol = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, undefined, undefined, false);
68069             var decl = symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration;
68070             if (!decl || !ts.isParameter(decl) || !isFunctionExpressionOrArrowFunction(decl.parent) || !ts.isNewExpression(decl.parent.parent) || !ts.isIdentifier(decl.parent.parent.expression)) {
68071                 return false;
68072             }
68073             var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
68074             if (!globalPromiseSymbol)
68075                 return false;
68076             var constructorSymbol = getSymbolAtLocation(decl.parent.parent.expression, /*ignoreErrors*/ true);
68077             return constructorSymbol === globalPromiseSymbol;
68078         }
68079         function getArgumentArityError(node, signatures, args) {
68080             var min = Number.POSITIVE_INFINITY;
68081             var max = Number.NEGATIVE_INFINITY;
68082             var belowArgCount = Number.NEGATIVE_INFINITY;
68083             var aboveArgCount = Number.POSITIVE_INFINITY;
68084             var argCount = args.length;
68085             var closestSignature;
68086             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
68087                 var sig = signatures_8[_i];
68088                 var minCount = getMinArgumentCount(sig);
68089                 var maxCount = getParameterCount(sig);
68090                 if (minCount < argCount && minCount > belowArgCount)
68091                     belowArgCount = minCount;
68092                 if (argCount < maxCount && maxCount < aboveArgCount)
68093                     aboveArgCount = maxCount;
68094                 if (minCount < min) {
68095                     min = minCount;
68096                     closestSignature = sig;
68097                 }
68098                 max = Math.max(max, maxCount);
68099             }
68100             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
68101             var paramRange = hasRestParameter ? min :
68102                 min < max ? min + "-" + max :
68103                     min;
68104             var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
68105             if (argCount <= max && hasSpreadArgument) {
68106                 argCount--;
68107             }
68108             var spanArray;
68109             var related;
68110             var error = hasRestParameter || hasSpreadArgument ?
68111                 hasRestParameter && hasSpreadArgument ?
68112                     ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
68113                     hasRestParameter ?
68114                         ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
68115                         ts.Diagnostics.Expected_0_arguments_but_got_1_or_more :
68116                 paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ?
68117                     ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise :
68118                     ts.Diagnostics.Expected_0_arguments_but_got_1;
68119             if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
68120                 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
68121                 if (paramDecl) {
68122                     related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided :
68123                         ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined);
68124                 }
68125             }
68126             if (min < argCount && argCount < max) {
68127                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
68128             }
68129             if (!hasSpreadArgument && argCount < min) {
68130                 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
68131                 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
68132             }
68133             if (hasRestParameter || hasSpreadArgument) {
68134                 spanArray = ts.factory.createNodeArray(args);
68135                 if (hasSpreadArgument && argCount) {
68136                     var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
68137                     spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
68138                 }
68139             }
68140             else {
68141                 spanArray = ts.factory.createNodeArray(args.slice(max));
68142             }
68143             var pos = ts.first(spanArray).pos;
68144             var end = ts.last(spanArray).end;
68145             if (end === pos) {
68146                 end++;
68147             }
68148             ts.setTextRangePosEnd(spanArray, pos, end);
68149             var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
68150             return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
68151         }
68152         function getTypeArgumentArityError(node, signatures, typeArguments) {
68153             var argCount = typeArguments.length;
68154             // No overloads exist
68155             if (signatures.length === 1) {
68156                 var sig = signatures[0];
68157                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
68158                 var max = ts.length(sig.typeParameters);
68159                 return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount);
68160             }
68161             // Overloads exist
68162             var belowArgCount = -Infinity;
68163             var aboveArgCount = Infinity;
68164             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
68165                 var sig = signatures_9[_i];
68166                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
68167                 var max = ts.length(sig.typeParameters);
68168                 if (min_2 > argCount) {
68169                     aboveArgCount = Math.min(aboveArgCount, min_2);
68170                 }
68171                 else if (max < argCount) {
68172                     belowArgCount = Math.max(belowArgCount, max);
68173                 }
68174             }
68175             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
68176                 return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount);
68177             }
68178             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
68179         }
68180         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
68181             var isTaggedTemplate = node.kind === 205 /* TaggedTemplateExpression */;
68182             var isDecorator = node.kind === 161 /* Decorator */;
68183             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
68184             var reportErrors = !candidatesOutArray && produceDiagnostics;
68185             var typeArguments;
68186             if (!isDecorator) {
68187                 typeArguments = node.typeArguments;
68188                 // We already perform checking on the type arguments on the class declaration itself.
68189                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 105 /* SuperKeyword */) {
68190                     ts.forEach(typeArguments, checkSourceElement);
68191                 }
68192             }
68193             var candidates = candidatesOutArray || [];
68194             // reorderCandidates fills up the candidates array directly
68195             reorderCandidates(signatures, candidates, callChainFlags);
68196             if (!candidates.length) {
68197                 if (reportErrors) {
68198                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
68199                 }
68200                 return resolveErrorCall(node);
68201             }
68202             var args = getEffectiveCallArguments(node);
68203             // The excludeArgument array contains true for each context sensitive argument (an argument
68204             // is context sensitive it is susceptible to a one-time permanent contextual typing).
68205             //
68206             // The idea is that we will perform type argument inference & assignability checking once
68207             // without using the susceptible parameters that are functions, and once more for those
68208             // parameters, contextually typing each as we go along.
68209             //
68210             // For a tagged template, then the first argument be 'undefined' if necessary because it
68211             // represents a TemplateStringsArray.
68212             //
68213             // For a decorator, no arguments are susceptible to contextual typing due to the fact
68214             // decorators are applied to a declaration by the emitter, and not to an expression.
68215             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
68216             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
68217             // The following variables are captured and modified by calls to chooseOverload.
68218             // If overload resolution or type argument inference fails, we want to report the
68219             // best error possible. The best error is one which says that an argument was not
68220             // assignable to a parameter. This implies that everything else about the overload
68221             // was fine. So if there is any overload that is only incorrect because of an
68222             // argument, we will report an error on that one.
68223             //
68224             //     function foo(s: string): void;
68225             //     function foo(n: number): void; // Report argument error on this overload
68226             //     function foo(): void;
68227             //     foo(true);
68228             //
68229             // If none of the overloads even made it that far, there are two possibilities.
68230             // There was a problem with type arguments for some overload, in which case
68231             // report an error on that. Or none of the overloads even had correct arity,
68232             // in which case give an arity error.
68233             //
68234             //     function foo<T extends string>(x: T): void; // Report type argument error
68235             //     function foo(): void;
68236             //     foo<number>(0);
68237             //
68238             var candidatesForArgumentError;
68239             var candidateForArgumentArityError;
68240             var candidateForTypeArgumentError;
68241             var result;
68242             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
68243             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
68244             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 203 /* CallExpression */ && node.arguments.hasTrailingComma;
68245             // Section 4.12.1:
68246             // if the candidate list contains one or more signatures for which the type of each argument
68247             // expression is a subtype of each corresponding parameter type, the return type of the first
68248             // of those signatures becomes the return type of the function call.
68249             // Otherwise, the return type of the first signature in the candidate list becomes the return
68250             // type of the function call.
68251             //
68252             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
68253             // is just important for choosing the best signature. So in the case where there is only one
68254             // signature, the subtype pass is useless. So skipping it is an optimization.
68255             if (candidates.length > 1) {
68256                 result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
68257             }
68258             if (!result) {
68259                 result = chooseOverload(candidates, assignableRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
68260             }
68261             if (result) {
68262                 return result;
68263             }
68264             // No signatures were applicable. Now report errors based on the last applicable signature with
68265             // no arguments excluded from assignability checks.
68266             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
68267             // skip the checkApplicableSignature check.
68268             if (reportErrors) {
68269                 if (candidatesForArgumentError) {
68270                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
68271                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
68272                         var chain_1;
68273                         if (candidatesForArgumentError.length > 3) {
68274                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
68275                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
68276                         }
68277                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
68278                         if (diags) {
68279                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
68280                                 var d = diags_1[_i];
68281                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
68282                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
68283                                 }
68284                                 addImplementationSuccessElaboration(last_2, d);
68285                                 diagnostics.add(d);
68286                             }
68287                         }
68288                         else {
68289                             ts.Debug.fail("No error for last overload signature");
68290                         }
68291                     }
68292                     else {
68293                         var allDiagnostics = [];
68294                         var max = 0;
68295                         var min_3 = Number.MAX_VALUE;
68296                         var minIndex = 0;
68297                         var i_1 = 0;
68298                         var _loop_21 = function (c) {
68299                             var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); };
68300                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
68301                             if (diags_2) {
68302                                 if (diags_2.length <= min_3) {
68303                                     min_3 = diags_2.length;
68304                                     minIndex = i_1;
68305                                 }
68306                                 max = Math.max(max, diags_2.length);
68307                                 allDiagnostics.push(diags_2);
68308                             }
68309                             else {
68310                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
68311                             }
68312                             i_1++;
68313                         };
68314                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
68315                             var c = candidatesForArgumentError_1[_a];
68316                             _loop_21(c);
68317                         }
68318                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
68319                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
68320                         var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call);
68321                         // The below is a spread to guarantee we get a new (mutable) array - our `flatMap` helper tries to do "smart" optimizations where it reuses input
68322                         // arrays and the emptyArray singleton where possible, which is decidedly not what we want while we're still constructing this diagnostic
68323                         var related = __spreadArrays(ts.flatMap(diags_3, function (d) { return d.relatedInformation; }));
68324                         var diag = void 0;
68325                         if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) {
68326                             var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
68327                             diag = { file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related };
68328                         }
68329                         else {
68330                             diag = ts.createDiagnosticForNodeFromMessageChain(node, chain, related);
68331                         }
68332                         addImplementationSuccessElaboration(candidatesForArgumentError[0], diag);
68333                         diagnostics.add(diag);
68334                     }
68335                 }
68336                 else if (candidateForArgumentArityError) {
68337                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
68338                 }
68339                 else if (candidateForTypeArgumentError) {
68340                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
68341                 }
68342                 else {
68343                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
68344                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
68345                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
68346                     }
68347                     else if (!isDecorator) {
68348                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
68349                     }
68350                     else if (fallbackError) {
68351                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
68352                     }
68353                 }
68354             }
68355             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
68356             function addImplementationSuccessElaboration(failed, diagnostic) {
68357                 var _a, _b;
68358                 var oldCandidatesForArgumentError = candidatesForArgumentError;
68359                 var oldCandidateForArgumentArityError = candidateForArgumentArityError;
68360                 var oldCandidateForTypeArgumentError = candidateForTypeArgumentError;
68361                 var failedSignatureDeclarations = ((_b = (_a = failed.declaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.declarations) || ts.emptyArray;
68362                 var isOverload = failedSignatureDeclarations.length > 1;
68363                 var implDecl = isOverload ? ts.find(failedSignatureDeclarations, function (d) { return ts.isFunctionLikeDeclaration(d) && ts.nodeIsPresent(d.body); }) : undefined;
68364                 if (implDecl) {
68365                     var candidate = getSignatureFromDeclaration(implDecl);
68366                     var isSingleNonGenericCandidate_1 = !candidate.typeParameters;
68367                     if (chooseOverload([candidate], assignableRelation, isSingleNonGenericCandidate_1)) {
68368                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(implDecl, ts.Diagnostics.The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_are_not_externally_visible));
68369                     }
68370                 }
68371                 candidatesForArgumentError = oldCandidatesForArgumentError;
68372                 candidateForArgumentArityError = oldCandidateForArgumentArityError;
68373                 candidateForTypeArgumentError = oldCandidateForTypeArgumentError;
68374             }
68375             function chooseOverload(candidates, relation, isSingleNonGenericCandidate, signatureHelpTrailingComma) {
68376                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
68377                 candidatesForArgumentError = undefined;
68378                 candidateForArgumentArityError = undefined;
68379                 candidateForTypeArgumentError = undefined;
68380                 if (isSingleNonGenericCandidate) {
68381                     var candidate = candidates[0];
68382                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
68383                         return undefined;
68384                     }
68385                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
68386                         candidatesForArgumentError = [candidate];
68387                         return undefined;
68388                     }
68389                     return candidate;
68390                 }
68391                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
68392                     var candidate = candidates[candidateIndex];
68393                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
68394                         continue;
68395                     }
68396                     var checkCandidate = void 0;
68397                     var inferenceContext = void 0;
68398                     if (candidate.typeParameters) {
68399                         var typeArgumentTypes = void 0;
68400                         if (ts.some(typeArguments)) {
68401                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
68402                             if (!typeArgumentTypes) {
68403                                 candidateForTypeArgumentError = candidate;
68404                                 continue;
68405                             }
68406                         }
68407                         else {
68408                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
68409                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
68410                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
68411                         }
68412                         checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
68413                         // If the original signature has a generic rest type, instantiation may produce a
68414                         // signature with different arity and we need to perform another arity check.
68415                         if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
68416                             candidateForArgumentArityError = checkCandidate;
68417                             continue;
68418                         }
68419                     }
68420                     else {
68421                         checkCandidate = candidate;
68422                     }
68423                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
68424                         // Give preference to error candidates that have no rest parameters (as they are more specific)
68425                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
68426                         continue;
68427                     }
68428                     if (argCheckMode) {
68429                         // If one or more context sensitive arguments were excluded, we start including
68430                         // them now (and keeping do so for any subsequent candidates) and perform a second
68431                         // round of type inference and applicability checking for this particular candidate.
68432                         argCheckMode = 0 /* Normal */;
68433                         if (inferenceContext) {
68434                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
68435                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
68436                             // If the original signature has a generic rest type, instantiation may produce a
68437                             // signature with different arity and we need to perform another arity check.
68438                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
68439                                 candidateForArgumentArityError = checkCandidate;
68440                                 continue;
68441                             }
68442                         }
68443                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
68444                             // Give preference to error candidates that have no rest parameters (as they are more specific)
68445                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
68446                             continue;
68447                         }
68448                     }
68449                     candidates[candidateIndex] = checkCandidate;
68450                     return checkCandidate;
68451                 }
68452                 return undefined;
68453             }
68454         }
68455         // No signature was applicable. We have already reported the errors for the invalid signature.
68456         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
68457             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
68458             checkNodeDeferred(node);
68459             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
68460             // Don't do this if there is a `candidatesOutArray`,
68461             // because then we want the chosen best candidate to be one of the overloads, not a combination.
68462             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
68463                 ? pickLongestCandidateSignature(node, candidates, args)
68464                 : createUnionOfSignaturesForOverloadFailure(candidates);
68465         }
68466         function createUnionOfSignaturesForOverloadFailure(candidates) {
68467             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
68468             var thisParameter;
68469             if (thisParameters.length) {
68470                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
68471             }
68472             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
68473             var parameters = [];
68474             var _loop_22 = function (i) {
68475                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
68476                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
68477                     i < s.parameters.length ? s.parameters[i] : undefined; });
68478                 ts.Debug.assert(symbols.length !== 0);
68479                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
68480             };
68481             for (var i = 0; i < maxNonRestParam; i++) {
68482                 _loop_22(i);
68483             }
68484             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
68485             var flags = 0 /* None */;
68486             if (restParameterSymbols.length !== 0) {
68487                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
68488                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
68489                 flags |= 1 /* HasRestParameter */;
68490             }
68491             if (candidates.some(signatureHasLiteralTypes)) {
68492                 flags |= 2 /* HasLiteralTypes */;
68493             }
68494             return createSignature(candidates[0].declaration, 
68495             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
68496             thisParameter, parameters, 
68497             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
68498             /*typePredicate*/ undefined, minArgumentCount, flags);
68499         }
68500         function getNumNonRestParameters(signature) {
68501             var numParams = signature.parameters.length;
68502             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
68503         }
68504         function createCombinedSymbolFromTypes(sources, types) {
68505             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
68506         }
68507         function createCombinedSymbolForOverloadFailure(sources, type) {
68508             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
68509             return createSymbolWithType(ts.first(sources), type);
68510         }
68511         function pickLongestCandidateSignature(node, candidates, args) {
68512             // Pick the longest signature. This way we can get a contextual type for cases like:
68513             //     declare function f(a: { xa: number; xb: number; }, b: number);
68514             //     f({ |
68515             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
68516             //     declare function f<T>(k: keyof T);
68517             //     f<Foo>("
68518             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
68519             var candidate = candidates[bestIndex];
68520             var typeParameters = candidate.typeParameters;
68521             if (!typeParameters) {
68522                 return candidate;
68523             }
68524             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
68525             var instantiated = typeArgumentNodes
68526                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
68527                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
68528             candidates[bestIndex] = instantiated;
68529             return instantiated;
68530         }
68531         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
68532             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
68533             while (typeArguments.length > typeParameters.length) {
68534                 typeArguments.pop();
68535             }
68536             while (typeArguments.length < typeParameters.length) {
68537                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
68538             }
68539             return typeArguments;
68540         }
68541         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
68542             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
68543             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
68544             return createSignatureInstantiation(candidate, typeArgumentTypes);
68545         }
68546         function getLongestCandidateIndex(candidates, argsCount) {
68547             var maxParamsIndex = -1;
68548             var maxParams = -1;
68549             for (var i = 0; i < candidates.length; i++) {
68550                 var candidate = candidates[i];
68551                 var paramCount = getParameterCount(candidate);
68552                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
68553                     return i;
68554                 }
68555                 if (paramCount > maxParams) {
68556                     maxParams = paramCount;
68557                     maxParamsIndex = i;
68558                 }
68559             }
68560             return maxParamsIndex;
68561         }
68562         function resolveCallExpression(node, candidatesOutArray, checkMode) {
68563             if (node.expression.kind === 105 /* SuperKeyword */) {
68564                 var superType = checkSuperExpression(node.expression);
68565                 if (isTypeAny(superType)) {
68566                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
68567                         var arg = _a[_i];
68568                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
68569                     }
68570                     return anySignature;
68571                 }
68572                 if (superType !== errorType) {
68573                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
68574                     // with the type arguments specified in the extends clause.
68575                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
68576                     if (baseTypeNode) {
68577                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
68578                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
68579                     }
68580                 }
68581                 return resolveUntypedCall(node);
68582             }
68583             var callChainFlags;
68584             var funcType = checkExpression(node.expression);
68585             if (ts.isCallChain(node)) {
68586                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
68587                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
68588                     ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
68589                         4 /* IsInnerCallChain */;
68590                 funcType = nonOptionalType;
68591             }
68592             else {
68593                 callChainFlags = 0 /* None */;
68594             }
68595             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
68596             if (funcType === silentNeverType) {
68597                 return silentNeverSignature;
68598             }
68599             var apparentType = getApparentType(funcType);
68600             if (apparentType === errorType) {
68601                 // Another error has already been reported
68602                 return resolveErrorCall(node);
68603             }
68604             // Technically, this signatures list may be incomplete. We are taking the apparent type,
68605             // but we are not including call signatures that may have been added to the Object or
68606             // Function interface, since they have none by default. This is a bit of a leap of faith
68607             // that the user will not add any.
68608             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
68609             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
68610             // TS 1.0 Spec: 4.12
68611             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
68612             // types are provided for the argument expressions, and the result is always of type Any.
68613             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
68614                 // The unknownType indicates that an error already occurred (and was reported).  No
68615                 // need to report another error in this case.
68616                 if (funcType !== errorType && node.typeArguments) {
68617                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
68618                 }
68619                 return resolveUntypedCall(node);
68620             }
68621             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
68622             // TypeScript employs overload resolution in typed function calls in order to support functions
68623             // with multiple call signatures.
68624             if (!callSignatures.length) {
68625                 if (numConstructSignatures) {
68626                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
68627                 }
68628                 else {
68629                     var relatedInformation = void 0;
68630                     if (node.arguments.length === 1) {
68631                         var text = ts.getSourceFileOfNode(node).text;
68632                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
68633                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
68634                         }
68635                     }
68636                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
68637                 }
68638                 return resolveErrorCall(node);
68639             }
68640             // When a call to a generic function is an argument to an outer call to a generic function for which
68641             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
68642             // its contextual type to its return type, deferring the inner call processing allows the best possible
68643             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
68644             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
68645             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
68646             // If no type arguments are specified in the inner call and at least one call signature is generic and
68647             // returns a function type, we choose to defer processing. This narrowly permits function composition
68648             // operators to flow inferences through return types, but otherwise processes calls right away. We
68649             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
68650             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
68651             // from which we never make inferences).
68652             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
68653                 skippedGenericFunction(node, checkMode);
68654                 return resolvingSignature;
68655             }
68656             // If the function is explicitly marked with `@class`, then it must be constructed.
68657             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
68658                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
68659                 return resolveErrorCall(node);
68660             }
68661             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
68662         }
68663         function isGenericFunctionReturningFunction(signature) {
68664             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
68665         }
68666         /**
68667          * TS 1.0 spec: 4.12
68668          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
68669          * but is a subtype of the Function interface, the call is an untyped function call.
68670          */
68671         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
68672             // We exclude union types because we may have a union of function types that happen to have no common signatures.
68673             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
68674                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
68675         }
68676         function resolveNewExpression(node, candidatesOutArray, checkMode) {
68677             if (node.arguments && languageVersion < 1 /* ES5 */) {
68678                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
68679                 if (spreadIndex >= 0) {
68680                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
68681                 }
68682             }
68683             var expressionType = checkNonNullExpression(node.expression);
68684             if (expressionType === silentNeverType) {
68685                 return silentNeverSignature;
68686             }
68687             // If expressionType's apparent type(section 3.8.1) is an object type with one or
68688             // more construct signatures, the expression is processed in the same manner as a
68689             // function call, but using the construct signatures as the initial set of candidate
68690             // signatures for overload resolution. The result type of the function call becomes
68691             // the result type of the operation.
68692             expressionType = getApparentType(expressionType);
68693             if (expressionType === errorType) {
68694                 // Another error has already been reported
68695                 return resolveErrorCall(node);
68696             }
68697             // TS 1.0 spec: 4.11
68698             // If expressionType is of type Any, Args can be any argument
68699             // list and the result of the operation is of type Any.
68700             if (isTypeAny(expressionType)) {
68701                 if (node.typeArguments) {
68702                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
68703                 }
68704                 return resolveUntypedCall(node);
68705             }
68706             // Technically, this signatures list may be incomplete. We are taking the apparent type,
68707             // but we are not including construct signatures that may have been added to the Object or
68708             // Function interface, since they have none by default. This is a bit of a leap of faith
68709             // that the user will not add any.
68710             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
68711             if (constructSignatures.length) {
68712                 if (!isConstructorAccessible(node, constructSignatures[0])) {
68713                     return resolveErrorCall(node);
68714                 }
68715                 // If the expression is a class of abstract type, then it cannot be instantiated.
68716                 // Note, only class declarations can be declared abstract.
68717                 // In the case of a merged class-module or class-interface declaration,
68718                 // only the class declaration node will have the Abstract flag set.
68719                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
68720                 if (valueDecl && ts.hasSyntacticModifier(valueDecl, 128 /* Abstract */)) {
68721                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
68722                     return resolveErrorCall(node);
68723                 }
68724                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
68725             }
68726             // If expressionType's apparent type is an object type with no construct signatures but
68727             // one or more call signatures, the expression is processed as a function call. A compile-time
68728             // error occurs if the result of the function call is not Void. The type of the result of the
68729             // operation is Any. It is an error to have a Void this type.
68730             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
68731             if (callSignatures.length) {
68732                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
68733                 if (!noImplicitAny) {
68734                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
68735                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
68736                     }
68737                     if (getThisTypeOfSignature(signature) === voidType) {
68738                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
68739                     }
68740                 }
68741                 return signature;
68742             }
68743             invocationError(node.expression, expressionType, 1 /* Construct */);
68744             return resolveErrorCall(node);
68745         }
68746         function typeHasProtectedAccessibleBase(target, type) {
68747             var baseTypes = getBaseTypes(type);
68748             if (!ts.length(baseTypes)) {
68749                 return false;
68750             }
68751             var firstBase = baseTypes[0];
68752             if (firstBase.flags & 2097152 /* Intersection */) {
68753                 var types = firstBase.types;
68754                 var mixinFlags = findMixins(types);
68755                 var i = 0;
68756                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
68757                     var intersectionMember = _a[_i];
68758                     // We want to ignore mixin ctors
68759                     if (!mixinFlags[i]) {
68760                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
68761                             if (intersectionMember.symbol === target) {
68762                                 return true;
68763                             }
68764                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
68765                                 return true;
68766                             }
68767                         }
68768                     }
68769                     i++;
68770                 }
68771                 return false;
68772             }
68773             if (firstBase.symbol === target) {
68774                 return true;
68775             }
68776             return typeHasProtectedAccessibleBase(target, firstBase);
68777         }
68778         function isConstructorAccessible(node, signature) {
68779             if (!signature || !signature.declaration) {
68780                 return true;
68781             }
68782             var declaration = signature.declaration;
68783             var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
68784             // (1) Public constructors and (2) constructor functions are always accessible.
68785             if (!modifiers || declaration.kind !== 166 /* Constructor */) {
68786                 return true;
68787             }
68788             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
68789             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
68790             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
68791             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
68792                 var containingClass = ts.getContainingClass(node);
68793                 if (containingClass && modifiers & 16 /* Protected */) {
68794                     var containingType = getTypeOfNode(containingClass);
68795                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
68796                         return true;
68797                     }
68798                 }
68799                 if (modifiers & 8 /* Private */) {
68800                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
68801                 }
68802                 if (modifiers & 16 /* Protected */) {
68803                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
68804                 }
68805                 return false;
68806             }
68807             return true;
68808         }
68809         function invocationErrorDetails(errorTarget, apparentType, kind) {
68810             var errorInfo;
68811             var isCall = kind === 0 /* Call */;
68812             var awaitedType = getAwaitedType(apparentType);
68813             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
68814             if (apparentType.flags & 1048576 /* Union */) {
68815                 var types = apparentType.types;
68816                 var hasSignatures = false;
68817                 for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
68818                     var constituent = types_19[_i];
68819                     var signatures = getSignaturesOfType(constituent, kind);
68820                     if (signatures.length !== 0) {
68821                         hasSignatures = true;
68822                         if (errorInfo) {
68823                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
68824                             break;
68825                         }
68826                     }
68827                     else {
68828                         // Error on the first non callable constituent only
68829                         if (!errorInfo) {
68830                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
68831                                 ts.Diagnostics.Type_0_has_no_call_signatures :
68832                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
68833                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
68834                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
68835                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
68836                         }
68837                         if (hasSignatures) {
68838                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
68839                             break;
68840                         }
68841                     }
68842                 }
68843                 if (!hasSignatures) {
68844                     errorInfo = ts.chainDiagnosticMessages(
68845                     /* detials */ undefined, isCall ?
68846                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
68847                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
68848                 }
68849                 if (!errorInfo) {
68850                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
68851                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
68852                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
68853                 }
68854             }
68855             else {
68856                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
68857                     ts.Diagnostics.Type_0_has_no_call_signatures :
68858                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
68859             }
68860             var headMessage = isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable;
68861             // Diagnose get accessors incorrectly called as functions
68862             if (ts.isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) {
68863                 var resolvedSymbol = getNodeLinks(errorTarget).resolvedSymbol;
68864                 if (resolvedSymbol && resolvedSymbol.flags & 32768 /* GetAccessor */) {
68865                     headMessage = ts.Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without;
68866                 }
68867             }
68868             return {
68869                 messageChain: ts.chainDiagnosticMessages(errorInfo, headMessage),
68870                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
68871             };
68872         }
68873         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
68874             var _a = invocationErrorDetails(errorTarget, apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
68875             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
68876             if (relatedInfo) {
68877                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
68878             }
68879             if (ts.isCallExpression(errorTarget.parent)) {
68880                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
68881                 diagnostic.start = start;
68882                 diagnostic.length = length_7;
68883             }
68884             diagnostics.add(diagnostic);
68885             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
68886         }
68887         function invocationErrorRecovery(apparentType, kind, diagnostic) {
68888             if (!apparentType.symbol) {
68889                 return;
68890             }
68891             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
68892             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
68893             //  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
68894             if (importNode && !ts.isImportCall(importNode)) {
68895                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
68896                 if (!sigs || !sigs.length)
68897                     return;
68898                 ts.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));
68899             }
68900         }
68901         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
68902             var tagType = checkExpression(node.tag);
68903             var apparentType = getApparentType(tagType);
68904             if (apparentType === errorType) {
68905                 // Another error has already been reported
68906                 return resolveErrorCall(node);
68907             }
68908             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
68909             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
68910             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
68911                 return resolveUntypedCall(node);
68912             }
68913             if (!callSignatures.length) {
68914                 if (ts.isArrayLiteralExpression(node.parent)) {
68915                     var diagnostic = ts.createDiagnosticForNode(node.tag, ts.Diagnostics.It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked);
68916                     diagnostics.add(diagnostic);
68917                     return resolveErrorCall(node);
68918                 }
68919                 invocationError(node.tag, apparentType, 0 /* Call */);
68920                 return resolveErrorCall(node);
68921             }
68922             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
68923         }
68924         /**
68925          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
68926          */
68927         function getDiagnosticHeadMessageForDecoratorResolution(node) {
68928             switch (node.parent.kind) {
68929                 case 252 /* ClassDeclaration */:
68930                 case 221 /* ClassExpression */:
68931                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
68932                 case 160 /* Parameter */:
68933                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
68934                 case 163 /* PropertyDeclaration */:
68935                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
68936                 case 165 /* MethodDeclaration */:
68937                 case 167 /* GetAccessor */:
68938                 case 168 /* SetAccessor */:
68939                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
68940                 default:
68941                     return ts.Debug.fail();
68942             }
68943         }
68944         /**
68945          * Resolves a decorator as if it were a call expression.
68946          */
68947         function resolveDecorator(node, candidatesOutArray, checkMode) {
68948             var funcType = checkExpression(node.expression);
68949             var apparentType = getApparentType(funcType);
68950             if (apparentType === errorType) {
68951                 return resolveErrorCall(node);
68952             }
68953             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
68954             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
68955             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
68956                 return resolveUntypedCall(node);
68957             }
68958             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
68959                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
68960                 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);
68961                 return resolveErrorCall(node);
68962             }
68963             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
68964             if (!callSignatures.length) {
68965                 var errorDetails = invocationErrorDetails(node.expression, apparentType, 0 /* Call */);
68966                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
68967                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
68968                 if (errorDetails.relatedMessage) {
68969                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
68970                 }
68971                 diagnostics.add(diag);
68972                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
68973                 return resolveErrorCall(node);
68974             }
68975             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
68976         }
68977         function createSignatureForJSXIntrinsic(node, result) {
68978             var namespace = getJsxNamespaceAt(node);
68979             var exports = namespace && getExportsOfSymbol(namespace);
68980             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
68981             // file would probably be preferable.
68982             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
68983             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
68984             var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
68985             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
68986             parameterSymbol.type = result;
68987             return createSignature(declaration, 
68988             /*typeParameters*/ undefined, 
68989             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
68990             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
68991         }
68992         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
68993             if (isJsxIntrinsicIdentifier(node.tagName)) {
68994                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
68995                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
68996                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
68997                 if (ts.length(node.typeArguments)) {
68998                     ts.forEach(node.typeArguments, checkSourceElement);
68999                     diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), node.typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, 0, ts.length(node.typeArguments)));
69000                 }
69001                 return fakeSignature;
69002             }
69003             var exprTypes = checkExpression(node.tagName);
69004             var apparentType = getApparentType(exprTypes);
69005             if (apparentType === errorType) {
69006                 return resolveErrorCall(node);
69007             }
69008             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
69009             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
69010                 return resolveUntypedCall(node);
69011             }
69012             if (signatures.length === 0) {
69013                 // We found no signatures at all, which is an error
69014                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
69015                 return resolveErrorCall(node);
69016             }
69017             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
69018         }
69019         /**
69020          * Sometimes, we have a decorator that could accept zero arguments,
69021          * but is receiving too many arguments as part of the decorator invocation.
69022          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
69023          */
69024         function isPotentiallyUncalledDecorator(decorator, signatures) {
69025             return signatures.length && ts.every(signatures, function (signature) {
69026                 return signature.minArgumentCount === 0 &&
69027                     !signatureHasRestParameter(signature) &&
69028                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
69029             });
69030         }
69031         function resolveSignature(node, candidatesOutArray, checkMode) {
69032             switch (node.kind) {
69033                 case 203 /* CallExpression */:
69034                     return resolveCallExpression(node, candidatesOutArray, checkMode);
69035                 case 204 /* NewExpression */:
69036                     return resolveNewExpression(node, candidatesOutArray, checkMode);
69037                 case 205 /* TaggedTemplateExpression */:
69038                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
69039                 case 161 /* Decorator */:
69040                     return resolveDecorator(node, candidatesOutArray, checkMode);
69041                 case 275 /* JsxOpeningElement */:
69042                 case 274 /* JsxSelfClosingElement */:
69043                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
69044             }
69045             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
69046         }
69047         /**
69048          * Resolve a signature of a given call-like expression.
69049          * @param node a call-like expression to try resolve a signature for
69050          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
69051          *                           the function will fill it up with appropriate candidate signatures
69052          * @return a signature of the call-like expression or undefined if one can't be found
69053          */
69054         function getResolvedSignature(node, candidatesOutArray, checkMode) {
69055             var links = getNodeLinks(node);
69056             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
69057             // However, it is possible that either candidatesOutArray was not passed in the first time,
69058             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
69059             // to correctly fill the candidatesOutArray.
69060             var cached = links.resolvedSignature;
69061             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
69062                 return cached;
69063             }
69064             links.resolvedSignature = resolvingSignature;
69065             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
69066             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
69067             // resolution should be deferred.
69068             if (result !== resolvingSignature) {
69069                 // If signature resolution originated in control flow type analysis (for example to compute the
69070                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
69071                 // types from the control flow analysis.
69072                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
69073             }
69074             return result;
69075         }
69076         /**
69077          * Indicates whether a declaration can be treated as a constructor in a JavaScript
69078          * file.
69079          */
69080         function isJSConstructor(node) {
69081             var _a;
69082             if (!node || !ts.isInJSFile(node)) {
69083                 return false;
69084             }
69085             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
69086                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
69087                     undefined;
69088             if (func) {
69089                 // If the node has a @class tag, treat it like a constructor.
69090                 if (ts.getJSDocClassTag(node))
69091                     return true;
69092                 // If the symbol of the node has members, treat it like a constructor.
69093                 var symbol = getSymbolOfNode(func);
69094                 return !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.members) === null || _a === void 0 ? void 0 : _a.size);
69095             }
69096             return false;
69097         }
69098         function mergeJSSymbols(target, source) {
69099             var _a, _b;
69100             if (source) {
69101                 var links = getSymbolLinks(source);
69102                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has(getSymbolId(target))) {
69103                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
69104                     inferred.exports = inferred.exports || ts.createSymbolTable();
69105                     inferred.members = inferred.members || ts.createSymbolTable();
69106                     inferred.flags |= source.flags & 32 /* Class */;
69107                     if ((_a = source.exports) === null || _a === void 0 ? void 0 : _a.size) {
69108                         mergeSymbolTable(inferred.exports, source.exports);
69109                     }
69110                     if ((_b = source.members) === null || _b === void 0 ? void 0 : _b.size) {
69111                         mergeSymbolTable(inferred.members, source.members);
69112                     }
69113                     (links.inferredClassSymbol || (links.inferredClassSymbol = new ts.Map())).set(getSymbolId(inferred), inferred);
69114                     return inferred;
69115                 }
69116                 return links.inferredClassSymbol.get(getSymbolId(target));
69117             }
69118         }
69119         function getAssignedClassSymbol(decl) {
69120             var _a;
69121             var assignmentSymbol = decl && getSymbolOfExpando(decl, /*allowDeclaration*/ true);
69122             var prototype = (_a = assignmentSymbol === null || assignmentSymbol === void 0 ? void 0 : assignmentSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("prototype");
69123             var init = (prototype === null || prototype === void 0 ? void 0 : prototype.valueDeclaration) && getAssignedJSPrototype(prototype.valueDeclaration);
69124             return init ? getSymbolOfNode(init) : undefined;
69125         }
69126         function getSymbolOfExpando(node, allowDeclaration) {
69127             if (!node.parent) {
69128                 return undefined;
69129             }
69130             var name;
69131             var decl;
69132             if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
69133                 if (!ts.isInJSFile(node) && !(ts.isVarConst(node.parent) && ts.isFunctionLikeDeclaration(node))) {
69134                     return undefined;
69135                 }
69136                 name = node.parent.name;
69137                 decl = node.parent;
69138             }
69139             else if (ts.isBinaryExpression(node.parent)) {
69140                 var parentNode = node.parent;
69141                 var parentNodeOperator = node.parent.operatorToken.kind;
69142                 if (parentNodeOperator === 62 /* EqualsToken */ && (allowDeclaration || parentNode.right === node)) {
69143                     name = parentNode.left;
69144                     decl = name;
69145                 }
69146                 else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
69147                     if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
69148                         name = parentNode.parent.name;
69149                         decl = parentNode.parent;
69150                     }
69151                     else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && (allowDeclaration || parentNode.parent.right === parentNode)) {
69152                         name = parentNode.parent.left;
69153                         decl = name;
69154                     }
69155                     if (!name || !ts.isBindableStaticNameExpression(name) || !ts.isSameEntityName(name, parentNode.left)) {
69156                         return undefined;
69157                     }
69158                 }
69159             }
69160             else if (allowDeclaration && ts.isFunctionDeclaration(node)) {
69161                 name = node.name;
69162                 decl = node;
69163             }
69164             if (!decl || !name || (!allowDeclaration && !ts.getExpandoInitializer(node, ts.isPrototypeAccess(name)))) {
69165                 return undefined;
69166             }
69167             return getSymbolOfNode(decl);
69168         }
69169         function getAssignedJSPrototype(node) {
69170             if (!node.parent) {
69171                 return false;
69172             }
69173             var parent = node.parent;
69174             while (parent && parent.kind === 201 /* PropertyAccessExpression */) {
69175                 parent = parent.parent;
69176             }
69177             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
69178                 var right = ts.getInitializerOfBinaryExpression(parent);
69179                 return ts.isObjectLiteralExpression(right) && right;
69180             }
69181         }
69182         /**
69183          * Syntactically and semantically checks a call or new expression.
69184          * @param node The call/new expression to be checked.
69185          * @returns On success, the expression's signature's return type. On failure, anyType.
69186          */
69187         function checkCallExpression(node, checkMode) {
69188             var _a;
69189             if (!checkGrammarTypeArguments(node, node.typeArguments))
69190                 checkGrammarArguments(node.arguments);
69191             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
69192             if (signature === resolvingSignature) {
69193                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
69194                 // returns a function type. We defer checking and return nonInferrableType.
69195                 return nonInferrableType;
69196             }
69197             checkDeprecatedSignature(signature, node);
69198             if (node.expression.kind === 105 /* SuperKeyword */) {
69199                 return voidType;
69200             }
69201             if (node.kind === 204 /* NewExpression */) {
69202                 var declaration = signature.declaration;
69203                 if (declaration &&
69204                     declaration.kind !== 166 /* Constructor */ &&
69205                     declaration.kind !== 170 /* ConstructSignature */ &&
69206                     declaration.kind !== 175 /* ConstructorType */ &&
69207                     !ts.isJSDocConstructSignature(declaration) &&
69208                     !isJSConstructor(declaration)) {
69209                     // When resolved signature is a call signature (and not a construct signature) the result type is any
69210                     if (noImplicitAny) {
69211                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
69212                     }
69213                     return anyType;
69214                 }
69215             }
69216             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
69217             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
69218                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
69219             }
69220             var returnType = getReturnTypeOfSignature(signature);
69221             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
69222             // as a fresh unique symbol literal type.
69223             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
69224                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
69225             }
69226             if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ &&
69227                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
69228                 if (!ts.isDottedName(node.expression)) {
69229                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
69230                 }
69231                 else if (!getEffectsSignature(node)) {
69232                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
69233                     getTypeOfDottedName(node.expression, diagnostic);
69234                 }
69235             }
69236             if (ts.isInJSFile(node)) {
69237                 var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false);
69238                 if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) {
69239                     var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
69240                     jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
69241                     return getIntersectionType([returnType, jsAssignmentType]);
69242                 }
69243             }
69244             return returnType;
69245         }
69246         function checkDeprecatedSignature(signature, node) {
69247             if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) {
69248                 var suggestionNode = getDeprecatedSuggestionNode(node);
69249                 errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature));
69250             }
69251         }
69252         function getDeprecatedSuggestionNode(node) {
69253             node = ts.skipParentheses(node);
69254             switch (node.kind) {
69255                 case 203 /* CallExpression */:
69256                 case 161 /* Decorator */:
69257                 case 204 /* NewExpression */:
69258                     return getDeprecatedSuggestionNode(node.expression);
69259                 case 205 /* TaggedTemplateExpression */:
69260                     return getDeprecatedSuggestionNode(node.tag);
69261                 case 275 /* JsxOpeningElement */:
69262                 case 274 /* JsxSelfClosingElement */:
69263                     return getDeprecatedSuggestionNode(node.tagName);
69264                 case 202 /* ElementAccessExpression */:
69265                     return node.argumentExpression;
69266                 case 201 /* PropertyAccessExpression */:
69267                     return node.name;
69268                 case 173 /* TypeReference */:
69269                     var typeReference = node;
69270                     return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference;
69271                 default:
69272                     return node;
69273             }
69274         }
69275         function isSymbolOrSymbolForCall(node) {
69276             if (!ts.isCallExpression(node))
69277                 return false;
69278             var left = node.expression;
69279             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
69280                 left = left.expression;
69281             }
69282             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
69283                 return false;
69284             }
69285             // make sure `Symbol` is the global symbol
69286             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
69287             if (!globalESSymbol) {
69288                 return false;
69289             }
69290             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
69291         }
69292         function checkImportCallExpression(node) {
69293             // Check grammar of dynamic import
69294             if (!checkGrammarArguments(node.arguments))
69295                 checkGrammarImportCallExpression(node);
69296             if (node.arguments.length === 0) {
69297                 return createPromiseReturnType(node, anyType);
69298             }
69299             var specifier = node.arguments[0];
69300             var specifierType = checkExpressionCached(specifier);
69301             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
69302             for (var i = 1; i < node.arguments.length; ++i) {
69303                 checkExpressionCached(node.arguments[i]);
69304             }
69305             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
69306                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
69307             }
69308             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
69309             var moduleSymbol = resolveExternalModuleName(node, specifier);
69310             if (moduleSymbol) {
69311                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
69312                 if (esModuleSymbol) {
69313                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
69314                 }
69315             }
69316             return createPromiseReturnType(node, anyType);
69317         }
69318         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
69319             if (allowSyntheticDefaultImports && type && type !== errorType) {
69320                 var synthType = type;
69321                 if (!synthType.syntheticType) {
69322                     var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
69323                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
69324                     if (hasSyntheticDefault) {
69325                         var memberTable = ts.createSymbolTable();
69326                         var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
69327                         newSymbol.parent = originalSymbol;
69328                         newSymbol.nameType = getLiteralType("default");
69329                         newSymbol.target = resolveSymbol(symbol);
69330                         memberTable.set("default" /* Default */, newSymbol);
69331                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
69332                         var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
69333                         anonymousSymbol.type = defaultContainingObject;
69334                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
69335                     }
69336                     else {
69337                         synthType.syntheticType = type;
69338                     }
69339                 }
69340                 return synthType.syntheticType;
69341             }
69342             return type;
69343         }
69344         function isCommonJsRequire(node) {
69345             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
69346                 return false;
69347             }
69348             // Make sure require is not a local function
69349             if (!ts.isIdentifier(node.expression))
69350                 return ts.Debug.fail();
69351             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
69352             if (resolvedRequire === requireSymbol) {
69353                 return true;
69354             }
69355             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
69356             if (resolvedRequire.flags & 2097152 /* Alias */) {
69357                 return false;
69358             }
69359             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
69360                 ? 251 /* FunctionDeclaration */
69361                 : resolvedRequire.flags & 3 /* Variable */
69362                     ? 249 /* VariableDeclaration */
69363                     : 0 /* Unknown */;
69364             if (targetDeclarationKind !== 0 /* Unknown */) {
69365                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
69366                 // function/variable declaration should be ambient
69367                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
69368             }
69369             return false;
69370         }
69371         function checkTaggedTemplateExpression(node) {
69372             if (!checkGrammarTaggedTemplateChain(node))
69373                 checkGrammarTypeArguments(node, node.typeArguments);
69374             if (languageVersion < 2 /* ES2015 */) {
69375                 checkExternalEmitHelpers(node, 524288 /* MakeTemplateObject */);
69376             }
69377             var signature = getResolvedSignature(node);
69378             checkDeprecatedSignature(signature, node);
69379             return getReturnTypeOfSignature(signature);
69380         }
69381         function checkAssertion(node) {
69382             return checkAssertionWorker(node, node.type, node.expression);
69383         }
69384         function isValidConstAssertionArgument(node) {
69385             switch (node.kind) {
69386                 case 10 /* StringLiteral */:
69387                 case 14 /* NoSubstitutionTemplateLiteral */:
69388                 case 8 /* NumericLiteral */:
69389                 case 9 /* BigIntLiteral */:
69390                 case 109 /* TrueKeyword */:
69391                 case 94 /* FalseKeyword */:
69392                 case 199 /* ArrayLiteralExpression */:
69393                 case 200 /* ObjectLiteralExpression */:
69394                 case 218 /* TemplateExpression */:
69395                     return true;
69396                 case 207 /* ParenthesizedExpression */:
69397                     return isValidConstAssertionArgument(node.expression);
69398                 case 214 /* PrefixUnaryExpression */:
69399                     var op = node.operator;
69400                     var arg = node.operand;
69401                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
69402                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
69403                 case 201 /* PropertyAccessExpression */:
69404                 case 202 /* ElementAccessExpression */:
69405                     var expr = node.expression;
69406                     if (ts.isIdentifier(expr)) {
69407                         var symbol = getSymbolAtLocation(expr);
69408                         if (symbol && symbol.flags & 2097152 /* Alias */) {
69409                             symbol = resolveAlias(symbol);
69410                         }
69411                         return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
69412                     }
69413             }
69414             return false;
69415         }
69416         function checkAssertionWorker(errNode, type, expression, checkMode) {
69417             var exprType = checkExpression(expression, checkMode);
69418             if (ts.isConstTypeReference(type)) {
69419                 if (!isValidConstAssertionArgument(expression)) {
69420                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
69421                 }
69422                 return getRegularTypeOfLiteralType(exprType);
69423             }
69424             checkSourceElement(type);
69425             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
69426             var targetType = getTypeFromTypeNode(type);
69427             if (produceDiagnostics && targetType !== errorType) {
69428                 var widenedType = getWidenedType(exprType);
69429                 if (!isTypeComparableTo(targetType, widenedType)) {
69430                     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);
69431                 }
69432             }
69433             return targetType;
69434         }
69435         function checkNonNullChain(node) {
69436             var leftType = checkExpression(node.expression);
69437             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
69438             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
69439         }
69440         function checkNonNullAssertion(node) {
69441             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
69442                 getNonNullableType(checkExpression(node.expression));
69443         }
69444         function checkMetaProperty(node) {
69445             checkGrammarMetaProperty(node);
69446             if (node.keywordToken === 102 /* NewKeyword */) {
69447                 return checkNewTargetMetaProperty(node);
69448             }
69449             if (node.keywordToken === 99 /* ImportKeyword */) {
69450                 return checkImportMetaProperty(node);
69451             }
69452             return ts.Debug.assertNever(node.keywordToken);
69453         }
69454         function checkNewTargetMetaProperty(node) {
69455             var container = ts.getNewTargetContainer(node);
69456             if (!container) {
69457                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
69458                 return errorType;
69459             }
69460             else if (container.kind === 166 /* Constructor */) {
69461                 var symbol = getSymbolOfNode(container.parent);
69462                 return getTypeOfSymbol(symbol);
69463             }
69464             else {
69465                 var symbol = getSymbolOfNode(container);
69466                 return getTypeOfSymbol(symbol);
69467             }
69468         }
69469         function checkImportMetaProperty(node) {
69470             if (moduleKind !== ts.ModuleKind.ES2020 && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
69471                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system);
69472             }
69473             var file = ts.getSourceFileOfNode(node);
69474             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
69475             ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
69476             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
69477         }
69478         function getTypeOfParameter(symbol) {
69479             var type = getTypeOfSymbol(symbol);
69480             if (strictNullChecks) {
69481                 var declaration = symbol.valueDeclaration;
69482                 if (declaration && ts.hasInitializer(declaration)) {
69483                     return getOptionalType(type);
69484                 }
69485             }
69486             return type;
69487         }
69488         function getTupleElementLabel(d) {
69489             ts.Debug.assert(ts.isIdentifier(d.name)); // Parameter declarations could be binding patterns, but we only allow identifier names
69490             return d.name.escapedText;
69491         }
69492         function getParameterNameAtPosition(signature, pos, overrideRestType) {
69493             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69494             if (pos < paramCount) {
69495                 return signature.parameters[pos].escapedName;
69496             }
69497             var restParameter = signature.parameters[paramCount] || unknownSymbol;
69498             var restType = overrideRestType || getTypeOfSymbol(restParameter);
69499             if (isTupleType(restType)) {
69500                 var associatedNames = restType.target.labeledElementDeclarations;
69501                 var index = pos - paramCount;
69502                 return associatedNames && getTupleElementLabel(associatedNames[index]) || restParameter.escapedName + "_" + index;
69503             }
69504             return restParameter.escapedName;
69505         }
69506         function isValidDeclarationForTupleLabel(d) {
69507             return d.kind === 192 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name));
69508         }
69509         function getNameableDeclarationAtPosition(signature, pos) {
69510             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69511             if (pos < paramCount) {
69512                 var decl = signature.parameters[pos].valueDeclaration;
69513                 return decl && isValidDeclarationForTupleLabel(decl) ? decl : undefined;
69514             }
69515             var restParameter = signature.parameters[paramCount] || unknownSymbol;
69516             var restType = getTypeOfSymbol(restParameter);
69517             if (isTupleType(restType)) {
69518                 var associatedNames = restType.target.labeledElementDeclarations;
69519                 var index = pos - paramCount;
69520                 return associatedNames && associatedNames[index];
69521             }
69522             return restParameter.valueDeclaration && isValidDeclarationForTupleLabel(restParameter.valueDeclaration) ? restParameter.valueDeclaration : undefined;
69523         }
69524         function getTypeAtPosition(signature, pos) {
69525             return tryGetTypeAtPosition(signature, pos) || anyType;
69526         }
69527         function tryGetTypeAtPosition(signature, pos) {
69528             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69529             if (pos < paramCount) {
69530                 return getTypeOfParameter(signature.parameters[pos]);
69531             }
69532             if (signatureHasRestParameter(signature)) {
69533                 // We want to return the value undefined for an out of bounds parameter position,
69534                 // so we need to check bounds here before calling getIndexedAccessType (which
69535                 // otherwise would return the type 'undefined').
69536                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
69537                 var index = pos - paramCount;
69538                 if (!isTupleType(restType) || restType.target.hasRestElement || index < restType.target.fixedLength) {
69539                     return getIndexedAccessType(restType, getLiteralType(index));
69540                 }
69541             }
69542             return undefined;
69543         }
69544         function getRestTypeAtPosition(source, pos) {
69545             var parameterCount = getParameterCount(source);
69546             var minArgumentCount = getMinArgumentCount(source);
69547             var restType = getEffectiveRestType(source);
69548             if (restType && pos >= parameterCount - 1) {
69549                 return pos === parameterCount - 1 ? restType : createArrayType(getIndexedAccessType(restType, numberType));
69550             }
69551             var types = [];
69552             var flags = [];
69553             var names = [];
69554             for (var i = pos; i < parameterCount; i++) {
69555                 if (!restType || i < parameterCount - 1) {
69556                     types.push(getTypeAtPosition(source, i));
69557                     flags.push(i < minArgumentCount ? 1 /* Required */ : 2 /* Optional */);
69558                 }
69559                 else {
69560                     types.push(restType);
69561                     flags.push(8 /* Variadic */);
69562                 }
69563                 var name = getNameableDeclarationAtPosition(source, i);
69564                 if (name) {
69565                     names.push(name);
69566                 }
69567             }
69568             return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
69569         }
69570         function getParameterCount(signature) {
69571             var length = signature.parameters.length;
69572             if (signatureHasRestParameter(signature)) {
69573                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
69574                 if (isTupleType(restType)) {
69575                     return length + restType.target.fixedLength - (restType.target.hasRestElement ? 0 : 1);
69576                 }
69577             }
69578             return length;
69579         }
69580         function getMinArgumentCount(signature, flags) {
69581             var strongArityForUntypedJS = flags & 1 /* StrongArityForUntypedJS */;
69582             var voidIsNonOptional = flags & 2 /* VoidIsNonOptional */;
69583             if (voidIsNonOptional || signature.resolvedMinArgumentCount === undefined) {
69584                 var minArgumentCount = void 0;
69585                 if (signatureHasRestParameter(signature)) {
69586                     var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
69587                     if (isTupleType(restType)) {
69588                         var firstOptionalIndex = ts.findIndex(restType.target.elementFlags, function (f) { return !(f & 1 /* Required */); });
69589                         var requiredCount = firstOptionalIndex < 0 ? restType.target.fixedLength : firstOptionalIndex;
69590                         if (requiredCount > 0) {
69591                             minArgumentCount = signature.parameters.length - 1 + requiredCount;
69592                         }
69593                     }
69594                 }
69595                 if (minArgumentCount === undefined) {
69596                     if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
69597                         return 0;
69598                     }
69599                     minArgumentCount = signature.minArgumentCount;
69600                 }
69601                 if (voidIsNonOptional) {
69602                     return minArgumentCount;
69603                 }
69604                 for (var i = minArgumentCount - 1; i >= 0; i--) {
69605                     var type = getTypeAtPosition(signature, i);
69606                     if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
69607                         break;
69608                     }
69609                     minArgumentCount = i;
69610                 }
69611                 signature.resolvedMinArgumentCount = minArgumentCount;
69612             }
69613             return signature.resolvedMinArgumentCount;
69614         }
69615         function hasEffectiveRestParameter(signature) {
69616             if (signatureHasRestParameter(signature)) {
69617                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
69618                 return !isTupleType(restType) || restType.target.hasRestElement;
69619             }
69620             return false;
69621         }
69622         function getEffectiveRestType(signature) {
69623             if (signatureHasRestParameter(signature)) {
69624                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
69625                 if (!isTupleType(restType)) {
69626                     return restType;
69627                 }
69628                 if (restType.target.hasRestElement) {
69629                     return sliceTupleType(restType, restType.target.fixedLength);
69630                 }
69631             }
69632             return undefined;
69633         }
69634         function getNonArrayRestType(signature) {
69635             var restType = getEffectiveRestType(signature);
69636             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
69637         }
69638         function getTypeOfFirstParameterOfSignature(signature) {
69639             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
69640         }
69641         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
69642             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
69643         }
69644         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
69645             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69646             for (var i = 0; i < len; i++) {
69647                 var declaration = signature.parameters[i].valueDeclaration;
69648                 if (declaration.type) {
69649                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
69650                     if (typeNode) {
69651                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
69652                     }
69653                 }
69654             }
69655             var restType = getEffectiveRestType(context);
69656             if (restType && restType.flags & 262144 /* TypeParameter */) {
69657                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
69658                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
69659                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
69660                 assignContextualParameterTypes(signature, instantiatedContext);
69661                 // We then infer from a tuple type representing the parameters that correspond to the contextual
69662                 // rest parameter.
69663                 var restPos = getParameterCount(context) - 1;
69664                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
69665             }
69666         }
69667         function assignContextualParameterTypes(signature, context) {
69668             signature.typeParameters = context.typeParameters;
69669             if (context.thisParameter) {
69670                 var parameter = signature.thisParameter;
69671                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
69672                     if (!parameter) {
69673                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
69674                     }
69675                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
69676                 }
69677             }
69678             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69679             for (var i = 0; i < len; i++) {
69680                 var parameter = signature.parameters[i];
69681                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
69682                     var contextualParameterType = tryGetTypeAtPosition(context, i);
69683                     assignParameterType(parameter, contextualParameterType);
69684                 }
69685             }
69686             if (signatureHasRestParameter(signature)) {
69687                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
69688                 var parameter = ts.last(signature.parameters);
69689                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
69690                     var contextualParameterType = getRestTypeAtPosition(context, len);
69691                     assignParameterType(parameter, contextualParameterType);
69692                 }
69693             }
69694         }
69695         function assignNonContextualParameterTypes(signature) {
69696             if (signature.thisParameter) {
69697                 assignParameterType(signature.thisParameter);
69698             }
69699             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
69700                 var parameter = _a[_i];
69701                 assignParameterType(parameter);
69702             }
69703         }
69704         function assignParameterType(parameter, type) {
69705             var links = getSymbolLinks(parameter);
69706             if (!links.type) {
69707                 var declaration = parameter.valueDeclaration;
69708                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
69709                 if (declaration.name.kind !== 78 /* Identifier */) {
69710                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
69711                     if (links.type === unknownType) {
69712                         links.type = getTypeFromBindingPattern(declaration.name);
69713                     }
69714                     assignBindingElementTypes(declaration.name);
69715                 }
69716             }
69717         }
69718         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
69719         // the destructured type into the contained binding elements.
69720         function assignBindingElementTypes(pattern) {
69721             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
69722                 var element = _a[_i];
69723                 if (!ts.isOmittedExpression(element)) {
69724                     if (element.name.kind === 78 /* Identifier */) {
69725                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
69726                     }
69727                     else {
69728                         assignBindingElementTypes(element.name);
69729                     }
69730                 }
69731             }
69732         }
69733         function createPromiseType(promisedType) {
69734             // creates a `Promise<T>` type where `T` is the promisedType argument
69735             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
69736             if (globalPromiseType !== emptyGenericType) {
69737                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
69738                 promisedType = getAwaitedType(promisedType) || unknownType;
69739                 return createTypeReference(globalPromiseType, [promisedType]);
69740             }
69741             return unknownType;
69742         }
69743         function createPromiseLikeType(promisedType) {
69744             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
69745             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
69746             if (globalPromiseLikeType !== emptyGenericType) {
69747                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
69748                 promisedType = getAwaitedType(promisedType) || unknownType;
69749                 return createTypeReference(globalPromiseLikeType, [promisedType]);
69750             }
69751             return unknownType;
69752         }
69753         function createPromiseReturnType(func, promisedType) {
69754             var promiseType = createPromiseType(promisedType);
69755             if (promiseType === unknownType) {
69756                 error(func, ts.isImportCall(func) ?
69757                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
69758                     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);
69759                 return errorType;
69760             }
69761             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
69762                 error(func, ts.isImportCall(func) ?
69763                     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 :
69764                     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);
69765             }
69766             return promiseType;
69767         }
69768         function getReturnTypeFromBody(func, checkMode) {
69769             if (!func.body) {
69770                 return errorType;
69771             }
69772             var functionFlags = ts.getFunctionFlags(func);
69773             var isAsync = (functionFlags & 2 /* Async */) !== 0;
69774             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
69775             var returnType;
69776             var yieldType;
69777             var nextType;
69778             var fallbackReturnType = voidType;
69779             if (func.body.kind !== 230 /* Block */) { // Async or normal arrow function
69780                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
69781                 if (isAsync) {
69782                     // From within an async function you can return either a non-promise value or a promise. Any
69783                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
69784                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
69785                     // the native Promise<T> type later in this function.
69786                     returnType = checkAwaitedType(returnType, /*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);
69787                 }
69788             }
69789             else if (isGenerator) { // Generator or AsyncGenerator function
69790                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
69791                 if (!returnTypes) {
69792                     fallbackReturnType = neverType;
69793                 }
69794                 else if (returnTypes.length > 0) {
69795                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
69796                 }
69797                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
69798                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
69799                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
69800             }
69801             else { // Async or normal function
69802                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
69803                 if (!types) {
69804                     // For an async function, the return type will not be never, but rather a Promise for never.
69805                     return functionFlags & 2 /* Async */
69806                         ? createPromiseReturnType(func, neverType) // Async function
69807                         : neverType; // Normal function
69808                 }
69809                 if (types.length === 0) {
69810                     // For an async function, the return type will not be void, but rather a Promise for void.
69811                     return functionFlags & 2 /* Async */
69812                         ? createPromiseReturnType(func, voidType) // Async function
69813                         : voidType; // Normal function
69814                 }
69815                 // Return a union of the return expression types.
69816                 returnType = getUnionType(types, 2 /* Subtype */);
69817             }
69818             if (returnType || yieldType || nextType) {
69819                 if (yieldType)
69820                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
69821                 if (returnType)
69822                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
69823                 if (nextType)
69824                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
69825                 if (returnType && isUnitType(returnType) ||
69826                     yieldType && isUnitType(yieldType) ||
69827                     nextType && isUnitType(nextType)) {
69828                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
69829                     var contextualType = !contextualSignature ? undefined :
69830                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
69831                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
69832                     if (isGenerator) {
69833                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
69834                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
69835                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
69836                     }
69837                     else {
69838                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
69839                     }
69840                 }
69841                 if (yieldType)
69842                     yieldType = getWidenedType(yieldType);
69843                 if (returnType)
69844                     returnType = getWidenedType(returnType);
69845                 if (nextType)
69846                     nextType = getWidenedType(nextType);
69847             }
69848             if (isGenerator) {
69849                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
69850             }
69851             else {
69852                 // From within an async function you can return either a non-promise value or a promise. Any
69853                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
69854                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
69855                 return isAsync
69856                     ? createPromiseType(returnType || fallbackReturnType)
69857                     : returnType || fallbackReturnType;
69858             }
69859         }
69860         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
69861             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
69862             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
69863             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
69864             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
69865             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
69866             if (globalGeneratorType === emptyGenericType) {
69867                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
69868                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
69869                 // nextType.
69870                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
69871                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
69872                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
69873                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
69874                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
69875                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
69876                     if (globalType !== emptyGenericType) {
69877                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
69878                     }
69879                     // The global IterableIterator type doesn't exist, so report an error
69880                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
69881                     return emptyObjectType;
69882                 }
69883                 // The global Generator type doesn't exist, so report an error
69884                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
69885                 return emptyObjectType;
69886             }
69887             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
69888         }
69889         function checkAndAggregateYieldOperandTypes(func, checkMode) {
69890             var yieldTypes = [];
69891             var nextTypes = [];
69892             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
69893             ts.forEachYieldExpression(func.body, function (yieldExpression) {
69894                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
69895                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
69896                 var nextType;
69897                 if (yieldExpression.asteriskToken) {
69898                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
69899                     nextType = iterationTypes && iterationTypes.nextType;
69900                 }
69901                 else {
69902                     nextType = getContextualType(yieldExpression);
69903                 }
69904                 if (nextType)
69905                     ts.pushIfUnique(nextTypes, nextType);
69906             });
69907             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
69908         }
69909         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
69910             var errorNode = node.expression || node;
69911             // A `yield*` expression effectively yields everything that its operand yields
69912             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
69913             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
69914                 ? 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
69915                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
69916         }
69917         /**
69918          * Collect the TypeFacts learned from a typeof switch with
69919          * total clauses `witnesses`, and the active clause ranging
69920          * from `start` to `end`. Parameter `hasDefault` denotes
69921          * whether the active clause contains a default clause.
69922          */
69923         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
69924             var facts = 0 /* None */;
69925             // When in the default we only collect inequality facts
69926             // because default is 'in theory' a set of infinite
69927             // equalities.
69928             if (hasDefault) {
69929                 // Value is not equal to any types after the active clause.
69930                 for (var i = end; i < witnesses.length; i++) {
69931                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
69932                 }
69933                 // Remove inequalities for types that appear in the
69934                 // active clause because they appear before other
69935                 // types collected so far.
69936                 for (var i = start; i < end; i++) {
69937                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
69938                 }
69939                 // Add inequalities for types before the active clause unconditionally.
69940                 for (var i = 0; i < start; i++) {
69941                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
69942                 }
69943             }
69944             // When in an active clause without default the set of
69945             // equalities is finite.
69946             else {
69947                 // Add equalities for all types in the active clause.
69948                 for (var i = start; i < end; i++) {
69949                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
69950                 }
69951                 // Remove equalities for types that appear before the
69952                 // active clause.
69953                 for (var i = 0; i < start; i++) {
69954                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
69955                 }
69956             }
69957             return facts;
69958         }
69959         function isExhaustiveSwitchStatement(node) {
69960             var links = getNodeLinks(node);
69961             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
69962         }
69963         function computeExhaustiveSwitchStatement(node) {
69964             if (node.expression.kind === 211 /* TypeOfExpression */) {
69965                 var operandType = getTypeOfExpression(node.expression.expression);
69966                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
69967                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
69968                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
69969                 var type_4 = getBaseConstraintOfType(operandType) || operandType;
69970                 // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types.
69971                 if (type_4.flags & 3 /* AnyOrUnknown */) {
69972                     return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */;
69973                 }
69974                 return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
69975             }
69976             var type = getTypeOfExpression(node.expression);
69977             if (!isLiteralType(type)) {
69978                 return false;
69979             }
69980             var switchTypes = getSwitchClauseTypes(node);
69981             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
69982                 return false;
69983             }
69984             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
69985         }
69986         function functionHasImplicitReturn(func) {
69987             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
69988         }
69989         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
69990         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
69991             var functionFlags = ts.getFunctionFlags(func);
69992             var aggregatedTypes = [];
69993             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
69994             var hasReturnOfTypeNever = false;
69995             ts.forEachReturnStatement(func.body, function (returnStatement) {
69996                 var expr = returnStatement.expression;
69997                 if (expr) {
69998                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
69999                     if (functionFlags & 2 /* Async */) {
70000                         // From within an async function you can return either a non-promise value or a promise. Any
70001                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
70002                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
70003                         // the native Promise<T> type by the caller.
70004                         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);
70005                     }
70006                     if (type.flags & 131072 /* Never */) {
70007                         hasReturnOfTypeNever = true;
70008                     }
70009                     ts.pushIfUnique(aggregatedTypes, type);
70010                 }
70011                 else {
70012                     hasReturnWithNoExpression = true;
70013                 }
70014             });
70015             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
70016                 return undefined;
70017             }
70018             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
70019                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
70020                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
70021                 ts.pushIfUnique(aggregatedTypes, undefinedType);
70022             }
70023             return aggregatedTypes;
70024         }
70025         function mayReturnNever(func) {
70026             switch (func.kind) {
70027                 case 208 /* FunctionExpression */:
70028                 case 209 /* ArrowFunction */:
70029                     return true;
70030                 case 165 /* MethodDeclaration */:
70031                     return func.parent.kind === 200 /* ObjectLiteralExpression */;
70032                 default:
70033                     return false;
70034             }
70035         }
70036         /**
70037          * TypeScript Specification 1.0 (6.3) - July 2014
70038          *   An explicitly typed function whose return type isn't the Void type,
70039          *   the Any type, or a union type containing the Void or Any type as a constituent
70040          *   must have at least one return statement somewhere in its body.
70041          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
70042          *
70043          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
70044          */
70045         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
70046             if (!produceDiagnostics) {
70047                 return;
70048             }
70049             var functionFlags = ts.getFunctionFlags(func);
70050             var type = returnType && unwrapReturnType(returnType, functionFlags);
70051             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
70052             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
70053                 return;
70054             }
70055             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
70056             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
70057             if (func.kind === 164 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 230 /* Block */ || !functionHasImplicitReturn(func)) {
70058                 return;
70059             }
70060             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
70061             if (type && type.flags & 131072 /* Never */) {
70062                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
70063             }
70064             else if (type && !hasExplicitReturn) {
70065                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
70066                 // this function does not conform to the specification.
70067                 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
70068                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
70069             }
70070             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
70071                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
70072             }
70073             else if (compilerOptions.noImplicitReturns) {
70074                 if (!type) {
70075                     // If return type annotation is omitted check if function has any explicit return statements.
70076                     // If it does not have any - its inferred return type is void - don't do any checks.
70077                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
70078                     if (!hasExplicitReturn) {
70079                         return;
70080                     }
70081                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
70082                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
70083                         return;
70084                     }
70085                 }
70086                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
70087             }
70088         }
70089         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
70090             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
70091             checkNodeDeferred(node);
70092             // The identityMapper object is used to indicate that function expressions are wildcards
70093             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
70094                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
70095                 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
70096                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
70097                     var contextualSignature = getContextualSignature(node);
70098                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
70099                         var links = getNodeLinks(node);
70100                         if (links.contextFreeType) {
70101                             return links.contextFreeType;
70102                         }
70103                         var returnType = getReturnTypeFromBody(node, checkMode);
70104                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
70105                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
70106                         returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
70107                         return links.contextFreeType = returnOnlyType;
70108                     }
70109                 }
70110                 return anyFunctionType;
70111             }
70112             // Grammar checking
70113             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
70114             if (!hasGrammarError && node.kind === 208 /* FunctionExpression */) {
70115                 checkGrammarForGenerator(node);
70116             }
70117             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
70118             return getTypeOfSymbol(getSymbolOfNode(node));
70119         }
70120         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
70121             var links = getNodeLinks(node);
70122             // Check if function expression is contextually typed and assign parameter types if so.
70123             if (!(links.flags & 1024 /* ContextChecked */)) {
70124                 var contextualSignature = getContextualSignature(node);
70125                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
70126                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
70127                 // already assigned contextual types.
70128                 if (!(links.flags & 1024 /* ContextChecked */)) {
70129                     links.flags |= 1024 /* ContextChecked */;
70130                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
70131                     if (!signature) {
70132                         return;
70133                     }
70134                     if (isContextSensitive(node)) {
70135                         if (contextualSignature) {
70136                             var inferenceContext = getInferenceContext(node);
70137                             if (checkMode && checkMode & 2 /* Inferential */) {
70138                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
70139                             }
70140                             var instantiatedContextualSignature = inferenceContext ?
70141                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
70142                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
70143                         }
70144                         else {
70145                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
70146                             assignNonContextualParameterTypes(signature);
70147                         }
70148                     }
70149                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
70150                         var returnType = getReturnTypeFromBody(node, checkMode);
70151                         if (!signature.resolvedReturnType) {
70152                             signature.resolvedReturnType = returnType;
70153                         }
70154                     }
70155                     checkSignatureDeclaration(node);
70156                 }
70157             }
70158         }
70159         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
70160             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
70161             var functionFlags = ts.getFunctionFlags(node);
70162             var returnType = getReturnTypeFromAnnotation(node);
70163             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
70164             if (node.body) {
70165                 if (!ts.getEffectiveReturnTypeNode(node)) {
70166                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
70167                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
70168                     // of a function. Because checking of function expression bodies is deferred, there was never an
70169                     // appropriate time to do this during the main walk of the file (see the comment at the top of
70170                     // checkFunctionExpressionBodies). So it must be done now.
70171                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
70172                 }
70173                 if (node.body.kind === 230 /* Block */) {
70174                     checkSourceElement(node.body);
70175                 }
70176                 else {
70177                     // From within an async function you can return either a non-promise value or a promise. Any
70178                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
70179                     // should not be checking assignability of a promise to the return type. Instead, we need to
70180                     // check assignability of the awaited type of the expression body against the promised type of
70181                     // its return type annotation.
70182                     var exprType = checkExpression(node.body);
70183                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
70184                     if (returnOrPromisedType) {
70185                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
70186                             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);
70187                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
70188                         }
70189                         else { // Normal function
70190                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
70191                         }
70192                     }
70193                 }
70194             }
70195         }
70196         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
70197             if (isAwaitValid === void 0) { isAwaitValid = false; }
70198             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
70199                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
70200                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
70201                 return false;
70202             }
70203             return true;
70204         }
70205         function isReadonlyAssignmentDeclaration(d) {
70206             if (!ts.isCallExpression(d)) {
70207                 return false;
70208             }
70209             if (!ts.isBindableObjectDefinePropertyCall(d)) {
70210                 return false;
70211             }
70212             var objectLitType = checkExpressionCached(d.arguments[2]);
70213             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
70214             if (valueType) {
70215                 var writableProp = getPropertyOfType(objectLitType, "writable");
70216                 var writableType = writableProp && getTypeOfSymbol(writableProp);
70217                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
70218                     return true;
70219                 }
70220                 // We include this definition whereupon we walk back and check the type at the declaration because
70221                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
70222                 // argument types, should the type be contextualized by the call itself.
70223                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
70224                     var initializer = writableProp.valueDeclaration.initializer;
70225                     var rawOriginalType = checkExpression(initializer);
70226                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
70227                         return true;
70228                     }
70229                 }
70230                 return false;
70231             }
70232             var setProp = getPropertyOfType(objectLitType, "set");
70233             return !setProp;
70234         }
70235         function isReadonlySymbol(symbol) {
70236             // The following symbols are considered read-only:
70237             // Properties with a 'readonly' modifier
70238             // Variables declared with 'const'
70239             // Get accessors without matching set accessors
70240             // Enum members
70241             // Object.defineProperty assignments with writable false or no setter
70242             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
70243             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
70244                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
70245                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
70246                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
70247                 symbol.flags & 8 /* EnumMember */ ||
70248                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
70249         }
70250         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
70251             var _a, _b;
70252             if (assignmentKind === 0 /* None */) {
70253                 // no assigment means it doesn't matter whether the entity is readonly
70254                 return false;
70255             }
70256             if (isReadonlySymbol(symbol)) {
70257                 // Allow assignments to readonly properties within constructors of the same class declaration.
70258                 if (symbol.flags & 4 /* Property */ &&
70259                     ts.isAccessExpression(expr) &&
70260                     expr.expression.kind === 107 /* ThisKeyword */) {
70261                     // Look for if this is the constructor for the class that `symbol` is a property of.
70262                     var ctor = ts.getContainingFunction(expr);
70263                     if (!(ctor && (ctor.kind === 166 /* Constructor */ || isJSConstructor(ctor)))) {
70264                         return true;
70265                     }
70266                     if (symbol.valueDeclaration) {
70267                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
70268                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
70269                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
70270                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
70271                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
70272                         var isWriteableSymbol = isLocalPropertyDeclaration
70273                             || isLocalParameterProperty
70274                             || isLocalThisPropertyAssignment
70275                             || isLocalThisPropertyAssignmentConstructorFunction;
70276                         return !isWriteableSymbol;
70277                     }
70278                 }
70279                 return true;
70280             }
70281             if (ts.isAccessExpression(expr)) {
70282                 // references through namespace import should be readonly
70283                 var node = ts.skipParentheses(expr.expression);
70284                 if (node.kind === 78 /* Identifier */) {
70285                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
70286                     if (symbol_2.flags & 2097152 /* Alias */) {
70287                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
70288                         return !!declaration && declaration.kind === 263 /* NamespaceImport */;
70289                     }
70290                 }
70291             }
70292             return false;
70293         }
70294         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
70295             // References are combinations of identifiers, parentheses, and property accesses.
70296             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
70297             if (node.kind !== 78 /* Identifier */ && !ts.isAccessExpression(node)) {
70298                 error(expr, invalidReferenceMessage);
70299                 return false;
70300             }
70301             if (node.flags & 32 /* OptionalChain */) {
70302                 error(expr, invalidOptionalChainMessage);
70303                 return false;
70304             }
70305             return true;
70306         }
70307         function checkDeleteExpression(node) {
70308             checkExpression(node.expression);
70309             var expr = ts.skipParentheses(node.expression);
70310             if (!ts.isAccessExpression(expr)) {
70311                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
70312                 return booleanType;
70313             }
70314             if (ts.isPropertyAccessExpression(expr) && ts.isPrivateIdentifier(expr.name)) {
70315                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
70316             }
70317             var links = getNodeLinks(expr);
70318             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
70319             if (symbol) {
70320                 if (isReadonlySymbol(symbol)) {
70321                     error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
70322                 }
70323                 checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol));
70324             }
70325             return booleanType;
70326         }
70327         function checkDeleteExpressionMustBeOptional(expr, type) {
70328             var AnyOrUnknownOrNeverFlags = 3 /* AnyOrUnknown */ | 131072 /* Never */;
70329             if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768 /* Undefined */)) {
70330                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional);
70331             }
70332         }
70333         function checkTypeOfExpression(node) {
70334             checkExpression(node.expression);
70335             return typeofType;
70336         }
70337         function checkVoidExpression(node) {
70338             checkExpression(node.expression);
70339             return undefinedWideningType;
70340         }
70341         function checkAwaitExpression(node) {
70342             // Grammar checking
70343             if (produceDiagnostics) {
70344                 if (!(node.flags & 32768 /* AwaitContext */)) {
70345                     if (ts.isInTopLevelContext(node)) {
70346                         var sourceFile = ts.getSourceFileOfNode(node);
70347                         if (!hasParseDiagnostics(sourceFile)) {
70348                             var span = void 0;
70349                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
70350                                 if (!span)
70351                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
70352                                 var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module);
70353                                 diagnostics.add(diagnostic);
70354                             }
70355                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
70356                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
70357                                 var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher);
70358                                 diagnostics.add(diagnostic);
70359                             }
70360                         }
70361                     }
70362                     else {
70363                         // use of 'await' in non-async function
70364                         var sourceFile = ts.getSourceFileOfNode(node);
70365                         if (!hasParseDiagnostics(sourceFile)) {
70366                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
70367                             var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules);
70368                             var func = ts.getContainingFunction(node);
70369                             if (func && func.kind !== 166 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
70370                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
70371                                 ts.addRelatedInfo(diagnostic, relatedInfo);
70372                             }
70373                             diagnostics.add(diagnostic);
70374                         }
70375                     }
70376                 }
70377                 if (isInParameterInitializerBeforeContainingFunction(node)) {
70378                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
70379                 }
70380             }
70381             var operandType = checkExpression(node.expression);
70382             var awaitedType = checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
70383             if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
70384                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
70385             }
70386             return awaitedType;
70387         }
70388         function checkPrefixUnaryExpression(node) {
70389             var operandType = checkExpression(node.operand);
70390             if (operandType === silentNeverType) {
70391                 return silentNeverType;
70392             }
70393             switch (node.operand.kind) {
70394                 case 8 /* NumericLiteral */:
70395                     switch (node.operator) {
70396                         case 40 /* MinusToken */:
70397                             return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
70398                         case 39 /* PlusToken */:
70399                             return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
70400                     }
70401                     break;
70402                 case 9 /* BigIntLiteral */:
70403                     if (node.operator === 40 /* MinusToken */) {
70404                         return getFreshTypeOfLiteralType(getLiteralType({
70405                             negative: true,
70406                             base10Value: ts.parsePseudoBigInt(node.operand.text)
70407                         }));
70408                     }
70409             }
70410             switch (node.operator) {
70411                 case 39 /* PlusToken */:
70412                 case 40 /* MinusToken */:
70413                 case 54 /* TildeToken */:
70414                     checkNonNullType(operandType, node.operand);
70415                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
70416                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
70417                     }
70418                     if (node.operator === 39 /* PlusToken */) {
70419                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
70420                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
70421                         }
70422                         return numberType;
70423                     }
70424                     return getUnaryResultType(operandType);
70425                 case 53 /* ExclamationToken */:
70426                     checkTruthinessExpression(node.operand);
70427                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
70428                     return facts === 4194304 /* Truthy */ ? falseType :
70429                         facts === 8388608 /* Falsy */ ? trueType :
70430                             booleanType;
70431                 case 45 /* PlusPlusToken */:
70432                 case 46 /* MinusMinusToken */:
70433                     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);
70434                     if (ok) {
70435                         // run check only if former checks succeeded to avoid reporting cascading errors
70436                         checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access);
70437                     }
70438                     return getUnaryResultType(operandType);
70439             }
70440             return errorType;
70441         }
70442         function checkPostfixUnaryExpression(node) {
70443             var operandType = checkExpression(node.operand);
70444             if (operandType === silentNeverType) {
70445                 return silentNeverType;
70446             }
70447             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);
70448             if (ok) {
70449                 // run check only if former checks succeeded to avoid reporting cascading errors
70450                 checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access);
70451             }
70452             return getUnaryResultType(operandType);
70453         }
70454         function getUnaryResultType(operandType) {
70455             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
70456                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
70457                     ? numberOrBigIntType
70458                     : bigintType;
70459             }
70460             // If it's not a bigint type, implicit coercion will result in a number
70461             return numberType;
70462         }
70463         // Return true if type might be of the given kind. A union or intersection type might be of a given
70464         // kind if at least one constituent type is of the given kind.
70465         function maybeTypeOfKind(type, kind) {
70466             if (type.flags & kind) {
70467                 return true;
70468             }
70469             if (type.flags & 3145728 /* UnionOrIntersection */) {
70470                 var types = type.types;
70471                 for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
70472                     var t = types_20[_i];
70473                     if (maybeTypeOfKind(t, kind)) {
70474                         return true;
70475                     }
70476                 }
70477             }
70478             return false;
70479         }
70480         function isTypeAssignableToKind(source, kind, strict) {
70481             if (source.flags & kind) {
70482                 return true;
70483             }
70484             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
70485                 return false;
70486             }
70487             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
70488                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
70489                 !!(kind & 402653316 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
70490                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
70491                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
70492                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
70493                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
70494                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
70495                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
70496                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
70497         }
70498         function allTypesAssignableToKind(source, kind, strict) {
70499             return source.flags & 1048576 /* Union */ ?
70500                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
70501                 isTypeAssignableToKind(source, kind, strict);
70502         }
70503         function isConstEnumObjectType(type) {
70504             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
70505         }
70506         function isConstEnumSymbol(symbol) {
70507             return (symbol.flags & 128 /* ConstEnum */) !== 0;
70508         }
70509         function checkInstanceOfExpression(left, right, leftType, rightType) {
70510             if (leftType === silentNeverType || rightType === silentNeverType) {
70511                 return silentNeverType;
70512             }
70513             // TypeScript 1.0 spec (April 2014): 4.15.4
70514             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
70515             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
70516             // The result is always of the Boolean primitive type.
70517             // NOTE: do not raise error if leftType is unknown as related error was already reported
70518             if (!isTypeAny(leftType) &&
70519                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
70520                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
70521             }
70522             // NOTE: do not raise error if right is unknown as related error was already reported
70523             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
70524                 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);
70525             }
70526             return booleanType;
70527         }
70528         function checkInExpression(left, right, leftType, rightType) {
70529             if (leftType === silentNeverType || rightType === silentNeverType) {
70530                 return silentNeverType;
70531             }
70532             leftType = checkNonNullType(leftType, left);
70533             rightType = checkNonNullType(rightType, right);
70534             // TypeScript 1.0 spec (April 2014): 4.15.5
70535             // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
70536             // and the right operand to be of type Any, an object type, or a type parameter type.
70537             // The result is always of the Boolean primitive type.
70538             if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) ||
70539                 isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) {
70540                 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
70541             }
70542             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
70543                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
70544             }
70545             return booleanType;
70546         }
70547         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
70548             var properties = node.properties;
70549             if (strictNullChecks && properties.length === 0) {
70550                 return checkNonNullType(sourceType, node);
70551             }
70552             for (var i = 0; i < properties.length; i++) {
70553                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
70554             }
70555             return sourceType;
70556         }
70557         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
70558         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
70559             if (rightIsThis === void 0) { rightIsThis = false; }
70560             var properties = node.properties;
70561             var property = properties[propertyIndex];
70562             if (property.kind === 288 /* PropertyAssignment */ || property.kind === 289 /* ShorthandPropertyAssignment */) {
70563                 var name = property.name;
70564                 var exprType = getLiteralTypeFromPropertyName(name);
70565                 if (isTypeUsableAsPropertyName(exprType)) {
70566                     var text = getPropertyNameFromType(exprType);
70567                     var prop = getPropertyOfType(objectLiteralType, text);
70568                     if (prop) {
70569                         markPropertyAsReferenced(prop, property, rightIsThis);
70570                         checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
70571                     }
70572                 }
70573                 var elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */);
70574                 var type = getFlowTypeOfDestructuring(property, elementType);
70575                 return checkDestructuringAssignment(property.kind === 289 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
70576             }
70577             else if (property.kind === 290 /* SpreadAssignment */) {
70578                 if (propertyIndex < properties.length - 1) {
70579                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
70580                 }
70581                 else {
70582                     if (languageVersion < 99 /* ESNext */) {
70583                         checkExternalEmitHelpers(property, 4 /* Rest */);
70584                     }
70585                     var nonRestNames = [];
70586                     if (allProperties) {
70587                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
70588                             var otherProperty = allProperties_1[_i];
70589                             if (!ts.isSpreadAssignment(otherProperty)) {
70590                                 nonRestNames.push(otherProperty.name);
70591                             }
70592                         }
70593                     }
70594                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
70595                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
70596                     return checkDestructuringAssignment(property.expression, type);
70597                 }
70598             }
70599             else {
70600                 error(property, ts.Diagnostics.Property_assignment_expected);
70601             }
70602         }
70603         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
70604             var elements = node.elements;
70605             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
70606                 checkExternalEmitHelpers(node, 512 /* Read */);
70607             }
70608             // This elementType will be used if the specific property corresponding to this index is not
70609             // present (aka the tuple element property). This call also checks that the parentType is in
70610             // fact an iterable or array (depending on target language).
70611             var possiblyOutOfBoundsType = checkIteratedTypeOrElementType(65 /* Destructuring */ | 128 /* PossiblyOutOfBounds */, sourceType, undefinedType, node) || errorType;
70612             var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType;
70613             for (var i = 0; i < elements.length; i++) {
70614                 var type = possiblyOutOfBoundsType;
70615                 if (node.elements[i].kind === 220 /* SpreadElement */) {
70616                     type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType);
70617                 }
70618                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode);
70619             }
70620             return sourceType;
70621         }
70622         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
70623             var elements = node.elements;
70624             var element = elements[elementIndex];
70625             if (element.kind !== 222 /* OmittedExpression */) {
70626                 if (element.kind !== 220 /* SpreadElement */) {
70627                     var indexType = getLiteralType(elementIndex);
70628                     if (isArrayLikeType(sourceType)) {
70629                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
70630                         // when the element is a SyntaxKind.ElementAccessExpression.
70631                         var accessFlags = 16 /* ExpressionPosition */ | (hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0);
70632                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, createSyntheticExpression(element, indexType), accessFlags) || errorType;
70633                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
70634                         var type = getFlowTypeOfDestructuring(element, assignedType);
70635                         return checkDestructuringAssignment(element, type, checkMode);
70636                     }
70637                     return checkDestructuringAssignment(element, elementType, checkMode);
70638                 }
70639                 if (elementIndex < elements.length - 1) {
70640                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
70641                 }
70642                 else {
70643                     var restExpression = element.expression;
70644                     if (restExpression.kind === 216 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
70645                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
70646                     }
70647                     else {
70648                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
70649                         var type = everyType(sourceType, isTupleType) ?
70650                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
70651                             createArrayType(elementType);
70652                         return checkDestructuringAssignment(restExpression, type, checkMode);
70653                     }
70654                 }
70655             }
70656             return undefined;
70657         }
70658         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
70659             var target;
70660             if (exprOrAssignment.kind === 289 /* ShorthandPropertyAssignment */) {
70661                 var prop = exprOrAssignment;
70662                 if (prop.objectAssignmentInitializer) {
70663                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
70664                     // undefined from the final type.
70665                     if (strictNullChecks &&
70666                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
70667                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
70668                     }
70669                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
70670                 }
70671                 target = exprOrAssignment.name;
70672             }
70673             else {
70674                 target = exprOrAssignment;
70675             }
70676             if (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
70677                 checkBinaryExpression(target, checkMode);
70678                 target = target.left;
70679             }
70680             if (target.kind === 200 /* ObjectLiteralExpression */) {
70681                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
70682             }
70683             if (target.kind === 199 /* ArrayLiteralExpression */) {
70684                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
70685             }
70686             return checkReferenceAssignment(target, sourceType, checkMode);
70687         }
70688         function checkReferenceAssignment(target, sourceType, checkMode) {
70689             var targetType = checkExpression(target, checkMode);
70690             var error = target.parent.kind === 290 /* SpreadAssignment */ ?
70691                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
70692                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
70693             var optionalError = target.parent.kind === 290 /* SpreadAssignment */ ?
70694                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
70695                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
70696             if (checkReferenceExpression(target, error, optionalError)) {
70697                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
70698             }
70699             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
70700                 checkExternalEmitHelpers(target.parent, 2097152 /* ClassPrivateFieldSet */);
70701             }
70702             return sourceType;
70703         }
70704         /**
70705          * This is a *shallow* check: An expression is side-effect-free if the
70706          * evaluation of the expression *itself* cannot produce side effects.
70707          * For example, x++ / 3 is side-effect free because the / operator
70708          * does not have side effects.
70709          * The intent is to "smell test" an expression for correctness in positions where
70710          * its value is discarded (e.g. the left side of the comma operator).
70711          */
70712         function isSideEffectFree(node) {
70713             node = ts.skipParentheses(node);
70714             switch (node.kind) {
70715                 case 78 /* Identifier */:
70716                 case 10 /* StringLiteral */:
70717                 case 13 /* RegularExpressionLiteral */:
70718                 case 205 /* TaggedTemplateExpression */:
70719                 case 218 /* TemplateExpression */:
70720                 case 14 /* NoSubstitutionTemplateLiteral */:
70721                 case 8 /* NumericLiteral */:
70722                 case 9 /* BigIntLiteral */:
70723                 case 109 /* TrueKeyword */:
70724                 case 94 /* FalseKeyword */:
70725                 case 103 /* NullKeyword */:
70726                 case 150 /* UndefinedKeyword */:
70727                 case 208 /* FunctionExpression */:
70728                 case 221 /* ClassExpression */:
70729                 case 209 /* ArrowFunction */:
70730                 case 199 /* ArrayLiteralExpression */:
70731                 case 200 /* ObjectLiteralExpression */:
70732                 case 211 /* TypeOfExpression */:
70733                 case 225 /* NonNullExpression */:
70734                 case 274 /* JsxSelfClosingElement */:
70735                 case 273 /* JsxElement */:
70736                     return true;
70737                 case 217 /* ConditionalExpression */:
70738                     return isSideEffectFree(node.whenTrue) &&
70739                         isSideEffectFree(node.whenFalse);
70740                 case 216 /* BinaryExpression */:
70741                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
70742                         return false;
70743                     }
70744                     return isSideEffectFree(node.left) &&
70745                         isSideEffectFree(node.right);
70746                 case 214 /* PrefixUnaryExpression */:
70747                 case 215 /* PostfixUnaryExpression */:
70748                     // Unary operators ~, !, +, and - have no side effects.
70749                     // The rest do.
70750                     switch (node.operator) {
70751                         case 53 /* ExclamationToken */:
70752                         case 39 /* PlusToken */:
70753                         case 40 /* MinusToken */:
70754                         case 54 /* TildeToken */:
70755                             return true;
70756                     }
70757                     return false;
70758                 // Some forms listed here for clarity
70759                 case 212 /* VoidExpression */: // Explicit opt-out
70760                 case 206 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
70761                 case 224 /* AsExpression */: // Not SEF, but can produce useful type warnings
70762                 default:
70763                     return false;
70764             }
70765         }
70766         function isTypeEqualityComparableTo(source, target) {
70767             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
70768         }
70769         var CheckBinaryExpressionState;
70770         (function (CheckBinaryExpressionState) {
70771             CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
70772             CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
70773             CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
70774         })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
70775         function checkBinaryExpression(node, checkMode) {
70776             var workStacks = {
70777                 expr: [node],
70778                 state: [0 /* MaybeCheckLeft */],
70779                 leftType: [undefined]
70780             };
70781             var stackIndex = 0;
70782             var lastResult;
70783             while (stackIndex >= 0) {
70784                 node = workStacks.expr[stackIndex];
70785                 switch (workStacks.state[stackIndex]) {
70786                     case 0 /* MaybeCheckLeft */: {
70787                         if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
70788                             finishInvocation(checkExpression(node.right, checkMode));
70789                             break;
70790                         }
70791                         checkGrammarNullishCoalesceWithLogicalExpression(node);
70792                         var operator = node.operatorToken.kind;
70793                         if (operator === 62 /* EqualsToken */ && (node.left.kind === 200 /* ObjectLiteralExpression */ || node.left.kind === 199 /* ArrayLiteralExpression */)) {
70794                             finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */));
70795                             break;
70796                         }
70797                         advanceState(1 /* CheckRight */);
70798                         maybeCheckExpression(node.left);
70799                         break;
70800                     }
70801                     case 1 /* CheckRight */: {
70802                         var leftType = lastResult;
70803                         workStacks.leftType[stackIndex] = leftType;
70804                         var operator = node.operatorToken.kind;
70805                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
70806                             checkTruthinessOfType(leftType, node.left);
70807                         }
70808                         advanceState(2 /* FinishCheck */);
70809                         maybeCheckExpression(node.right);
70810                         break;
70811                     }
70812                     case 2 /* FinishCheck */: {
70813                         var leftType = workStacks.leftType[stackIndex];
70814                         var rightType = lastResult;
70815                         finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
70816                         break;
70817                     }
70818                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
70819                 }
70820             }
70821             return lastResult;
70822             function finishInvocation(result) {
70823                 lastResult = result;
70824                 stackIndex--;
70825             }
70826             /**
70827              * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
70828              * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
70829              */
70830             function advanceState(nextState) {
70831                 workStacks.state[stackIndex] = nextState;
70832             }
70833             function maybeCheckExpression(node) {
70834                 if (ts.isBinaryExpression(node)) {
70835                     stackIndex++;
70836                     workStacks.expr[stackIndex] = node;
70837                     workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
70838                     workStacks.leftType[stackIndex] = undefined;
70839                 }
70840                 else {
70841                     lastResult = checkExpression(node, checkMode);
70842                 }
70843             }
70844         }
70845         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
70846             var left = node.left, operatorToken = node.operatorToken, right = node.right;
70847             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
70848                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
70849                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
70850                 }
70851                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
70852                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
70853                 }
70854             }
70855         }
70856         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
70857         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
70858         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
70859             var operator = operatorToken.kind;
70860             if (operator === 62 /* EqualsToken */ && (left.kind === 200 /* ObjectLiteralExpression */ || left.kind === 199 /* ArrayLiteralExpression */)) {
70861                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107 /* ThisKeyword */);
70862             }
70863             var leftType;
70864             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
70865                 leftType = checkTruthinessExpression(left, checkMode);
70866             }
70867             else {
70868                 leftType = checkExpression(left, checkMode);
70869             }
70870             var rightType = checkExpression(right, checkMode);
70871             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
70872         }
70873         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
70874             var operator = operatorToken.kind;
70875             switch (operator) {
70876                 case 41 /* AsteriskToken */:
70877                 case 42 /* AsteriskAsteriskToken */:
70878                 case 65 /* AsteriskEqualsToken */:
70879                 case 66 /* AsteriskAsteriskEqualsToken */:
70880                 case 43 /* SlashToken */:
70881                 case 67 /* SlashEqualsToken */:
70882                 case 44 /* PercentToken */:
70883                 case 68 /* PercentEqualsToken */:
70884                 case 40 /* MinusToken */:
70885                 case 64 /* MinusEqualsToken */:
70886                 case 47 /* LessThanLessThanToken */:
70887                 case 69 /* LessThanLessThanEqualsToken */:
70888                 case 48 /* GreaterThanGreaterThanToken */:
70889                 case 70 /* GreaterThanGreaterThanEqualsToken */:
70890                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
70891                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
70892                 case 51 /* BarToken */:
70893                 case 73 /* BarEqualsToken */:
70894                 case 52 /* CaretToken */:
70895                 case 77 /* CaretEqualsToken */:
70896                 case 50 /* AmpersandToken */:
70897                 case 72 /* AmpersandEqualsToken */:
70898                     if (leftType === silentNeverType || rightType === silentNeverType) {
70899                         return silentNeverType;
70900                     }
70901                     leftType = checkNonNullType(leftType, left);
70902                     rightType = checkNonNullType(rightType, right);
70903                     var suggestedOperator = void 0;
70904                     // if a user tries to apply a bitwise operator to 2 boolean operands
70905                     // try and return them a helpful suggestion
70906                     if ((leftType.flags & 528 /* BooleanLike */) &&
70907                         (rightType.flags & 528 /* BooleanLike */) &&
70908                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
70909                         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));
70910                         return numberType;
70911                     }
70912                     else {
70913                         // otherwise just check each operand separately and report errors as normal
70914                         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, /*isAwaitValid*/ true);
70915                         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, /*isAwaitValid*/ true);
70916                         var resultType_1;
70917                         // If both are any or unknown, allow operation; assume it will resolve to number
70918                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
70919                             // Or, if neither could be bigint, implicit coercion results in a number result
70920                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
70921                             resultType_1 = numberType;
70922                         }
70923                         // At least one is assignable to bigint, so check that both are
70924                         else if (bothAreBigIntLike(leftType, rightType)) {
70925                             switch (operator) {
70926                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
70927                                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
70928                                     reportOperatorError();
70929                                     break;
70930                                 case 42 /* AsteriskAsteriskToken */:
70931                                 case 66 /* AsteriskAsteriskEqualsToken */:
70932                                     if (languageVersion < 3 /* ES2016 */) {
70933                                         error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later);
70934                                     }
70935                             }
70936                             resultType_1 = bigintType;
70937                         }
70938                         // Exactly one of leftType/rightType is assignable to bigint
70939                         else {
70940                             reportOperatorError(bothAreBigIntLike);
70941                             resultType_1 = errorType;
70942                         }
70943                         if (leftOk && rightOk) {
70944                             checkAssignmentOperator(resultType_1);
70945                         }
70946                         return resultType_1;
70947                     }
70948                 case 39 /* PlusToken */:
70949                 case 63 /* PlusEqualsToken */:
70950                     if (leftType === silentNeverType || rightType === silentNeverType) {
70951                         return silentNeverType;
70952                     }
70953                     if (!isTypeAssignableToKind(leftType, 402653316 /* StringLike */) && !isTypeAssignableToKind(rightType, 402653316 /* StringLike */)) {
70954                         leftType = checkNonNullType(leftType, left);
70955                         rightType = checkNonNullType(rightType, right);
70956                     }
70957                     var resultType = void 0;
70958                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
70959                         // Operands of an enum type are treated as having the primitive type Number.
70960                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
70961                         resultType = numberType;
70962                     }
70963                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
70964                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
70965                         resultType = bigintType;
70966                     }
70967                     else if (isTypeAssignableToKind(leftType, 402653316 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 402653316 /* StringLike */, /*strict*/ true)) {
70968                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
70969                         resultType = stringType;
70970                     }
70971                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
70972                         // Otherwise, the result is of type Any.
70973                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
70974                         resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
70975                     }
70976                     // Symbols are not allowed at all in arithmetic expressions
70977                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
70978                         return resultType;
70979                     }
70980                     if (!resultType) {
70981                         // Types that have a reasonably good chance of being a valid operand type.
70982                         // If both types have an awaited type of one of these, we'll assume the user
70983                         // might be missing an await without doing an exhaustive check that inserting
70984                         // await(s) will actually be a completely valid binary expression.
70985                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 3 /* AnyOrUnknown */;
70986                         reportOperatorError(function (left, right) {
70987                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
70988                                 isTypeAssignableToKind(right, closeEnoughKind_1);
70989                         });
70990                         return anyType;
70991                     }
70992                     if (operator === 63 /* PlusEqualsToken */) {
70993                         checkAssignmentOperator(resultType);
70994                     }
70995                     return resultType;
70996                 case 29 /* LessThanToken */:
70997                 case 31 /* GreaterThanToken */:
70998                 case 32 /* LessThanEqualsToken */:
70999                 case 33 /* GreaterThanEqualsToken */:
71000                     if (checkForDisallowedESSymbolOperand(operator)) {
71001                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
71002                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
71003                         reportOperatorErrorUnless(function (left, right) {
71004                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
71005                         });
71006                     }
71007                     return booleanType;
71008                 case 34 /* EqualsEqualsToken */:
71009                 case 35 /* ExclamationEqualsToken */:
71010                 case 36 /* EqualsEqualsEqualsToken */:
71011                 case 37 /* ExclamationEqualsEqualsToken */:
71012                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
71013                     return booleanType;
71014                 case 101 /* InstanceOfKeyword */:
71015                     return checkInstanceOfExpression(left, right, leftType, rightType);
71016                 case 100 /* InKeyword */:
71017                     return checkInExpression(left, right, leftType, rightType);
71018                 case 55 /* AmpersandAmpersandToken */:
71019                 case 75 /* AmpersandAmpersandEqualsToken */: {
71020                     var resultType_2 = getTypeFacts(leftType) & 4194304 /* Truthy */ ?
71021                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
71022                         leftType;
71023                     if (operator === 75 /* AmpersandAmpersandEqualsToken */) {
71024                         checkAssignmentOperator(rightType);
71025                     }
71026                     return resultType_2;
71027                 }
71028                 case 56 /* BarBarToken */:
71029                 case 74 /* BarBarEqualsToken */: {
71030                     var resultType_3 = getTypeFacts(leftType) & 8388608 /* Falsy */ ?
71031                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
71032                         leftType;
71033                     if (operator === 74 /* BarBarEqualsToken */) {
71034                         checkAssignmentOperator(rightType);
71035                     }
71036                     return resultType_3;
71037                 }
71038                 case 60 /* QuestionQuestionToken */:
71039                 case 76 /* QuestionQuestionEqualsToken */: {
71040                     var resultType_4 = getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
71041                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
71042                         leftType;
71043                     if (operator === 76 /* QuestionQuestionEqualsToken */) {
71044                         checkAssignmentOperator(rightType);
71045                     }
71046                     return resultType_4;
71047                 }
71048                 case 62 /* EqualsToken */:
71049                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
71050                     checkAssignmentDeclaration(declKind, rightType);
71051                     if (isAssignmentDeclaration(declKind)) {
71052                         if (!(rightType.flags & 524288 /* Object */) ||
71053                             declKind !== 2 /* ModuleExports */ &&
71054                                 declKind !== 6 /* Prototype */ &&
71055                                 !isEmptyObjectType(rightType) &&
71056                                 !isFunctionObjectType(rightType) &&
71057                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
71058                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
71059                             checkAssignmentOperator(rightType);
71060                         }
71061                         return leftType;
71062                     }
71063                     else {
71064                         checkAssignmentOperator(rightType);
71065                         return getRegularTypeOfObjectLiteral(rightType);
71066                     }
71067                 case 27 /* CommaToken */:
71068                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
71069                         var sf = ts.getSourceFileOfNode(left);
71070                         var sourceText = sf.text;
71071                         var start_3 = ts.skipTrivia(sourceText, left.pos);
71072                         var isInDiag2657 = sf.parseDiagnostics.some(function (diag) {
71073                             if (diag.code !== ts.Diagnostics.JSX_expressions_must_have_one_parent_element.code)
71074                                 return false;
71075                             return ts.textSpanContainsPosition(diag, start_3);
71076                         });
71077                         if (!isInDiag2657)
71078                             error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
71079                     }
71080                     return rightType;
71081                 default:
71082                     return ts.Debug.fail();
71083             }
71084             function bothAreBigIntLike(left, right) {
71085                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
71086             }
71087             function checkAssignmentDeclaration(kind, rightType) {
71088                 if (kind === 2 /* ModuleExports */) {
71089                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
71090                         var prop = _a[_i];
71091                         var propType = getTypeOfSymbol(prop);
71092                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
71093                             var name = prop.escapedName;
71094                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
71095                             if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
71096                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
71097                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
71098                             }
71099                         }
71100                     }
71101                 }
71102             }
71103             function isEvalNode(node) {
71104                 return node.kind === 78 /* Identifier */ && node.escapedText === "eval";
71105             }
71106             // Return true if there was no error, false if there was an error.
71107             function checkForDisallowedESSymbolOperand(operator) {
71108                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
71109                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
71110                         undefined;
71111                 if (offendingSymbolOperand) {
71112                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
71113                     return false;
71114                 }
71115                 return true;
71116             }
71117             function getSuggestedBooleanOperator(operator) {
71118                 switch (operator) {
71119                     case 51 /* BarToken */:
71120                     case 73 /* BarEqualsToken */:
71121                         return 56 /* BarBarToken */;
71122                     case 52 /* CaretToken */:
71123                     case 77 /* CaretEqualsToken */:
71124                         return 37 /* ExclamationEqualsEqualsToken */;
71125                     case 50 /* AmpersandToken */:
71126                     case 72 /* AmpersandEqualsToken */:
71127                         return 55 /* AmpersandAmpersandToken */;
71128                     default:
71129                         return undefined;
71130                 }
71131             }
71132             function checkAssignmentOperator(valueType) {
71133                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
71134                     // TypeScript 1.0 spec (April 2014): 4.17
71135                     // An assignment of the form
71136                     //    VarExpr = ValueExpr
71137                     // requires VarExpr to be classified as a reference
71138                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
71139                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
71140                     if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)
71141                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
71142                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
71143                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
71144                     }
71145                 }
71146             }
71147             function isAssignmentDeclaration(kind) {
71148                 var _a;
71149                 switch (kind) {
71150                     case 2 /* ModuleExports */:
71151                         return true;
71152                     case 1 /* ExportsProperty */:
71153                     case 5 /* Property */:
71154                     case 6 /* Prototype */:
71155                     case 3 /* PrototypeProperty */:
71156                     case 4 /* ThisProperty */:
71157                         var symbol = getSymbolOfNode(left);
71158                         var init = ts.getAssignedExpandoInitializer(right);
71159                         return !!init && ts.isObjectLiteralExpression(init) &&
71160                             !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
71161                     default:
71162                         return false;
71163                 }
71164             }
71165             /**
71166              * Returns true if an error is reported
71167              */
71168             function reportOperatorErrorUnless(typesAreCompatible) {
71169                 if (!typesAreCompatible(leftType, rightType)) {
71170                     reportOperatorError(typesAreCompatible);
71171                     return true;
71172                 }
71173                 return false;
71174             }
71175             function reportOperatorError(isRelated) {
71176                 var _a;
71177                 var wouldWorkWithAwait = false;
71178                 var errNode = errorNode || operatorToken;
71179                 if (isRelated) {
71180                     var awaitedLeftType = getAwaitedType(leftType);
71181                     var awaitedRightType = getAwaitedType(rightType);
71182                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
71183                         && !!(awaitedLeftType && awaitedRightType)
71184                         && isRelated(awaitedLeftType, awaitedRightType);
71185                 }
71186                 var effectiveLeft = leftType;
71187                 var effectiveRight = rightType;
71188                 if (!wouldWorkWithAwait && isRelated) {
71189                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
71190                 }
71191                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
71192                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
71193                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
71194                 }
71195             }
71196             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
71197                 var typeName;
71198                 switch (operatorToken.kind) {
71199                     case 36 /* EqualsEqualsEqualsToken */:
71200                     case 34 /* EqualsEqualsToken */:
71201                         typeName = "false";
71202                         break;
71203                     case 37 /* ExclamationEqualsEqualsToken */:
71204                     case 35 /* ExclamationEqualsToken */:
71205                         typeName = "true";
71206                 }
71207                 if (typeName) {
71208                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
71209                 }
71210                 return undefined;
71211             }
71212         }
71213         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
71214             var effectiveLeft = leftType;
71215             var effectiveRight = rightType;
71216             var leftBase = getBaseTypeOfLiteralType(leftType);
71217             var rightBase = getBaseTypeOfLiteralType(rightType);
71218             if (!isRelated(leftBase, rightBase)) {
71219                 effectiveLeft = leftBase;
71220                 effectiveRight = rightBase;
71221             }
71222             return [effectiveLeft, effectiveRight];
71223         }
71224         function checkYieldExpression(node) {
71225             // Grammar checking
71226             if (produceDiagnostics) {
71227                 if (!(node.flags & 8192 /* YieldContext */)) {
71228                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
71229                 }
71230                 if (isInParameterInitializerBeforeContainingFunction(node)) {
71231                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
71232                 }
71233             }
71234             var func = ts.getContainingFunction(node);
71235             if (!func)
71236                 return anyType;
71237             var functionFlags = ts.getFunctionFlags(func);
71238             if (!(functionFlags & 1 /* Generator */)) {
71239                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
71240                 return anyType;
71241             }
71242             var isAsync = (functionFlags & 2 /* Async */) !== 0;
71243             if (node.asteriskToken) {
71244                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
71245                 // and __asyncValues helpers
71246                 if (isAsync && languageVersion < 99 /* ESNext */) {
71247                     checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
71248                 }
71249                 // Generator functions prior to ES2015 require the __values helper
71250                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
71251                     checkExternalEmitHelpers(node, 256 /* Values */);
71252                 }
71253             }
71254             // There is no point in doing an assignability check if the function
71255             // has no explicit return type because the return type is directly computed
71256             // from the yield expressions.
71257             var returnType = getReturnTypeFromAnnotation(func);
71258             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
71259             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
71260             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
71261             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
71262             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
71263             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
71264             if (returnType && yieldedType) {
71265                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
71266             }
71267             if (node.asteriskToken) {
71268                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
71269                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
71270                     || anyType;
71271             }
71272             else if (returnType) {
71273                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
71274                     || anyType;
71275             }
71276             return getContextualIterationType(2 /* Next */, func) || anyType;
71277         }
71278         function checkConditionalExpression(node, checkMode) {
71279             var type = checkTruthinessExpression(node.condition);
71280             checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
71281             var type1 = checkExpression(node.whenTrue, checkMode);
71282             var type2 = checkExpression(node.whenFalse, checkMode);
71283             return getUnionType([type1, type2], 2 /* Subtype */);
71284         }
71285         function checkTemplateExpression(node) {
71286             var texts = [node.head.text];
71287             var types = [];
71288             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
71289                 var span = _a[_i];
71290                 var type = checkExpression(span.expression);
71291                 if (maybeTypeOfKind(type, 12288 /* ESSymbolLike */)) {
71292                     error(span.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
71293                 }
71294                 texts.push(span.literal.text);
71295                 types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType);
71296             }
71297             return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType;
71298         }
71299         function getContextNode(node) {
71300             if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
71301                 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)
71302             }
71303             return node;
71304         }
71305         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
71306             var context = getContextNode(node);
71307             var saveContextualType = context.contextualType;
71308             var saveInferenceContext = context.inferenceContext;
71309             try {
71310                 context.contextualType = contextualType;
71311                 context.inferenceContext = inferenceContext;
71312                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
71313                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
71314                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
71315                 // here would be to not mark contextually typed literals as fresh in the first place.
71316                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
71317                     getRegularTypeOfLiteralType(type) : type;
71318                 return result;
71319             }
71320             finally {
71321                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
71322                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
71323                 // may hold onto the checker that created it.
71324                 context.contextualType = saveContextualType;
71325                 context.inferenceContext = saveInferenceContext;
71326             }
71327         }
71328         function checkExpressionCached(node, checkMode) {
71329             var links = getNodeLinks(node);
71330             if (!links.resolvedType) {
71331                 if (checkMode && checkMode !== 0 /* Normal */) {
71332                     return checkExpression(node, checkMode);
71333                 }
71334                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
71335                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
71336                 // to the top of the stack ensures all transient types are computed from a known point.
71337                 var saveFlowLoopStart = flowLoopStart;
71338                 var saveFlowTypeCache = flowTypeCache;
71339                 flowLoopStart = flowLoopCount;
71340                 flowTypeCache = undefined;
71341                 links.resolvedType = checkExpression(node, checkMode);
71342                 flowTypeCache = saveFlowTypeCache;
71343                 flowLoopStart = saveFlowLoopStart;
71344             }
71345             return links.resolvedType;
71346         }
71347         function isTypeAssertion(node) {
71348             node = ts.skipParentheses(node);
71349             return node.kind === 206 /* TypeAssertionExpression */ || node.kind === 224 /* AsExpression */;
71350         }
71351         function checkDeclarationInitializer(declaration, contextualType) {
71352             var initializer = ts.getEffectiveInitializer(declaration);
71353             var type = getQuickTypeOfExpression(initializer) ||
71354                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
71355             return ts.isParameter(declaration) && declaration.name.kind === 197 /* ArrayBindingPattern */ &&
71356                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
71357                 padTupleType(type, declaration.name) : type;
71358         }
71359         function padTupleType(type, pattern) {
71360             var patternElements = pattern.elements;
71361             var elementTypes = getTypeArguments(type).slice();
71362             var elementFlags = type.target.elementFlags.slice();
71363             for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) {
71364                 var e = patternElements[i];
71365                 if (i < patternElements.length - 1 || !(e.kind === 198 /* BindingElement */ && e.dotDotDotToken)) {
71366                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
71367                     elementFlags.push(2 /* Optional */);
71368                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
71369                         reportImplicitAny(e, anyType);
71370                     }
71371                 }
71372             }
71373             return createTupleType(elementTypes, elementFlags, type.target.readonly);
71374         }
71375         function widenTypeInferredFromInitializer(declaration, type) {
71376             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
71377             if (ts.isInJSFile(declaration)) {
71378                 if (widened.flags & 98304 /* Nullable */) {
71379                     reportImplicitAny(declaration, anyType);
71380                     return anyType;
71381                 }
71382                 else if (isEmptyArrayLiteralType(widened)) {
71383                     reportImplicitAny(declaration, anyArrayType);
71384                     return anyArrayType;
71385                 }
71386             }
71387             return widened;
71388         }
71389         function isLiteralOfContextualType(candidateType, contextualType) {
71390             if (contextualType) {
71391                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
71392                     var types = contextualType.types;
71393                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
71394                 }
71395                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
71396                     // If the contextual type is a type variable constrained to a primitive type, consider
71397                     // this a literal context for literals of that primitive type. For example, given a
71398                     // type parameter 'T extends string', infer string literal types for T.
71399                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
71400                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
71401                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
71402                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
71403                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
71404                         isLiteralOfContextualType(candidateType, constraint);
71405                 }
71406                 // If the contextual type is a literal of a particular primitive type, we consider this a
71407                 // literal context for all literals of that primitive type.
71408                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
71409                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
71410                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
71411                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
71412                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
71413             }
71414             return false;
71415         }
71416         function isConstContext(node) {
71417             var parent = node.parent;
71418             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
71419                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
71420                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent) || ts.isTemplateSpan(parent)) && isConstContext(parent.parent);
71421         }
71422         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
71423             var type = checkExpression(node, checkMode, forceTuple);
71424             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
71425                 isTypeAssertion(node) ? type :
71426                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
71427         }
71428         function checkPropertyAssignment(node, checkMode) {
71429             // Do not use hasDynamicName here, because that returns false for well known symbols.
71430             // We want to perform checkComputedPropertyName for all computed properties, including
71431             // well known symbols.
71432             if (node.name.kind === 158 /* ComputedPropertyName */) {
71433                 checkComputedPropertyName(node.name);
71434             }
71435             return checkExpressionForMutableLocation(node.initializer, checkMode);
71436         }
71437         function checkObjectLiteralMethod(node, checkMode) {
71438             // Grammar checking
71439             checkGrammarMethod(node);
71440             // Do not use hasDynamicName here, because that returns false for well known symbols.
71441             // We want to perform checkComputedPropertyName for all computed properties, including
71442             // well known symbols.
71443             if (node.name.kind === 158 /* ComputedPropertyName */) {
71444                 checkComputedPropertyName(node.name);
71445             }
71446             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
71447             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
71448         }
71449         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
71450             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
71451                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
71452                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
71453                 var signature = callSignature || constructSignature;
71454                 if (signature && signature.typeParameters) {
71455                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
71456                     if (contextualType) {
71457                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
71458                         if (contextualSignature && !contextualSignature.typeParameters) {
71459                             if (checkMode & 8 /* SkipGenericFunctions */) {
71460                                 skippedGenericFunction(node, checkMode);
71461                                 return anyFunctionType;
71462                             }
71463                             var context = getInferenceContext(node);
71464                             // We have an expression that is an argument of a generic function for which we are performing
71465                             // type argument inference. The expression is of a function type with a single generic call
71466                             // signature and a contextual function type with a single non-generic call signature. Now check
71467                             // if the outer function returns a function type with a single non-generic call signature and
71468                             // if some of the outer function type parameters have no inferences so far. If so, we can
71469                             // potentially add inferred type parameters to the outer function return type.
71470                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
71471                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
71472                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
71473                                 // Instantiate the signature with its own type parameters as type arguments, possibly
71474                                 // renaming the type parameters to ensure they have unique names.
71475                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
71476                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
71477                                 // Infer from the parameters of the instantiated signature to the parameters of the
71478                                 // contextual signature starting with an empty set of inference candidates.
71479                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
71480                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
71481                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
71482                                 });
71483                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
71484                                     // We have inference candidates, indicating that one or more type parameters are referenced
71485                                     // in the parameter types of the contextual signature. Now also infer from the return type.
71486                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
71487                                         inferTypes(inferences_3, source, target);
71488                                     });
71489                                     // If the type parameters for which we produced candidates do not have any inferences yet,
71490                                     // we adopt the new inference candidates and add the type parameters of the expression type
71491                                     // to the set of inferred type parameters for the outer function return type.
71492                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
71493                                         mergeInferences(context.inferences, inferences_3);
71494                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
71495                                         return getOrCreateTypeFromSignature(instantiatedSignature);
71496                                     }
71497                                 }
71498                             }
71499                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
71500                         }
71501                     }
71502                 }
71503             }
71504             return type;
71505         }
71506         function skippedGenericFunction(node, checkMode) {
71507             if (checkMode & 2 /* Inferential */) {
71508                 // We have skipped a generic function during inferential typing. Obtain the inference context and
71509                 // indicate this has occurred such that we know a second pass of inference is be needed.
71510                 var context = getInferenceContext(node);
71511                 context.flags |= 4 /* SkippedGenericFunction */;
71512             }
71513         }
71514         function hasInferenceCandidates(info) {
71515             return !!(info.candidates || info.contraCandidates);
71516         }
71517         function hasOverlappingInferences(a, b) {
71518             for (var i = 0; i < a.length; i++) {
71519                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
71520                     return true;
71521                 }
71522             }
71523             return false;
71524         }
71525         function mergeInferences(target, source) {
71526             for (var i = 0; i < target.length; i++) {
71527                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
71528                     target[i] = source[i];
71529                 }
71530             }
71531         }
71532         function getUniqueTypeParameters(context, typeParameters) {
71533             var result = [];
71534             var oldTypeParameters;
71535             var newTypeParameters;
71536             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
71537                 var tp = typeParameters_2[_i];
71538                 var name = tp.symbol.escapedName;
71539                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
71540                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
71541                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
71542                     var newTypeParameter = createTypeParameter(symbol);
71543                     newTypeParameter.target = tp;
71544                     oldTypeParameters = ts.append(oldTypeParameters, tp);
71545                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
71546                     result.push(newTypeParameter);
71547                 }
71548                 else {
71549                     result.push(tp);
71550                 }
71551             }
71552             if (newTypeParameters) {
71553                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
71554                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
71555                     var tp = newTypeParameters_1[_a];
71556                     tp.mapper = mapper;
71557                 }
71558             }
71559             return result;
71560         }
71561         function hasTypeParameterByName(typeParameters, name) {
71562             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
71563         }
71564         function getUniqueTypeParameterName(typeParameters, baseName) {
71565             var len = baseName.length;
71566             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
71567                 len--;
71568             var s = baseName.slice(0, len);
71569             for (var index = 1; true; index++) {
71570                 var augmentedName = (s + index);
71571                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
71572                     return augmentedName;
71573                 }
71574             }
71575         }
71576         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
71577             var signature = getSingleCallSignature(funcType);
71578             if (signature && !signature.typeParameters) {
71579                 return getReturnTypeOfSignature(signature);
71580             }
71581         }
71582         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
71583             var funcType = checkExpression(expr.expression);
71584             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
71585             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
71586             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
71587         }
71588         /**
71589          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
71590          * with computing the type and may not fully check all contained sub-expressions for errors.
71591          */
71592         function getTypeOfExpression(node) {
71593             // Don't bother caching types that require no flow analysis and are quick to compute.
71594             var quickType = getQuickTypeOfExpression(node);
71595             if (quickType) {
71596                 return quickType;
71597             }
71598             // If a type has been cached for the node, return it.
71599             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
71600                 var cachedType = flowTypeCache[getNodeId(node)];
71601                 if (cachedType) {
71602                     return cachedType;
71603                 }
71604             }
71605             var startInvocationCount = flowInvocationCount;
71606             var type = checkExpression(node);
71607             // If control flow analysis was required to determine the type, it is worth caching.
71608             if (flowInvocationCount !== startInvocationCount) {
71609                 var cache = flowTypeCache || (flowTypeCache = []);
71610                 cache[getNodeId(node)] = type;
71611                 ts.setNodeFlags(node, node.flags | 67108864 /* TypeCached */);
71612             }
71613             return type;
71614         }
71615         function getQuickTypeOfExpression(node) {
71616             var expr = ts.skipParentheses(node);
71617             // Optimize for the common case of a call to a function with a single non-generic call
71618             // signature where we can just fetch the return type without checking the arguments.
71619             if (ts.isCallExpression(expr) && expr.expression.kind !== 105 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
71620                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
71621                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
71622                 if (type) {
71623                     return type;
71624                 }
71625             }
71626             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
71627                 return getTypeFromTypeNode(expr.type);
71628             }
71629             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
71630                 node.kind === 109 /* TrueKeyword */ || node.kind === 94 /* FalseKeyword */) {
71631                 return checkExpression(node);
71632             }
71633             return undefined;
71634         }
71635         /**
71636          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
71637          * with computing the type and may not fully check all contained sub-expressions for errors.
71638          * It is intended for uses where you know there is no contextual type,
71639          * and requesting the contextual type might cause a circularity or other bad behaviour.
71640          * It sets the contextual type of the node to any before calling getTypeOfExpression.
71641          */
71642         function getContextFreeTypeOfExpression(node) {
71643             var links = getNodeLinks(node);
71644             if (links.contextFreeType) {
71645                 return links.contextFreeType;
71646             }
71647             var saveContextualType = node.contextualType;
71648             node.contextualType = anyType;
71649             try {
71650                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
71651                 return type;
71652             }
71653             finally {
71654                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
71655                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
71656                 // may hold onto the checker that created it.
71657                 node.contextualType = saveContextualType;
71658             }
71659         }
71660         function checkExpression(node, checkMode, forceTuple) {
71661             ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end });
71662             var saveCurrentNode = currentNode;
71663             currentNode = node;
71664             instantiationCount = 0;
71665             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
71666             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
71667             if (isConstEnumObjectType(type)) {
71668                 checkConstEnumAccess(node, type);
71669             }
71670             currentNode = saveCurrentNode;
71671             ts.tracing.pop();
71672             return type;
71673         }
71674         function checkConstEnumAccess(node, type) {
71675             // enum object type for const enums are only permitted in:
71676             // - 'left' in property access
71677             // - 'object' in indexed access
71678             // - target in rhs of import statement
71679             var ok = (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.expression === node) ||
71680                 (node.parent.kind === 202 /* ElementAccessExpression */ && node.parent.expression === node) ||
71681                 ((node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
71682                     (node.parent.kind === 176 /* TypeQuery */ && node.parent.exprName === node)) ||
71683                 (node.parent.kind === 270 /* ExportSpecifier */); // We allow reexporting const enums
71684             if (!ok) {
71685                 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);
71686             }
71687             if (compilerOptions.isolatedModules) {
71688                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
71689                 var constEnumDeclaration = type.symbol.valueDeclaration;
71690                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
71691                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
71692                 }
71693             }
71694         }
71695         function checkParenthesizedExpression(node, checkMode) {
71696             var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
71697             if (tag) {
71698                 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
71699             }
71700             return checkExpression(node.expression, checkMode);
71701         }
71702         function checkExpressionWorker(node, checkMode, forceTuple) {
71703             var kind = node.kind;
71704             if (cancellationToken) {
71705                 // Only bother checking on a few construct kinds.  We don't want to be excessively
71706                 // hitting the cancellation token on every node we check.
71707                 switch (kind) {
71708                     case 221 /* ClassExpression */:
71709                     case 208 /* FunctionExpression */:
71710                     case 209 /* ArrowFunction */:
71711                         cancellationToken.throwIfCancellationRequested();
71712                 }
71713             }
71714             switch (kind) {
71715                 case 78 /* Identifier */:
71716                     return checkIdentifier(node);
71717                 case 107 /* ThisKeyword */:
71718                     return checkThisExpression(node);
71719                 case 105 /* SuperKeyword */:
71720                     return checkSuperExpression(node);
71721                 case 103 /* NullKeyword */:
71722                     return nullWideningType;
71723                 case 14 /* NoSubstitutionTemplateLiteral */:
71724                 case 10 /* StringLiteral */:
71725                     return getFreshTypeOfLiteralType(getLiteralType(node.text));
71726                 case 8 /* NumericLiteral */:
71727                     checkGrammarNumericLiteral(node);
71728                     return getFreshTypeOfLiteralType(getLiteralType(+node.text));
71729                 case 9 /* BigIntLiteral */:
71730                     checkGrammarBigIntLiteral(node);
71731                     return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
71732                 case 109 /* TrueKeyword */:
71733                     return trueType;
71734                 case 94 /* FalseKeyword */:
71735                     return falseType;
71736                 case 218 /* TemplateExpression */:
71737                     return checkTemplateExpression(node);
71738                 case 13 /* RegularExpressionLiteral */:
71739                     return globalRegExpType;
71740                 case 199 /* ArrayLiteralExpression */:
71741                     return checkArrayLiteral(node, checkMode, forceTuple);
71742                 case 200 /* ObjectLiteralExpression */:
71743                     return checkObjectLiteral(node, checkMode);
71744                 case 201 /* PropertyAccessExpression */:
71745                     return checkPropertyAccessExpression(node);
71746                 case 157 /* QualifiedName */:
71747                     return checkQualifiedName(node);
71748                 case 202 /* ElementAccessExpression */:
71749                     return checkIndexedAccess(node);
71750                 case 203 /* CallExpression */:
71751                     if (node.expression.kind === 99 /* ImportKeyword */) {
71752                         return checkImportCallExpression(node);
71753                     }
71754                 // falls through
71755                 case 204 /* NewExpression */:
71756                     return checkCallExpression(node, checkMode);
71757                 case 205 /* TaggedTemplateExpression */:
71758                     return checkTaggedTemplateExpression(node);
71759                 case 207 /* ParenthesizedExpression */:
71760                     return checkParenthesizedExpression(node, checkMode);
71761                 case 221 /* ClassExpression */:
71762                     return checkClassExpression(node);
71763                 case 208 /* FunctionExpression */:
71764                 case 209 /* ArrowFunction */:
71765                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
71766                 case 211 /* TypeOfExpression */:
71767                     return checkTypeOfExpression(node);
71768                 case 206 /* TypeAssertionExpression */:
71769                 case 224 /* AsExpression */:
71770                     return checkAssertion(node);
71771                 case 225 /* NonNullExpression */:
71772                     return checkNonNullAssertion(node);
71773                 case 226 /* MetaProperty */:
71774                     return checkMetaProperty(node);
71775                 case 210 /* DeleteExpression */:
71776                     return checkDeleteExpression(node);
71777                 case 212 /* VoidExpression */:
71778                     return checkVoidExpression(node);
71779                 case 213 /* AwaitExpression */:
71780                     return checkAwaitExpression(node);
71781                 case 214 /* PrefixUnaryExpression */:
71782                     return checkPrefixUnaryExpression(node);
71783                 case 215 /* PostfixUnaryExpression */:
71784                     return checkPostfixUnaryExpression(node);
71785                 case 216 /* BinaryExpression */:
71786                     return checkBinaryExpression(node, checkMode);
71787                 case 217 /* ConditionalExpression */:
71788                     return checkConditionalExpression(node, checkMode);
71789                 case 220 /* SpreadElement */:
71790                     return checkSpreadExpression(node, checkMode);
71791                 case 222 /* OmittedExpression */:
71792                     return undefinedWideningType;
71793                 case 219 /* YieldExpression */:
71794                     return checkYieldExpression(node);
71795                 case 227 /* SyntheticExpression */:
71796                     return checkSyntheticExpression(node);
71797                 case 283 /* JsxExpression */:
71798                     return checkJsxExpression(node, checkMode);
71799                 case 273 /* JsxElement */:
71800                     return checkJsxElement(node, checkMode);
71801                 case 274 /* JsxSelfClosingElement */:
71802                     return checkJsxSelfClosingElement(node, checkMode);
71803                 case 277 /* JsxFragment */:
71804                     return checkJsxFragment(node);
71805                 case 281 /* JsxAttributes */:
71806                     return checkJsxAttributes(node, checkMode);
71807                 case 275 /* JsxOpeningElement */:
71808                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
71809             }
71810             return errorType;
71811         }
71812         // DECLARATION AND STATEMENT TYPE CHECKING
71813         function checkTypeParameter(node) {
71814             // Grammar Checking
71815             if (node.expression) {
71816                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
71817             }
71818             checkSourceElement(node.constraint);
71819             checkSourceElement(node.default);
71820             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
71821             // Resolve base constraint to reveal circularity errors
71822             getBaseConstraintOfType(typeParameter);
71823             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
71824                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
71825             }
71826             var constraintType = getConstraintOfTypeParameter(typeParameter);
71827             var defaultType = getDefaultFromTypeParameter(typeParameter);
71828             if (constraintType && defaultType) {
71829                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
71830             }
71831             if (produceDiagnostics) {
71832                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
71833             }
71834         }
71835         function checkParameter(node) {
71836             // Grammar checking
71837             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
71838             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
71839             // or if its FunctionBody is strict code(11.1.5).
71840             checkGrammarDecoratorsAndModifiers(node);
71841             checkVariableLikeDeclaration(node);
71842             var func = ts.getContainingFunction(node);
71843             if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) {
71844                 if (!(func.kind === 166 /* Constructor */ && ts.nodeIsPresent(func.body))) {
71845                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
71846                 }
71847                 if (func.kind === 166 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
71848                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
71849                 }
71850             }
71851             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
71852                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
71853             }
71854             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
71855                 if (func.parameters.indexOf(node) !== 0) {
71856                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
71857                 }
71858                 if (func.kind === 166 /* Constructor */ || func.kind === 170 /* ConstructSignature */ || func.kind === 175 /* ConstructorType */) {
71859                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
71860                 }
71861                 if (func.kind === 209 /* ArrowFunction */) {
71862                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
71863                 }
71864                 if (func.kind === 167 /* GetAccessor */ || func.kind === 168 /* SetAccessor */) {
71865                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
71866                 }
71867             }
71868             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
71869             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
71870             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
71871                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
71872             }
71873         }
71874         function checkTypePredicate(node) {
71875             var parent = getTypePredicateParent(node);
71876             if (!parent) {
71877                 // The parent must not be valid.
71878                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
71879                 return;
71880             }
71881             var signature = getSignatureFromDeclaration(parent);
71882             var typePredicate = getTypePredicateOfSignature(signature);
71883             if (!typePredicate) {
71884                 return;
71885             }
71886             checkSourceElement(node.type);
71887             var parameterName = node.parameterName;
71888             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
71889                 getTypeFromThisTypeNode(parameterName);
71890             }
71891             else {
71892                 if (typePredicate.parameterIndex >= 0) {
71893                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
71894                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
71895                     }
71896                     else {
71897                         if (typePredicate.type) {
71898                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
71899                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
71900                             /*headMessage*/ undefined, leadingError);
71901                         }
71902                     }
71903                 }
71904                 else if (parameterName) {
71905                     var hasReportedError = false;
71906                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
71907                         var name = _a[_i].name;
71908                         if (ts.isBindingPattern(name) &&
71909                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
71910                             hasReportedError = true;
71911                             break;
71912                         }
71913                     }
71914                     if (!hasReportedError) {
71915                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
71916                     }
71917                 }
71918             }
71919         }
71920         function getTypePredicateParent(node) {
71921             switch (node.parent.kind) {
71922                 case 209 /* ArrowFunction */:
71923                 case 169 /* CallSignature */:
71924                 case 251 /* FunctionDeclaration */:
71925                 case 208 /* FunctionExpression */:
71926                 case 174 /* FunctionType */:
71927                 case 165 /* MethodDeclaration */:
71928                 case 164 /* MethodSignature */:
71929                     var parent = node.parent;
71930                     if (node === parent.type) {
71931                         return parent;
71932                     }
71933             }
71934         }
71935         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
71936             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
71937                 var element = _a[_i];
71938                 if (ts.isOmittedExpression(element)) {
71939                     continue;
71940                 }
71941                 var name = element.name;
71942                 if (name.kind === 78 /* Identifier */ && name.escapedText === predicateVariableName) {
71943                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
71944                     return true;
71945                 }
71946                 else if (name.kind === 197 /* ArrayBindingPattern */ || name.kind === 196 /* ObjectBindingPattern */) {
71947                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
71948                         return true;
71949                     }
71950                 }
71951             }
71952         }
71953         function checkSignatureDeclaration(node) {
71954             // Grammar checking
71955             if (node.kind === 171 /* IndexSignature */) {
71956                 checkGrammarIndexSignature(node);
71957             }
71958             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
71959             else if (node.kind === 174 /* FunctionType */ || node.kind === 251 /* FunctionDeclaration */ || node.kind === 175 /* ConstructorType */ ||
71960                 node.kind === 169 /* CallSignature */ || node.kind === 166 /* Constructor */ ||
71961                 node.kind === 170 /* ConstructSignature */) {
71962                 checkGrammarFunctionLikeDeclaration(node);
71963             }
71964             var functionFlags = ts.getFunctionFlags(node);
71965             if (!(functionFlags & 4 /* Invalid */)) {
71966                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
71967                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
71968                     checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
71969                 }
71970                 // Async functions prior to ES2017 require the __awaiter helper
71971                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
71972                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
71973                 }
71974                 // Generator functions, Async functions, and Async Generator functions prior to
71975                 // ES2015 require the __generator helper
71976                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
71977                     checkExternalEmitHelpers(node, 128 /* Generator */);
71978                 }
71979             }
71980             checkTypeParameters(node.typeParameters);
71981             ts.forEach(node.parameters, checkParameter);
71982             // TODO(rbuckton): Should we start checking JSDoc types?
71983             if (node.type) {
71984                 checkSourceElement(node.type);
71985             }
71986             if (produceDiagnostics) {
71987                 checkCollisionWithArgumentsInGeneratedCode(node);
71988                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
71989                 if (noImplicitAny && !returnTypeNode) {
71990                     switch (node.kind) {
71991                         case 170 /* ConstructSignature */:
71992                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
71993                             break;
71994                         case 169 /* CallSignature */:
71995                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
71996                             break;
71997                     }
71998                 }
71999                 if (returnTypeNode) {
72000                     var functionFlags_1 = ts.getFunctionFlags(node);
72001                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
72002                         var returnType = getTypeFromTypeNode(returnTypeNode);
72003                         if (returnType === voidType) {
72004                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
72005                         }
72006                         else {
72007                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
72008                             // However, that would not catch the error in the following case.
72009                             //
72010                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
72011                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
72012                             //
72013                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
72014                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
72015                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
72016                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
72017                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
72018                         }
72019                     }
72020                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
72021                         checkAsyncFunctionReturnType(node, returnTypeNode);
72022                     }
72023                 }
72024                 if (node.kind !== 171 /* IndexSignature */ && node.kind !== 308 /* JSDocFunctionType */) {
72025                     registerForUnusedIdentifiersCheck(node);
72026                 }
72027             }
72028         }
72029         function checkClassForDuplicateDeclarations(node) {
72030             var instanceNames = new ts.Map();
72031             var staticNames = new ts.Map();
72032             // instance and static private identifiers share the same scope
72033             var privateIdentifiers = new ts.Map();
72034             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
72035                 var member = _a[_i];
72036                 if (member.kind === 166 /* Constructor */) {
72037                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
72038                         var param = _c[_b];
72039                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
72040                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
72041                         }
72042                     }
72043                 }
72044                 else {
72045                     var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */);
72046                     var name = member.name;
72047                     if (!name) {
72048                         return;
72049                     }
72050                     var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
72051                         isStatic ? staticNames :
72052                             instanceNames;
72053                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
72054                     if (memberName) {
72055                         switch (member.kind) {
72056                             case 167 /* GetAccessor */:
72057                                 addName(names, name, memberName, 1 /* GetAccessor */);
72058                                 break;
72059                             case 168 /* SetAccessor */:
72060                                 addName(names, name, memberName, 2 /* SetAccessor */);
72061                                 break;
72062                             case 163 /* PropertyDeclaration */:
72063                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
72064                                 break;
72065                             case 165 /* MethodDeclaration */:
72066                                 addName(names, name, memberName, 8 /* Method */);
72067                                 break;
72068                         }
72069                     }
72070                 }
72071             }
72072             function addName(names, location, name, meaning) {
72073                 var prev = names.get(name);
72074                 if (prev) {
72075                     if (prev & 8 /* Method */) {
72076                         if (meaning !== 8 /* Method */) {
72077                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
72078                         }
72079                     }
72080                     else if (prev & meaning) {
72081                         error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
72082                     }
72083                     else {
72084                         names.set(name, prev | meaning);
72085                     }
72086                 }
72087                 else {
72088                     names.set(name, meaning);
72089                 }
72090             }
72091         }
72092         /**
72093          * Static members being set on a constructor function may conflict with built-in properties
72094          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
72095          * built-in properties. This check issues a transpile error when a class has a static
72096          * member with the same name as a non-writable built-in property.
72097          *
72098          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
72099          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
72100          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
72101          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
72102          */
72103         function checkClassForStaticPropertyNameConflicts(node) {
72104             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
72105                 var member = _a[_i];
72106                 var memberNameNode = member.name;
72107                 var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */);
72108                 if (isStatic && memberNameNode) {
72109                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
72110                     switch (memberName) {
72111                         case "name":
72112                         case "length":
72113                         case "caller":
72114                         case "arguments":
72115                         case "prototype":
72116                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
72117                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
72118                             error(memberNameNode, message, memberName, className);
72119                             break;
72120                     }
72121                 }
72122             }
72123         }
72124         function checkObjectTypeForDuplicateDeclarations(node) {
72125             var names = new ts.Map();
72126             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
72127                 var member = _a[_i];
72128                 if (member.kind === 162 /* PropertySignature */) {
72129                     var memberName = void 0;
72130                     var name = member.name;
72131                     switch (name.kind) {
72132                         case 10 /* StringLiteral */:
72133                         case 8 /* NumericLiteral */:
72134                             memberName = name.text;
72135                             break;
72136                         case 78 /* Identifier */:
72137                             memberName = ts.idText(name);
72138                             break;
72139                         default:
72140                             continue;
72141                     }
72142                     if (names.get(memberName)) {
72143                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
72144                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
72145                     }
72146                     else {
72147                         names.set(memberName, true);
72148                     }
72149                 }
72150             }
72151         }
72152         function checkTypeForDuplicateIndexSignatures(node) {
72153             if (node.kind === 253 /* InterfaceDeclaration */) {
72154                 var nodeSymbol = getSymbolOfNode(node);
72155                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
72156                 // to prevent this run check only for the first declaration of a given kind
72157                 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
72158                     return;
72159                 }
72160             }
72161             // TypeScript 1.0 spec (April 2014)
72162             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
72163             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
72164             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
72165             if (indexSymbol) {
72166                 var seenNumericIndexer = false;
72167                 var seenStringIndexer = false;
72168                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
72169                     var decl = _a[_i];
72170                     var declaration = decl;
72171                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
72172                         switch (declaration.parameters[0].type.kind) {
72173                             case 147 /* StringKeyword */:
72174                                 if (!seenStringIndexer) {
72175                                     seenStringIndexer = true;
72176                                 }
72177                                 else {
72178                                     error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
72179                                 }
72180                                 break;
72181                             case 144 /* NumberKeyword */:
72182                                 if (!seenNumericIndexer) {
72183                                     seenNumericIndexer = true;
72184                                 }
72185                                 else {
72186                                     error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
72187                                 }
72188                                 break;
72189                         }
72190                     }
72191                 }
72192             }
72193         }
72194         function checkPropertyDeclaration(node) {
72195             // Grammar checking
72196             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
72197                 checkGrammarComputedPropertyName(node.name);
72198             checkVariableLikeDeclaration(node);
72199             // Private class fields transformation relies on WeakMaps.
72200             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
72201                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
72202                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
72203                 }
72204             }
72205         }
72206         function checkPropertySignature(node) {
72207             if (ts.isPrivateIdentifier(node.name)) {
72208                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
72209             }
72210             return checkPropertyDeclaration(node);
72211         }
72212         function checkMethodDeclaration(node) {
72213             // Grammar checking
72214             if (!checkGrammarMethod(node))
72215                 checkGrammarComputedPropertyName(node.name);
72216             if (ts.isPrivateIdentifier(node.name)) {
72217                 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
72218             }
72219             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
72220             checkFunctionOrMethodDeclaration(node);
72221             // Abstract methods cannot have an implementation.
72222             // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
72223             if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 165 /* MethodDeclaration */ && node.body) {
72224                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
72225             }
72226         }
72227         function checkConstructorDeclaration(node) {
72228             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
72229             checkSignatureDeclaration(node);
72230             // Grammar check for checking only related to constructorDeclaration
72231             if (!checkGrammarConstructorTypeParameters(node))
72232                 checkGrammarConstructorTypeAnnotation(node);
72233             checkSourceElement(node.body);
72234             var symbol = getSymbolOfNode(node);
72235             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
72236             // Only type check the symbol once
72237             if (node === firstDeclaration) {
72238                 checkFunctionOrConstructorSymbol(symbol);
72239             }
72240             // exit early in the case of signature - super checks are not relevant to them
72241             if (ts.nodeIsMissing(node.body)) {
72242                 return;
72243             }
72244             if (!produceDiagnostics) {
72245                 return;
72246             }
72247             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
72248                 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
72249                     return true;
72250                 }
72251                 return n.kind === 163 /* PropertyDeclaration */ &&
72252                     !ts.hasSyntacticModifier(n, 32 /* Static */) &&
72253                     !!n.initializer;
72254             }
72255             // TS 1.0 spec (April 2014): 8.3.2
72256             // Constructors of classes with no extends clause may not contain super calls, whereas
72257             // constructors of derived classes must contain at least one super call somewhere in their function body.
72258             var containingClassDecl = node.parent;
72259             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
72260                 captureLexicalThis(node.parent, containingClassDecl);
72261                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
72262                 var superCall = findFirstSuperCall(node.body);
72263                 if (superCall) {
72264                     if (classExtendsNull) {
72265                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
72266                     }
72267                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
72268                     // if both of the following are true:
72269                     // - The containing class is a derived class.
72270                     // - The constructor declares parameter properties
72271                     //   or the containing class declares instance member variables with initializers.
72272                     var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
72273                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
72274                             ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); }));
72275                     // Skip past any prologue directives to find the first statement
72276                     // to ensure that it was a super call.
72277                     if (superCallShouldBeFirst) {
72278                         var statements = node.body.statements;
72279                         var superCallStatement = void 0;
72280                         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
72281                             var statement = statements_4[_i];
72282                             if (statement.kind === 233 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
72283                                 superCallStatement = statement;
72284                                 break;
72285                             }
72286                             if (!ts.isPrologueDirective(statement)) {
72287                                 break;
72288                             }
72289                         }
72290                         if (!superCallStatement) {
72291                             error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers);
72292                         }
72293                     }
72294                 }
72295                 else if (!classExtendsNull) {
72296                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
72297                 }
72298             }
72299         }
72300         function checkAccessorDeclaration(node) {
72301             if (produceDiagnostics) {
72302                 // Grammar checking accessors
72303                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
72304                     checkGrammarComputedPropertyName(node.name);
72305                 checkDecorators(node);
72306                 checkSignatureDeclaration(node);
72307                 if (node.kind === 167 /* GetAccessor */) {
72308                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
72309                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
72310                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
72311                         }
72312                     }
72313                 }
72314                 // Do not use hasDynamicName here, because that returns false for well known symbols.
72315                 // We want to perform checkComputedPropertyName for all computed properties, including
72316                 // well known symbols.
72317                 if (node.name.kind === 158 /* ComputedPropertyName */) {
72318                     checkComputedPropertyName(node.name);
72319                 }
72320                 if (ts.isPrivateIdentifier(node.name)) {
72321                     error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
72322                 }
72323                 if (!hasNonBindableDynamicName(node)) {
72324                     // TypeScript 1.0 spec (April 2014): 8.4.3
72325                     // Accessors for the same member name must specify the same accessibility.
72326                     var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
72327                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
72328                     if (otherAccessor) {
72329                         var nodeFlags = ts.getEffectiveModifierFlags(node);
72330                         var otherFlags = ts.getEffectiveModifierFlags(otherAccessor);
72331                         if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
72332                             error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
72333                         }
72334                         if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
72335                             error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
72336                         }
72337                         // TypeScript 1.0 spec (April 2014): 4.5
72338                         // If both accessors include type annotations, the specified types must be identical.
72339                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
72340                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
72341                     }
72342                 }
72343                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
72344                 if (node.kind === 167 /* GetAccessor */) {
72345                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
72346                 }
72347             }
72348             checkSourceElement(node.body);
72349         }
72350         function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
72351             var firstType = getAnnotatedType(first);
72352             var secondType = getAnnotatedType(second);
72353             if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
72354                 error(first, message);
72355             }
72356         }
72357         function checkMissingDeclaration(node) {
72358             checkDecorators(node);
72359         }
72360         function getEffectiveTypeArguments(node, typeParameters) {
72361             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
72362         }
72363         function checkTypeArgumentConstraints(node, typeParameters) {
72364             var typeArguments;
72365             var mapper;
72366             var result = true;
72367             for (var i = 0; i < typeParameters.length; i++) {
72368                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
72369                 if (constraint) {
72370                     if (!typeArguments) {
72371                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
72372                         mapper = createTypeMapper(typeParameters, typeArguments);
72373                     }
72374                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
72375                 }
72376             }
72377             return result;
72378         }
72379         function getTypeParametersForTypeReference(node) {
72380             var type = getTypeFromTypeReference(node);
72381             if (type !== errorType) {
72382                 var symbol = getNodeLinks(node).resolvedSymbol;
72383                 if (symbol) {
72384                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
72385                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
72386                 }
72387             }
72388             return undefined;
72389         }
72390         function checkTypeReferenceNode(node) {
72391             checkGrammarTypeArguments(node, node.typeArguments);
72392             if (node.kind === 173 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
72393                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
72394             }
72395             ts.forEach(node.typeArguments, checkSourceElement);
72396             var type = getTypeFromTypeReference(node);
72397             if (type !== errorType) {
72398                 if (node.typeArguments && produceDiagnostics) {
72399                     var typeParameters = getTypeParametersForTypeReference(node);
72400                     if (typeParameters) {
72401                         checkTypeArgumentConstraints(node, typeParameters);
72402                     }
72403                 }
72404                 var symbol = getNodeLinks(node).resolvedSymbol;
72405                 if (symbol) {
72406                     if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) {
72407                         errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName);
72408                     }
72409                     if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) {
72410                         error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
72411                     }
72412                 }
72413             }
72414         }
72415         function getTypeArgumentConstraint(node) {
72416             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
72417             if (!typeReferenceNode)
72418                 return undefined;
72419             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
72420             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
72421             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
72422         }
72423         function checkTypeQuery(node) {
72424             getTypeFromTypeQueryNode(node);
72425         }
72426         function checkTypeLiteral(node) {
72427             ts.forEach(node.members, checkSourceElement);
72428             if (produceDiagnostics) {
72429                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
72430                 checkIndexConstraints(type);
72431                 checkTypeForDuplicateIndexSignatures(node);
72432                 checkObjectTypeForDuplicateDeclarations(node);
72433             }
72434         }
72435         function checkArrayType(node) {
72436             checkSourceElement(node.elementType);
72437         }
72438         function checkTupleType(node) {
72439             var elementTypes = node.elements;
72440             var seenOptionalElement = false;
72441             var seenRestElement = false;
72442             var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember);
72443             for (var i = 0; i < elementTypes.length; i++) {
72444                 var e = elementTypes[i];
72445                 if (e.kind !== 192 /* NamedTupleMember */ && hasNamedElement) {
72446                     grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names);
72447                     break;
72448                 }
72449                 var flags = getTupleElementFlags(e);
72450                 if (flags & 8 /* Variadic */) {
72451                     var type = getTypeFromTypeNode(e.type);
72452                     if (!isArrayLikeType(type)) {
72453                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
72454                         break;
72455                     }
72456                     if (isArrayType(type) || isTupleType(type) && type.target.combinedFlags & 4 /* Rest */) {
72457                         seenRestElement = true;
72458                     }
72459                 }
72460                 else if (flags & 4 /* Rest */) {
72461                     seenRestElement = true;
72462                 }
72463                 else if (flags & 2 /* Optional */) {
72464                     seenOptionalElement = true;
72465                 }
72466                 else if (seenOptionalElement) {
72467                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
72468                     break;
72469                 }
72470                 if (seenRestElement && i !== elementTypes.length - 1) {
72471                     grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
72472                     break;
72473                 }
72474             }
72475             ts.forEach(node.elements, checkSourceElement);
72476             getTypeFromTypeNode(node);
72477         }
72478         function checkUnionOrIntersectionType(node) {
72479             ts.forEach(node.types, checkSourceElement);
72480             getTypeFromTypeNode(node);
72481         }
72482         function checkIndexedAccessIndexType(type, accessNode) {
72483             if (!(type.flags & 8388608 /* IndexedAccess */)) {
72484                 return type;
72485             }
72486             // Check if the index type is assignable to 'keyof T' for the object type.
72487             var objectType = type.objectType;
72488             var indexType = type.indexType;
72489             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
72490                 if (accessNode.kind === 202 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
72491                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
72492                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
72493                 }
72494                 return type;
72495             }
72496             // Check if we're indexing with a numeric type and if either object or index types
72497             // is a generic type with a constraint that has a numeric index signature.
72498             var apparentObjectType = getApparentType(objectType);
72499             if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
72500                 return type;
72501             }
72502             if (isGenericObjectType(objectType)) {
72503                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
72504                 if (propertyName_1) {
72505                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
72506                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
72507                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
72508                         return errorType;
72509                     }
72510                 }
72511             }
72512             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
72513             return errorType;
72514         }
72515         function checkIndexedAccessType(node) {
72516             checkSourceElement(node.objectType);
72517             checkSourceElement(node.indexType);
72518             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
72519         }
72520         function checkMappedType(node) {
72521             checkSourceElement(node.typeParameter);
72522             checkSourceElement(node.nameType);
72523             checkSourceElement(node.type);
72524             if (!node.type) {
72525                 reportImplicitAny(node, anyType);
72526             }
72527             var type = getTypeFromMappedTypeNode(node);
72528             var nameType = getNameTypeFromMappedType(type);
72529             if (nameType) {
72530                 checkTypeAssignableTo(nameType, keyofConstraintType, node.nameType);
72531             }
72532             else {
72533                 var constraintType = getConstraintTypeFromMappedType(type);
72534                 checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
72535             }
72536         }
72537         function checkThisType(node) {
72538             getTypeFromThisTypeNode(node);
72539         }
72540         function checkTypeOperator(node) {
72541             checkGrammarTypeOperatorNode(node);
72542             checkSourceElement(node.type);
72543         }
72544         function checkConditionalType(node) {
72545             ts.forEachChild(node, checkSourceElement);
72546         }
72547         function checkInferType(node) {
72548             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 184 /* ConditionalType */ && n.parent.extendsType === n; })) {
72549                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
72550             }
72551             checkSourceElement(node.typeParameter);
72552             registerForUnusedIdentifiersCheck(node);
72553         }
72554         function checkTemplateLiteralType(node) {
72555             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
72556                 var span = _a[_i];
72557                 checkSourceElement(span.type);
72558                 var type = getTypeFromTypeNode(span.type);
72559                 checkTypeAssignableTo(type, templateConstraintType, span.type);
72560             }
72561             getTypeFromTypeNode(node);
72562         }
72563         function checkImportType(node) {
72564             checkSourceElement(node.argument);
72565             getTypeFromTypeNode(node);
72566         }
72567         function checkNamedTupleMember(node) {
72568             if (node.dotDotDotToken && node.questionToken) {
72569                 grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest);
72570             }
72571             if (node.type.kind === 180 /* OptionalType */) {
72572                 grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type);
72573             }
72574             if (node.type.kind === 181 /* RestType */) {
72575                 grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type);
72576             }
72577             checkSourceElement(node.type);
72578             getTypeFromTypeNode(node);
72579         }
72580         function isPrivateWithinAmbient(node) {
72581             return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
72582         }
72583         function getEffectiveDeclarationFlags(n, flagsToCheck) {
72584             var flags = ts.getCombinedModifierFlags(n);
72585             // children of classes (even ambient classes) should not be marked as ambient or export
72586             // because those flags have no useful semantics there.
72587             if (n.parent.kind !== 253 /* InterfaceDeclaration */ &&
72588                 n.parent.kind !== 252 /* ClassDeclaration */ &&
72589                 n.parent.kind !== 221 /* ClassExpression */ &&
72590                 n.flags & 8388608 /* Ambient */) {
72591                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
72592                     // It is nested in an ambient context, which means it is automatically exported
72593                     flags |= 1 /* Export */;
72594                 }
72595                 flags |= 2 /* Ambient */;
72596             }
72597             return flags & flagsToCheck;
72598         }
72599         function checkFunctionOrConstructorSymbol(symbol) {
72600             if (!produceDiagnostics) {
72601                 return;
72602             }
72603             function getCanonicalOverload(overloads, implementation) {
72604                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
72605                 // Error on all deviations from this canonical set of flags
72606                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
72607                 // report the errors on those. To achieve this, we will say that the implementation is
72608                 // the canonical signature only if it is in the same container as the first overload
72609                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
72610                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
72611             }
72612             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
72613                 // Error if some overloads have a flag that is not shared by all overloads. To find the
72614                 // deviations, we XOR someOverloadFlags with allOverloadFlags
72615                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
72616                 if (someButNotAllOverloadFlags !== 0) {
72617                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
72618                     ts.forEach(overloads, function (o) {
72619                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
72620                         if (deviation & 1 /* Export */) {
72621                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
72622                         }
72623                         else if (deviation & 2 /* Ambient */) {
72624                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
72625                         }
72626                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
72627                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
72628                         }
72629                         else if (deviation & 128 /* Abstract */) {
72630                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
72631                         }
72632                     });
72633                 }
72634             }
72635             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
72636                 if (someHaveQuestionToken !== allHaveQuestionToken) {
72637                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
72638                     ts.forEach(overloads, function (o) {
72639                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
72640                         if (deviation) {
72641                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
72642                         }
72643                     });
72644                 }
72645             }
72646             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
72647             var someNodeFlags = 0 /* None */;
72648             var allNodeFlags = flagsToCheck;
72649             var someHaveQuestionToken = false;
72650             var allHaveQuestionToken = true;
72651             var hasOverloads = false;
72652             var bodyDeclaration;
72653             var lastSeenNonAmbientDeclaration;
72654             var previousDeclaration;
72655             var declarations = symbol.declarations;
72656             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
72657             function reportImplementationExpectedError(node) {
72658                 if (node.name && ts.nodeIsMissing(node.name)) {
72659                     return;
72660                 }
72661                 var seen = false;
72662                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
72663                     if (seen) {
72664                         return c;
72665                     }
72666                     else {
72667                         seen = c === node;
72668                     }
72669                 });
72670                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
72671                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
72672                 if (subsequentNode && subsequentNode.pos === node.end) {
72673                     if (subsequentNode.kind === node.kind) {
72674                         var errorNode_1 = subsequentNode.name || subsequentNode;
72675                         var subsequentName = subsequentNode.name;
72676                         if (node.name && subsequentName && (
72677                         // both are private identifiers
72678                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
72679                             // Both are computed property names
72680                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
72681                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
72682                             // Both are literal property names that are the same.
72683                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
72684                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
72685                             var reportError = (node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */) &&
72686                                 ts.hasSyntacticModifier(node, 32 /* Static */) !== ts.hasSyntacticModifier(subsequentNode, 32 /* Static */);
72687                             // we can get here in two cases
72688                             // 1. mixed static and instance class members
72689                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
72690                             // here we'll report error only for the first case since for second we should already report error in binder
72691                             if (reportError) {
72692                                 var diagnostic = ts.hasSyntacticModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
72693                                 error(errorNode_1, diagnostic);
72694                             }
72695                             return;
72696                         }
72697                         if (ts.nodeIsPresent(subsequentNode.body)) {
72698                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
72699                             return;
72700                         }
72701                     }
72702                 }
72703                 var errorNode = node.name || node;
72704                 if (isConstructor) {
72705                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
72706                 }
72707                 else {
72708                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
72709                     // the node in question is abstract.
72710                     if (ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
72711                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
72712                     }
72713                     else {
72714                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
72715                     }
72716                 }
72717             }
72718             var duplicateFunctionDeclaration = false;
72719             var multipleConstructorImplementation = false;
72720             var hasNonAmbientClass = false;
72721             var functionDeclarations = [];
72722             for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
72723                 var current = declarations_4[_i];
72724                 var node = current;
72725                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
72726                 var inAmbientContextOrInterface = node.parent && (node.parent.kind === 253 /* InterfaceDeclaration */ || node.parent.kind === 177 /* TypeLiteral */) || inAmbientContext;
72727                 if (inAmbientContextOrInterface) {
72728                     // check if declarations are consecutive only if they are non-ambient
72729                     // 1. ambient declarations can be interleaved
72730                     // i.e. this is legal
72731                     //     declare function foo();
72732                     //     declare function bar();
72733                     //     declare function foo();
72734                     // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
72735                     previousDeclaration = undefined;
72736                 }
72737                 if ((node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */) && !inAmbientContext) {
72738                     hasNonAmbientClass = true;
72739                 }
72740                 if (node.kind === 251 /* FunctionDeclaration */ || node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */ || node.kind === 166 /* Constructor */) {
72741                     functionDeclarations.push(node);
72742                     var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
72743                     someNodeFlags |= currentNodeFlags;
72744                     allNodeFlags &= currentNodeFlags;
72745                     someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
72746                     allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
72747                     var bodyIsPresent = ts.nodeIsPresent(node.body);
72748                     if (bodyIsPresent && bodyDeclaration) {
72749                         if (isConstructor) {
72750                             multipleConstructorImplementation = true;
72751                         }
72752                         else {
72753                             duplicateFunctionDeclaration = true;
72754                         }
72755                     }
72756                     else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) {
72757                         reportImplementationExpectedError(previousDeclaration);
72758                     }
72759                     if (bodyIsPresent) {
72760                         if (!bodyDeclaration) {
72761                             bodyDeclaration = node;
72762                         }
72763                     }
72764                     else {
72765                         hasOverloads = true;
72766                     }
72767                     previousDeclaration = node;
72768                     if (!inAmbientContextOrInterface) {
72769                         lastSeenNonAmbientDeclaration = node;
72770                     }
72771                 }
72772             }
72773             if (multipleConstructorImplementation) {
72774                 ts.forEach(functionDeclarations, function (declaration) {
72775                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
72776                 });
72777             }
72778             if (duplicateFunctionDeclaration) {
72779                 ts.forEach(functionDeclarations, function (declaration) {
72780                     error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_function_implementation);
72781                 });
72782             }
72783             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
72784                 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
72785                 // TODO: The below just replicates our older error from when classes and functions were
72786                 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
72787                 // might be warranted. :shrug:
72788                 ts.forEach(declarations, function (declaration) {
72789                     addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
72790                 });
72791             }
72792             // Abstract methods can't have an implementation -- in particular, they don't need one.
72793             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
72794                 !ts.hasSyntacticModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
72795                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
72796             }
72797             if (hasOverloads) {
72798                 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
72799                 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
72800                 if (bodyDeclaration) {
72801                     var signatures = getSignaturesOfSymbol(symbol);
72802                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
72803                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
72804                         var signature = signatures_10[_a];
72805                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
72806                             ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
72807                             break;
72808                         }
72809                     }
72810                 }
72811             }
72812         }
72813         function checkExportsOnMergedDeclarations(node) {
72814             if (!produceDiagnostics) {
72815                 return;
72816             }
72817             // if localSymbol is defined on node then node itself is exported - check is required
72818             var symbol = node.localSymbol;
72819             if (!symbol) {
72820                 // local symbol is undefined => this declaration is non-exported.
72821                 // however symbol might contain other declarations that are exported
72822                 symbol = getSymbolOfNode(node);
72823                 if (!symbol.exportSymbol) {
72824                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
72825                     return;
72826                 }
72827             }
72828             // run the check only for the first declaration in the list
72829             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
72830                 return;
72831             }
72832             var exportedDeclarationSpaces = 0 /* None */;
72833             var nonExportedDeclarationSpaces = 0 /* None */;
72834             var defaultExportedDeclarationSpaces = 0 /* None */;
72835             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
72836                 var d = _a[_i];
72837                 var declarationSpaces = getDeclarationSpaces(d);
72838                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
72839                 if (effectiveDeclarationFlags & 1 /* Export */) {
72840                     if (effectiveDeclarationFlags & 512 /* Default */) {
72841                         defaultExportedDeclarationSpaces |= declarationSpaces;
72842                     }
72843                     else {
72844                         exportedDeclarationSpaces |= declarationSpaces;
72845                     }
72846                 }
72847                 else {
72848                     nonExportedDeclarationSpaces |= declarationSpaces;
72849                 }
72850             }
72851             // Spaces for anything not declared a 'default export'.
72852             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
72853             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
72854             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
72855             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
72856                 // declaration spaces for exported and non-exported declarations intersect
72857                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
72858                     var d = _c[_b];
72859                     var declarationSpaces = getDeclarationSpaces(d);
72860                     var name = ts.getNameOfDeclaration(d);
72861                     // Only error on the declarations that contributed to the intersecting spaces.
72862                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
72863                         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));
72864                     }
72865                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
72866                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
72867                     }
72868                 }
72869             }
72870             function getDeclarationSpaces(decl) {
72871                 var d = decl;
72872                 switch (d.kind) {
72873                     case 253 /* InterfaceDeclaration */:
72874                     case 254 /* TypeAliasDeclaration */:
72875                     // A jsdoc typedef and callback are, by definition, type aliases.
72876                     // falls through
72877                     case 331 /* JSDocTypedefTag */:
72878                     case 324 /* JSDocCallbackTag */:
72879                     case 325 /* JSDocEnumTag */:
72880                         return 2 /* ExportType */;
72881                     case 256 /* ModuleDeclaration */:
72882                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
72883                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
72884                             : 4 /* ExportNamespace */;
72885                     case 252 /* ClassDeclaration */:
72886                     case 255 /* EnumDeclaration */:
72887                     case 291 /* EnumMember */:
72888                         return 2 /* ExportType */ | 1 /* ExportValue */;
72889                     case 297 /* SourceFile */:
72890                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
72891                     case 266 /* ExportAssignment */:
72892                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
72893                         if (!ts.isEntityNameExpression(d.expression)) {
72894                             return 1 /* ExportValue */;
72895                         }
72896                         d = d.expression;
72897                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
72898                     // falls through
72899                     case 260 /* ImportEqualsDeclaration */:
72900                     case 263 /* NamespaceImport */:
72901                     case 262 /* ImportClause */:
72902                         var result_12 = 0 /* None */;
72903                         var target = resolveAlias(getSymbolOfNode(d));
72904                         ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); });
72905                         return result_12;
72906                     case 249 /* VariableDeclaration */:
72907                     case 198 /* BindingElement */:
72908                     case 251 /* FunctionDeclaration */:
72909                     case 265 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
72910                     case 78 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
72911                         // Identifiers are used as declarations of assignment declarations whose parents may be
72912                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
72913                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
72914                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
72915                         // all of which are pretty much always values, or at least imply a value meaning.
72916                         // It may be apprpriate to treat these as aliases in the future.
72917                         return 1 /* ExportValue */;
72918                     default:
72919                         return ts.Debug.failBadSyntaxKind(d);
72920                 }
72921             }
72922         }
72923         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
72924             var promisedType = getPromisedTypeOfPromise(type, errorNode);
72925             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
72926         }
72927         /**
72928          * Gets the "promised type" of a promise.
72929          * @param type The type of the promise.
72930          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
72931          */
72932         function getPromisedTypeOfPromise(type, errorNode) {
72933             //
72934             //  { // type
72935             //      then( // thenFunction
72936             //          onfulfilled: ( // onfulfilledParameterType
72937             //              value: T // valueParameterType
72938             //          ) => any
72939             //      ): any;
72940             //  }
72941             //
72942             if (isTypeAny(type)) {
72943                 return undefined;
72944             }
72945             var typeAsPromise = type;
72946             if (typeAsPromise.promisedTypeOfPromise) {
72947                 return typeAsPromise.promisedTypeOfPromise;
72948             }
72949             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
72950                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
72951             }
72952             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
72953             if (isTypeAny(thenFunction)) {
72954                 return undefined;
72955             }
72956             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
72957             if (thenSignatures.length === 0) {
72958                 if (errorNode) {
72959                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
72960                 }
72961                 return undefined;
72962             }
72963             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
72964             if (isTypeAny(onfulfilledParameterType)) {
72965                 return undefined;
72966             }
72967             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
72968             if (onfulfilledParameterSignatures.length === 0) {
72969                 if (errorNode) {
72970                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
72971                 }
72972                 return undefined;
72973             }
72974             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
72975         }
72976         /**
72977          * Gets the "awaited type" of a type.
72978          * @param type The type to await.
72979          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
72980          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
72981          * The runtime behavior of the `await` keyword.
72982          */
72983         function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
72984             var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
72985             return awaitedType || errorType;
72986         }
72987         /**
72988          * Determines whether a type has a callable `then` member.
72989          */
72990         function isThenableType(type) {
72991             var thenFunction = getTypeOfPropertyOfType(type, "then");
72992             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
72993         }
72994         /**
72995          * Gets the "awaited type" of a type.
72996          *
72997          * The "awaited type" of an expression is its "promised type" if the expression is a
72998          * Promise-like type; otherwise, it is the type of the expression. If the "promised
72999          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
73000          * non-promise type is found.
73001          *
73002          * This is used to reflect the runtime behavior of the `await` keyword.
73003          */
73004         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
73005             if (isTypeAny(type)) {
73006                 return type;
73007             }
73008             var typeAsAwaitable = type;
73009             if (typeAsAwaitable.awaitedTypeOfType) {
73010                 return typeAsAwaitable.awaitedTypeOfType;
73011             }
73012             // For a union, get a union of the awaited types of each constituent.
73013             //
73014             return typeAsAwaitable.awaitedTypeOfType =
73015                 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
73016         }
73017         function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
73018             var typeAsAwaitable = type;
73019             if (typeAsAwaitable.awaitedTypeOfType) {
73020                 return typeAsAwaitable.awaitedTypeOfType;
73021             }
73022             var promisedType = getPromisedTypeOfPromise(type);
73023             if (promisedType) {
73024                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
73025                     // Verify that we don't have a bad actor in the form of a promise whose
73026                     // promised type is the same as the promise type, or a mutually recursive
73027                     // promise. If so, we return undefined as we cannot guess the shape. If this
73028                     // were the actual case in the JavaScript, this Promise would never resolve.
73029                     //
73030                     // An example of a bad actor with a singly-recursive promise type might
73031                     // be:
73032                     //
73033                     //  interface BadPromise {
73034                     //      then(
73035                     //          onfulfilled: (value: BadPromise) => any,
73036                     //          onrejected: (error: any) => any): BadPromise;
73037                     //  }
73038                     //
73039                     // The above interface will pass the PromiseLike check, and return a
73040                     // promised type of `BadPromise`. Since this is a self reference, we
73041                     // don't want to keep recursing ad infinitum.
73042                     //
73043                     // An example of a bad actor in the form of a mutually-recursive
73044                     // promise type might be:
73045                     //
73046                     //  interface BadPromiseA {
73047                     //      then(
73048                     //          onfulfilled: (value: BadPromiseB) => any,
73049                     //          onrejected: (error: any) => any): BadPromiseB;
73050                     //  }
73051                     //
73052                     //  interface BadPromiseB {
73053                     //      then(
73054                     //          onfulfilled: (value: BadPromiseA) => any,
73055                     //          onrejected: (error: any) => any): BadPromiseA;
73056                     //  }
73057                     //
73058                     if (errorNode) {
73059                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
73060                     }
73061                     return undefined;
73062                 }
73063                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
73064                 // See the comments above for more information.
73065                 awaitedTypeStack.push(type.id);
73066                 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
73067                 awaitedTypeStack.pop();
73068                 if (!awaitedType) {
73069                     return undefined;
73070                 }
73071                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
73072             }
73073             // The type was not a promise, so it could not be unwrapped any further.
73074             // As long as the type does not have a callable "then" property, it is
73075             // safe to return the type; otherwise, an error is reported and we return
73076             // undefined.
73077             //
73078             // An example of a non-promise "thenable" might be:
73079             //
73080             //  await { then(): void {} }
73081             //
73082             // The "thenable" does not match the minimal definition for a promise. When
73083             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
73084             // will never settle. We treat this as an error to help flag an early indicator
73085             // of a runtime problem. If the user wants to return this value from an async
73086             // function, they would need to wrap it in some other value. If they want it to
73087             // be treated as a promise, they can cast to <any>.
73088             if (isThenableType(type)) {
73089                 if (errorNode) {
73090                     if (!diagnosticMessage)
73091                         return ts.Debug.fail();
73092                     error(errorNode, diagnosticMessage, arg0);
73093                 }
73094                 return undefined;
73095             }
73096             return typeAsAwaitable.awaitedTypeOfType = type;
73097         }
73098         /**
73099          * Checks the return type of an async function to ensure it is a compatible
73100          * Promise implementation.
73101          *
73102          * This checks that an async function has a valid Promise-compatible return type.
73103          * An async function has a valid Promise-compatible return type if the resolved value
73104          * of the return type has a construct signature that takes in an `initializer` function
73105          * that in turn supplies a `resolve` function as one of its arguments and results in an
73106          * object with a callable `then` signature.
73107          *
73108          * @param node The signature to check
73109          */
73110         function checkAsyncFunctionReturnType(node, returnTypeNode) {
73111             // As part of our emit for an async function, we will need to emit the entity name of
73112             // the return type annotation as an expression. To meet the necessary runtime semantics
73113             // for __awaiter, we must also check that the type of the declaration (e.g. the static
73114             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
73115             //
73116             // An example might be (from lib.es6.d.ts):
73117             //
73118             //  interface Promise<T> { ... }
73119             //  interface PromiseConstructor {
73120             //      new <T>(...): Promise<T>;
73121             //  }
73122             //  declare var Promise: PromiseConstructor;
73123             //
73124             // When an async function declares a return type annotation of `Promise<T>`, we
73125             // need to get the type of the `Promise` variable declaration above, which would
73126             // be `PromiseConstructor`.
73127             //
73128             // The same case applies to a class:
73129             //
73130             //  declare class Promise<T> {
73131             //      constructor(...);
73132             //      then<U>(...): Promise<U>;
73133             //  }
73134             //
73135             var returnType = getTypeFromTypeNode(returnTypeNode);
73136             if (languageVersion >= 2 /* ES2015 */) {
73137                 if (returnType === errorType) {
73138                     return;
73139                 }
73140                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
73141                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
73142                     // The promise type was not a valid type reference to the global promise type, so we
73143                     // report an error and return the unknown type.
73144                     error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedType(returnType) || voidType));
73145                     return;
73146                 }
73147             }
73148             else {
73149                 // Always mark the type node as referenced if it points to a value
73150                 markTypeNodeAsReferenced(returnTypeNode);
73151                 if (returnType === errorType) {
73152                     return;
73153                 }
73154                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
73155                 if (promiseConstructorName === undefined) {
73156                     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));
73157                     return;
73158                 }
73159                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
73160                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
73161                 if (promiseConstructorType === errorType) {
73162                     if (promiseConstructorName.kind === 78 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
73163                         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);
73164                     }
73165                     else {
73166                         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));
73167                     }
73168                     return;
73169                 }
73170                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
73171                 if (globalPromiseConstructorLikeType === emptyObjectType) {
73172                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
73173                     // compatibility with __awaiter.
73174                     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));
73175                     return;
73176                 }
73177                 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)) {
73178                     return;
73179                 }
73180                 // Verify there is no local declaration that could collide with the promise constructor.
73181                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
73182                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
73183                 if (collidingSymbol) {
73184                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
73185                     return;
73186                 }
73187             }
73188             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);
73189         }
73190         /** Check a decorator */
73191         function checkDecorator(node) {
73192             var signature = getResolvedSignature(node);
73193             checkDeprecatedSignature(signature, node);
73194             var returnType = getReturnTypeOfSignature(signature);
73195             if (returnType.flags & 1 /* Any */) {
73196                 return;
73197             }
73198             var expectedReturnType;
73199             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
73200             var errorInfo;
73201             switch (node.parent.kind) {
73202                 case 252 /* ClassDeclaration */:
73203                     var classSymbol = getSymbolOfNode(node.parent);
73204                     var classConstructorType = getTypeOfSymbol(classSymbol);
73205                     expectedReturnType = getUnionType([classConstructorType, voidType]);
73206                     break;
73207                 case 160 /* Parameter */:
73208                     expectedReturnType = voidType;
73209                     errorInfo = ts.chainDiagnosticMessages(
73210                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
73211                     break;
73212                 case 163 /* PropertyDeclaration */:
73213                     expectedReturnType = voidType;
73214                     errorInfo = ts.chainDiagnosticMessages(
73215                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
73216                     break;
73217                 case 165 /* MethodDeclaration */:
73218                 case 167 /* GetAccessor */:
73219                 case 168 /* SetAccessor */:
73220                     var methodType = getTypeOfNode(node.parent);
73221                     var descriptorType = createTypedPropertyDescriptorType(methodType);
73222                     expectedReturnType = getUnionType([descriptorType, voidType]);
73223                     break;
73224                 default:
73225                     return ts.Debug.fail();
73226             }
73227             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
73228         }
73229         /**
73230          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
73231          * marked as referenced to prevent import elision.
73232          */
73233         function markTypeNodeAsReferenced(node) {
73234             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
73235         }
73236         function markEntityNameOrEntityExpressionAsReference(typeName) {
73237             if (!typeName)
73238                 return;
73239             var rootName = ts.getFirstIdentifier(typeName);
73240             var meaning = (typeName.kind === 78 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
73241             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
73242             if (rootSymbol
73243                 && rootSymbol.flags & 2097152 /* Alias */
73244                 && symbolIsValue(rootSymbol)
73245                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
73246                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
73247                 markAliasSymbolAsReferenced(rootSymbol);
73248             }
73249         }
73250         /**
73251          * This function marks the type used for metadata decorator as referenced if it is import
73252          * from external module.
73253          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
73254          * union and intersection type
73255          * @param node
73256          */
73257         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
73258             var entityName = getEntityNameForDecoratorMetadata(node);
73259             if (entityName && ts.isEntityName(entityName)) {
73260                 markEntityNameOrEntityExpressionAsReference(entityName);
73261             }
73262         }
73263         function getEntityNameForDecoratorMetadata(node) {
73264             if (node) {
73265                 switch (node.kind) {
73266                     case 183 /* IntersectionType */:
73267                     case 182 /* UnionType */:
73268                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
73269                     case 184 /* ConditionalType */:
73270                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
73271                     case 186 /* ParenthesizedType */:
73272                     case 192 /* NamedTupleMember */:
73273                         return getEntityNameForDecoratorMetadata(node.type);
73274                     case 173 /* TypeReference */:
73275                         return node.typeName;
73276                 }
73277             }
73278         }
73279         function getEntityNameForDecoratorMetadataFromTypeList(types) {
73280             var commonEntityName;
73281             for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
73282                 var typeNode = types_21[_i];
73283                 while (typeNode.kind === 186 /* ParenthesizedType */ || typeNode.kind === 192 /* NamedTupleMember */) {
73284                     typeNode = typeNode.type; // Skip parens if need be
73285                 }
73286                 if (typeNode.kind === 141 /* NeverKeyword */) {
73287                     continue; // Always elide `never` from the union/intersection if possible
73288                 }
73289                 if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) {
73290                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
73291                 }
73292                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
73293                 if (!individualEntityName) {
73294                     // Individual is something like string number
73295                     // So it would be serialized to either that type or object
73296                     // Safe to return here
73297                     return undefined;
73298                 }
73299                 if (commonEntityName) {
73300                     // Note this is in sync with the transformation that happens for type node.
73301                     // Keep this in sync with serializeUnionOrIntersectionType
73302                     // Verify if they refer to same entity and is identifier
73303                     // return undefined if they dont match because we would emit object
73304                     if (!ts.isIdentifier(commonEntityName) ||
73305                         !ts.isIdentifier(individualEntityName) ||
73306                         commonEntityName.escapedText !== individualEntityName.escapedText) {
73307                         return undefined;
73308                     }
73309                 }
73310                 else {
73311                     commonEntityName = individualEntityName;
73312                 }
73313             }
73314             return commonEntityName;
73315         }
73316         function getParameterTypeNodeForDecoratorCheck(node) {
73317             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
73318             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
73319         }
73320         /** Check the decorators of a node */
73321         function checkDecorators(node) {
73322             if (!node.decorators) {
73323                 return;
73324             }
73325             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
73326             // checkGrammarDecorators.
73327             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
73328                 return;
73329             }
73330             if (!compilerOptions.experimentalDecorators) {
73331                 error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning);
73332             }
73333             var firstDecorator = node.decorators[0];
73334             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
73335             if (node.kind === 160 /* Parameter */) {
73336                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
73337             }
73338             if (compilerOptions.emitDecoratorMetadata) {
73339                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
73340                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
73341                 switch (node.kind) {
73342                     case 252 /* ClassDeclaration */:
73343                         var constructor = ts.getFirstConstructorWithBody(node);
73344                         if (constructor) {
73345                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
73346                                 var parameter = _a[_i];
73347                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
73348                             }
73349                         }
73350                         break;
73351                     case 167 /* GetAccessor */:
73352                     case 168 /* SetAccessor */:
73353                         var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
73354                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
73355                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
73356                         break;
73357                     case 165 /* MethodDeclaration */:
73358                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
73359                             var parameter = _c[_b];
73360                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
73361                         }
73362                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
73363                         break;
73364                     case 163 /* PropertyDeclaration */:
73365                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
73366                         break;
73367                     case 160 /* Parameter */:
73368                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
73369                         var containingSignature = node.parent;
73370                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
73371                             var parameter = _e[_d];
73372                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
73373                         }
73374                         break;
73375                 }
73376             }
73377             ts.forEach(node.decorators, checkDecorator);
73378         }
73379         function checkFunctionDeclaration(node) {
73380             if (produceDiagnostics) {
73381                 checkFunctionOrMethodDeclaration(node);
73382                 checkGrammarForGenerator(node);
73383                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
73384                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
73385             }
73386         }
73387         function checkJSDocTypeAliasTag(node) {
73388             if (!node.typeExpression) {
73389                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
73390                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
73391             }
73392             if (node.name) {
73393                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
73394             }
73395             checkSourceElement(node.typeExpression);
73396         }
73397         function checkJSDocTemplateTag(node) {
73398             checkSourceElement(node.constraint);
73399             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
73400                 var tp = _a[_i];
73401                 checkSourceElement(tp);
73402             }
73403         }
73404         function checkJSDocTypeTag(node) {
73405             checkSourceElement(node.typeExpression);
73406         }
73407         function checkJSDocParameterTag(node) {
73408             checkSourceElement(node.typeExpression);
73409             if (!ts.getParameterSymbolFromJSDoc(node)) {
73410                 var decl = ts.getHostSignatureFromJSDoc(node);
73411                 // don't issue an error for invalid hosts -- just functions --
73412                 // and give a better error message when the host function mentions `arguments`
73413                 // but the tag doesn't have an array type
73414                 if (decl) {
73415                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
73416                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
73417                         return;
73418                     }
73419                     if (!containsArgumentsReference(decl)) {
73420                         if (ts.isQualifiedName(node.name)) {
73421                             error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left));
73422                         }
73423                         else {
73424                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
73425                         }
73426                     }
73427                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
73428                         node.typeExpression && node.typeExpression.type &&
73429                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
73430                         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 === 157 /* QualifiedName */ ? node.name.right : node.name));
73431                     }
73432                 }
73433             }
73434         }
73435         function checkJSDocPropertyTag(node) {
73436             checkSourceElement(node.typeExpression);
73437         }
73438         function checkJSDocFunctionType(node) {
73439             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
73440                 reportImplicitAny(node, anyType);
73441             }
73442             checkSignatureDeclaration(node);
73443         }
73444         function checkJSDocImplementsTag(node) {
73445             var classLike = ts.getEffectiveJSDocHost(node);
73446             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
73447                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
73448             }
73449         }
73450         function checkJSDocAugmentsTag(node) {
73451             var classLike = ts.getEffectiveJSDocHost(node);
73452             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
73453                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
73454                 return;
73455             }
73456             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
73457             ts.Debug.assert(augmentsTags.length > 0);
73458             if (augmentsTags.length > 1) {
73459                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
73460             }
73461             var name = getIdentifierFromEntityNameExpression(node.class.expression);
73462             var extend = ts.getClassExtendsHeritageElement(classLike);
73463             if (extend) {
73464                 var className = getIdentifierFromEntityNameExpression(extend.expression);
73465                 if (className && name.escapedText !== className.escapedText) {
73466                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
73467                 }
73468             }
73469         }
73470         function getIdentifierFromEntityNameExpression(node) {
73471             switch (node.kind) {
73472                 case 78 /* Identifier */:
73473                     return node;
73474                 case 201 /* PropertyAccessExpression */:
73475                     return node.name;
73476                 default:
73477                     return undefined;
73478             }
73479         }
73480         function checkFunctionOrMethodDeclaration(node) {
73481             checkDecorators(node);
73482             checkSignatureDeclaration(node);
73483             var functionFlags = ts.getFunctionFlags(node);
73484             // Do not use hasDynamicName here, because that returns false for well known symbols.
73485             // We want to perform checkComputedPropertyName for all computed properties, including
73486             // well known symbols.
73487             if (node.name && node.name.kind === 158 /* ComputedPropertyName */) {
73488                 // This check will account for methods in class/interface declarations,
73489                 // as well as accessors in classes/object literals
73490                 checkComputedPropertyName(node.name);
73491             }
73492             if (!hasNonBindableDynamicName(node)) {
73493                 // first we want to check the local symbol that contain this declaration
73494                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
73495                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
73496                 var symbol = getSymbolOfNode(node);
73497                 var localSymbol = node.localSymbol || symbol;
73498                 // Since the javascript won't do semantic analysis like typescript,
73499                 // if the javascript file comes before the typescript file and both contain same name functions,
73500                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
73501                 var firstDeclaration = ts.find(localSymbol.declarations, 
73502                 // Get first non javascript function declaration
73503                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
73504                 // Only type check the symbol once
73505                 if (node === firstDeclaration) {
73506                     checkFunctionOrConstructorSymbol(localSymbol);
73507                 }
73508                 if (symbol.parent) {
73509                     // run check on export symbol to check that modifiers agree across all exported declarations
73510                     checkFunctionOrConstructorSymbol(symbol);
73511                 }
73512             }
73513             var body = node.kind === 164 /* MethodSignature */ ? undefined : node.body;
73514             checkSourceElement(body);
73515             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
73516             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
73517                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
73518                 // in an ambient context
73519                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
73520                     reportImplicitAny(node, anyType);
73521                 }
73522                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
73523                     // A generator with a body and no type annotation can still cause errors. It can error if the
73524                     // yielded values have no common supertype, or it can give an implicit any error if it has no
73525                     // yielded values. The only way to trigger these errors is to try checking its return type.
73526                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
73527                 }
73528             }
73529             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
73530             if (ts.isInJSFile(node)) {
73531                 var typeTag = ts.getJSDocTypeTag(node);
73532                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
73533                     error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
73534                 }
73535             }
73536         }
73537         function registerForUnusedIdentifiersCheck(node) {
73538             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
73539             if (produceDiagnostics) {
73540                 var sourceFile = ts.getSourceFileOfNode(node);
73541                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
73542                 if (!potentiallyUnusedIdentifiers) {
73543                     potentiallyUnusedIdentifiers = [];
73544                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
73545                 }
73546                 // TODO: GH#22580
73547                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
73548                 potentiallyUnusedIdentifiers.push(node);
73549             }
73550         }
73551         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
73552             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
73553                 var node = potentiallyUnusedIdentifiers_1[_i];
73554                 switch (node.kind) {
73555                     case 252 /* ClassDeclaration */:
73556                     case 221 /* ClassExpression */:
73557                         checkUnusedClassMembers(node, addDiagnostic);
73558                         checkUnusedTypeParameters(node, addDiagnostic);
73559                         break;
73560                     case 297 /* SourceFile */:
73561                     case 256 /* ModuleDeclaration */:
73562                     case 230 /* Block */:
73563                     case 258 /* CaseBlock */:
73564                     case 237 /* ForStatement */:
73565                     case 238 /* ForInStatement */:
73566                     case 239 /* ForOfStatement */:
73567                         checkUnusedLocalsAndParameters(node, addDiagnostic);
73568                         break;
73569                     case 166 /* Constructor */:
73570                     case 208 /* FunctionExpression */:
73571                     case 251 /* FunctionDeclaration */:
73572                     case 209 /* ArrowFunction */:
73573                     case 165 /* MethodDeclaration */:
73574                     case 167 /* GetAccessor */:
73575                     case 168 /* SetAccessor */:
73576                         if (node.body) { // Don't report unused parameters in overloads
73577                             checkUnusedLocalsAndParameters(node, addDiagnostic);
73578                         }
73579                         checkUnusedTypeParameters(node, addDiagnostic);
73580                         break;
73581                     case 164 /* MethodSignature */:
73582                     case 169 /* CallSignature */:
73583                     case 170 /* ConstructSignature */:
73584                     case 174 /* FunctionType */:
73585                     case 175 /* ConstructorType */:
73586                     case 254 /* TypeAliasDeclaration */:
73587                     case 253 /* InterfaceDeclaration */:
73588                         checkUnusedTypeParameters(node, addDiagnostic);
73589                         break;
73590                     case 185 /* InferType */:
73591                         checkUnusedInferTypeParameter(node, addDiagnostic);
73592                         break;
73593                     default:
73594                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
73595                 }
73596             }
73597         }
73598         function errorUnusedLocal(declaration, name, addDiagnostic) {
73599             var node = ts.getNameOfDeclaration(declaration) || declaration;
73600             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
73601             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
73602         }
73603         function isIdentifierThatStartsWithUnderscore(node) {
73604             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
73605         }
73606         function checkUnusedClassMembers(node, addDiagnostic) {
73607             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
73608                 var member = _a[_i];
73609                 switch (member.kind) {
73610                     case 165 /* MethodDeclaration */:
73611                     case 163 /* PropertyDeclaration */:
73612                     case 167 /* GetAccessor */:
73613                     case 168 /* SetAccessor */:
73614                         if (member.kind === 168 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
73615                             // Already would have reported an error on the getter.
73616                             break;
73617                         }
73618                         var symbol = getSymbolOfNode(member);
73619                         if (!symbol.isReferenced
73620                             && (ts.hasEffectiveModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
73621                             && !(member.flags & 8388608 /* Ambient */)) {
73622                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
73623                         }
73624                         break;
73625                     case 166 /* Constructor */:
73626                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
73627                             var parameter = _c[_b];
73628                             if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) {
73629                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
73630                             }
73631                         }
73632                         break;
73633                     case 171 /* IndexSignature */:
73634                     case 229 /* SemicolonClassElement */:
73635                         // Can't be private
73636                         break;
73637                     default:
73638                         ts.Debug.fail();
73639                 }
73640             }
73641         }
73642         function checkUnusedInferTypeParameter(node, addDiagnostic) {
73643             var typeParameter = node.typeParameter;
73644             if (isTypeParameterUnused(typeParameter)) {
73645                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
73646             }
73647         }
73648         function checkUnusedTypeParameters(node, addDiagnostic) {
73649             // Only report errors on the last declaration for the type parameter container;
73650             // this ensures that all uses have been accounted for.
73651             if (ts.last(getSymbolOfNode(node).declarations) !== node)
73652                 return;
73653             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
73654             var seenParentsWithEveryUnused = new ts.Set();
73655             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
73656                 var typeParameter = typeParameters_3[_i];
73657                 if (!isTypeParameterUnused(typeParameter))
73658                     continue;
73659                 var name = ts.idText(typeParameter.name);
73660                 var parent = typeParameter.parent;
73661                 if (parent.kind !== 185 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
73662                     if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) {
73663                         var range = ts.isJSDocTemplateTag(parent)
73664                             // Whole @template tag
73665                             ? ts.rangeOfNode(parent)
73666                             // Include the `<>` in the error message
73667                             : ts.rangeOfTypeParameters(parent.typeParameters);
73668                         var only = parent.typeParameters.length === 1;
73669                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
73670                         var arg0 = only ? name : undefined;
73671                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
73672                     }
73673                 }
73674                 else {
73675                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
73676                 }
73677             }
73678         }
73679         function isTypeParameterUnused(typeParameter) {
73680             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
73681         }
73682         function addToGroup(map, key, value, getKey) {
73683             var keyString = String(getKey(key));
73684             var group = map.get(keyString);
73685             if (group) {
73686                 group[1].push(value);
73687             }
73688             else {
73689                 map.set(keyString, [key, [value]]);
73690             }
73691         }
73692         function tryGetRootParameterDeclaration(node) {
73693             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
73694         }
73695         function isValidUnusedLocalDeclaration(declaration) {
73696             if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
73697                 return !!ts.findAncestor(declaration.parent, function (ancestor) {
73698                     return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
73699                         ts.isForOfStatement(ancestor) ? true : "quit";
73700                 });
73701             }
73702             return ts.isAmbientModule(declaration) ||
73703                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
73704         }
73705         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
73706             // 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.
73707             var unusedImports = new ts.Map();
73708             var unusedDestructures = new ts.Map();
73709             var unusedVariables = new ts.Map();
73710             nodeWithLocals.locals.forEach(function (local) {
73711                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
73712                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
73713                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
73714                     return;
73715                 }
73716                 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
73717                     var declaration = _a[_i];
73718                     if (isValidUnusedLocalDeclaration(declaration)) {
73719                         continue;
73720                     }
73721                     if (isImportedDeclaration(declaration)) {
73722                         addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
73723                     }
73724                     else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
73725                         // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
73726                         var lastElement = ts.last(declaration.parent.elements);
73727                         if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
73728                             addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
73729                         }
73730                     }
73731                     else if (ts.isVariableDeclaration(declaration)) {
73732                         addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
73733                     }
73734                     else {
73735                         var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
73736                         var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
73737                         if (parameter && name) {
73738                             if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
73739                                 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
73740                             }
73741                         }
73742                         else {
73743                             errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
73744                         }
73745                     }
73746                 }
73747             });
73748             unusedImports.forEach(function (_a) {
73749                 var importClause = _a[0], unuseds = _a[1];
73750                 var importDecl = importClause.parent;
73751                 var nDeclarations = (importClause.name ? 1 : 0) +
73752                     (importClause.namedBindings ?
73753                         (importClause.namedBindings.kind === 263 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
73754                         : 0);
73755                 if (nDeclarations === unuseds.length) {
73756                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
73757                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
73758                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
73759                 }
73760                 else {
73761                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
73762                         var unused = unuseds_1[_i];
73763                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
73764                     }
73765                 }
73766             });
73767             unusedDestructures.forEach(function (_a) {
73768                 var bindingPattern = _a[0], bindingElements = _a[1];
73769                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
73770                 if (bindingPattern.elements.length === bindingElements.length) {
73771                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 249 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 250 /* VariableDeclarationList */) {
73772                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
73773                     }
73774                     else {
73775                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
73776                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
73777                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
73778                     }
73779                 }
73780                 else {
73781                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
73782                         var e = bindingElements_1[_i];
73783                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
73784                     }
73785                 }
73786             });
73787             unusedVariables.forEach(function (_a) {
73788                 var declarationList = _a[0], declarations = _a[1];
73789                 if (declarationList.declarations.length === declarations.length) {
73790                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
73791                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
73792                         : ts.createDiagnosticForNode(declarationList.parent.kind === 232 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
73793                 }
73794                 else {
73795                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
73796                         var decl = declarations_5[_i];
73797                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
73798                     }
73799                 }
73800             });
73801         }
73802         function bindingNameText(name) {
73803             switch (name.kind) {
73804                 case 78 /* Identifier */:
73805                     return ts.idText(name);
73806                 case 197 /* ArrayBindingPattern */:
73807                 case 196 /* ObjectBindingPattern */:
73808                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
73809                 default:
73810                     return ts.Debug.assertNever(name);
73811             }
73812         }
73813         function isImportedDeclaration(node) {
73814             return node.kind === 262 /* ImportClause */ || node.kind === 265 /* ImportSpecifier */ || node.kind === 263 /* NamespaceImport */;
73815         }
73816         function importClauseFromImported(decl) {
73817             return decl.kind === 262 /* ImportClause */ ? decl : decl.kind === 263 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
73818         }
73819         function checkBlock(node) {
73820             // Grammar checking for SyntaxKind.Block
73821             if (node.kind === 230 /* Block */) {
73822                 checkGrammarStatementInAmbientContext(node);
73823             }
73824             if (ts.isFunctionOrModuleBlock(node)) {
73825                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
73826                 ts.forEach(node.statements, checkSourceElement);
73827                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
73828             }
73829             else {
73830                 ts.forEach(node.statements, checkSourceElement);
73831             }
73832             if (node.locals) {
73833                 registerForUnusedIdentifiersCheck(node);
73834             }
73835         }
73836         function checkCollisionWithArgumentsInGeneratedCode(node) {
73837             // no rest parameters \ declaration context \ overload - no codegen impact
73838             if (languageVersion >= 2 /* ES2015 */ || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
73839                 return;
73840             }
73841             ts.forEach(node.parameters, function (p) {
73842                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
73843                     errorSkippedOn("noEmit", p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
73844                 }
73845             });
73846         }
73847         function needCollisionCheckForIdentifier(node, identifier, name) {
73848             if (!(identifier && identifier.escapedText === name)) {
73849                 return false;
73850             }
73851             if (node.kind === 163 /* PropertyDeclaration */ ||
73852                 node.kind === 162 /* PropertySignature */ ||
73853                 node.kind === 165 /* MethodDeclaration */ ||
73854                 node.kind === 164 /* MethodSignature */ ||
73855                 node.kind === 167 /* GetAccessor */ ||
73856                 node.kind === 168 /* SetAccessor */) {
73857                 // it is ok to have member named '_super' or '_this' - member access is always qualified
73858                 return false;
73859             }
73860             if (node.flags & 8388608 /* Ambient */) {
73861                 // ambient context - no codegen impact
73862                 return false;
73863             }
73864             var root = ts.getRootDeclaration(node);
73865             if (root.kind === 160 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
73866                 // just an overload - no codegen impact
73867                 return false;
73868             }
73869             return true;
73870         }
73871         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
73872         function checkIfThisIsCapturedInEnclosingScope(node) {
73873             ts.findAncestor(node, function (current) {
73874                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
73875                     var isDeclaration_1 = node.kind !== 78 /* Identifier */;
73876                     if (isDeclaration_1) {
73877                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
73878                     }
73879                     else {
73880                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
73881                     }
73882                     return true;
73883                 }
73884                 return false;
73885             });
73886         }
73887         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
73888             ts.findAncestor(node, function (current) {
73889                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
73890                     var isDeclaration_2 = node.kind !== 78 /* Identifier */;
73891                     if (isDeclaration_2) {
73892                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
73893                     }
73894                     else {
73895                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
73896                     }
73897                     return true;
73898                 }
73899                 return false;
73900             });
73901         }
73902         function checkWeakMapCollision(node) {
73903             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
73904             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
73905                 errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
73906             }
73907         }
73908         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
73909             // No need to check for require or exports for ES6 modules and later
73910             if (moduleKind >= ts.ModuleKind.ES2015) {
73911                 return;
73912             }
73913             if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
73914                 return;
73915             }
73916             // Uninstantiated modules shouldnt do this check
73917             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
73918                 return;
73919             }
73920             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
73921             var parent = getDeclarationContainer(node);
73922             if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
73923                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
73924                 errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
73925             }
73926         }
73927         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
73928             if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) {
73929                 return;
73930             }
73931             // Uninstantiated modules shouldnt do this check
73932             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
73933                 return;
73934             }
73935             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
73936             var parent = getDeclarationContainer(node);
73937             if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
73938                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
73939                 errorSkippedOn("noEmit", 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));
73940             }
73941         }
73942         function checkVarDeclaredNamesNotShadowed(node) {
73943             // - ScriptBody : StatementList
73944             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
73945             // also occurs in the VarDeclaredNames of StatementList.
73946             // - Block : { StatementList }
73947             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
73948             // also occurs in the VarDeclaredNames of StatementList.
73949             // Variable declarations are hoisted to the top of their function scope. They can shadow
73950             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
73951             // by the binder as the declaration scope is different.
73952             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
73953             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
73954             // block declared value. this is fine for let, but not const.
73955             // Only consider declarations with initializers, uninitialized const declarations will not
73956             // step on a let/const variable.
73957             // Do not consider const and const declarations, as duplicate block-scoped declarations
73958             // are handled by the binder.
73959             // We are only looking for const declarations that step on let\const declarations from a
73960             // different scope. e.g.:
73961             //      {
73962             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
73963             //          const x = 0; // symbol for this declaration will be 'symbol'
73964             //      }
73965             // skip block-scoped variables and parameters
73966             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
73967                 return;
73968             }
73969             // skip variable declarations that don't have initializers
73970             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
73971             // so we'll always treat binding elements as initialized
73972             if (node.kind === 249 /* VariableDeclaration */ && !node.initializer) {
73973                 return;
73974             }
73975             var symbol = getSymbolOfNode(node);
73976             if (symbol.flags & 1 /* FunctionScopedVariable */) {
73977                 if (!ts.isIdentifier(node.name))
73978                     return ts.Debug.fail();
73979                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
73980                 if (localDeclarationSymbol &&
73981                     localDeclarationSymbol !== symbol &&
73982                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
73983                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
73984                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 250 /* VariableDeclarationList */);
73985                         var container = varDeclList.parent.kind === 232 /* VariableStatement */ && varDeclList.parent.parent
73986                             ? varDeclList.parent.parent
73987                             : undefined;
73988                         // names of block-scoped and function scoped variables can collide only
73989                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
73990                         var namesShareScope = container &&
73991                             (container.kind === 230 /* Block */ && ts.isFunctionLike(container.parent) ||
73992                                 container.kind === 257 /* ModuleBlock */ ||
73993                                 container.kind === 256 /* ModuleDeclaration */ ||
73994                                 container.kind === 297 /* SourceFile */);
73995                         // here we know that function scoped variable is shadowed by block scoped one
73996                         // if they are defined in the same scope - binder has already reported redeclaration error
73997                         // otherwise if variable has an initializer - show error that initialization will fail
73998                         // since LHS will be block scoped name instead of function scoped
73999                         if (!namesShareScope) {
74000                             var name = symbolToString(localDeclarationSymbol);
74001                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
74002                         }
74003                     }
74004                 }
74005             }
74006         }
74007         function convertAutoToAny(type) {
74008             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
74009         }
74010         // Check variable, parameter, or property declaration
74011         function checkVariableLikeDeclaration(node) {
74012             var _a;
74013             checkDecorators(node);
74014             if (!ts.isBindingElement(node)) {
74015                 checkSourceElement(node.type);
74016             }
74017             // JSDoc `function(string, string): string` syntax results in parameters with no name
74018             if (!node.name) {
74019                 return;
74020             }
74021             // For a computed property, just check the initializer and exit
74022             // Do not use hasDynamicName here, because that returns false for well known symbols.
74023             // We want to perform checkComputedPropertyName for all computed properties, including
74024             // well known symbols.
74025             if (node.name.kind === 158 /* ComputedPropertyName */) {
74026                 checkComputedPropertyName(node.name);
74027                 if (node.initializer) {
74028                     checkExpressionCached(node.initializer);
74029                 }
74030             }
74031             if (node.kind === 198 /* BindingElement */) {
74032                 if (node.parent.kind === 196 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
74033                     checkExternalEmitHelpers(node, 4 /* Rest */);
74034                 }
74035                 // check computed properties inside property names of binding elements
74036                 if (node.propertyName && node.propertyName.kind === 158 /* ComputedPropertyName */) {
74037                     checkComputedPropertyName(node.propertyName);
74038                 }
74039                 // check private/protected variable access
74040                 var parent = node.parent.parent;
74041                 var parentType = getTypeForBindingElementParent(parent);
74042                 var name = node.propertyName || node.name;
74043                 if (parentType && !ts.isBindingPattern(name)) {
74044                     var exprType = getLiteralTypeFromPropertyName(name);
74045                     if (isTypeUsableAsPropertyName(exprType)) {
74046                         var nameText = getPropertyNameFromType(exprType);
74047                         var property = getPropertyOfType(parentType, nameText);
74048                         if (property) {
74049                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
74050                             checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, parentType, property);
74051                         }
74052                     }
74053                 }
74054             }
74055             // For a binding pattern, check contained binding elements
74056             if (ts.isBindingPattern(node.name)) {
74057                 if (node.name.kind === 197 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
74058                     checkExternalEmitHelpers(node, 512 /* Read */);
74059                 }
74060                 ts.forEach(node.name.elements, checkSourceElement);
74061             }
74062             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
74063             if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
74064                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
74065                 return;
74066             }
74067             // For a binding pattern, validate the initializer and exit
74068             if (ts.isBindingPattern(node.name)) {
74069                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 238 /* ForInStatement */;
74070                 var needCheckWidenedType = node.name.elements.length === 0;
74071                 if (needCheckInitializer || needCheckWidenedType) {
74072                     // Don't validate for-in initializer as it is already an error
74073                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
74074                     if (needCheckInitializer) {
74075                         var initializerType = checkExpressionCached(node.initializer);
74076                         if (strictNullChecks && needCheckWidenedType) {
74077                             checkNonNullNonVoidType(initializerType, node);
74078                         }
74079                         else {
74080                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
74081                         }
74082                     }
74083                     // check the binding pattern with empty elements
74084                     if (needCheckWidenedType) {
74085                         if (ts.isArrayBindingPattern(node.name)) {
74086                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
74087                         }
74088                         else if (strictNullChecks) {
74089                             checkNonNullNonVoidType(widenedType, node);
74090                         }
74091                     }
74092                 }
74093                 return;
74094             }
74095             // For a commonjs `const x = require`, validate the alias and exit
74096             var symbol = getSymbolOfNode(node);
74097             if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)) {
74098                 checkAliasSymbol(node);
74099                 return;
74100             }
74101             var type = convertAutoToAny(getTypeOfSymbol(symbol));
74102             if (node === symbol.valueDeclaration) {
74103                 // Node is the primary declaration of the symbol, just validate the initializer
74104                 // Don't validate for-in initializer as it is already an error
74105                 var initializer = ts.getEffectiveInitializer(node);
74106                 if (initializer) {
74107                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
74108                         ts.isObjectLiteralExpression(initializer) &&
74109                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
74110                         !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
74111                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 238 /* ForInStatement */) {
74112                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
74113                     }
74114                 }
74115                 if (symbol.declarations.length > 1) {
74116                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
74117                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
74118                     }
74119                 }
74120             }
74121             else {
74122                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
74123                 // initializer is consistent with type associated with the node
74124                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
74125                 if (type !== errorType && declarationType !== errorType &&
74126                     !isTypeIdenticalTo(type, declarationType) &&
74127                     !(symbol.flags & 67108864 /* Assignment */)) {
74128                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
74129                 }
74130                 if (node.initializer) {
74131                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
74132                 }
74133                 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
74134                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
74135                 }
74136             }
74137             if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */) {
74138                 // We know we don't have a binding pattern or computed name here
74139                 checkExportsOnMergedDeclarations(node);
74140                 if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) {
74141                     checkVarDeclaredNamesNotShadowed(node);
74142                 }
74143                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
74144                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
74145                 if (languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
74146                     potentialWeakMapCollisions.push(node);
74147                 }
74148             }
74149         }
74150         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
74151             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
74152             var message = nextDeclaration.kind === 163 /* PropertyDeclaration */ || nextDeclaration.kind === 162 /* PropertySignature */
74153                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
74154                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
74155             var declName = ts.declarationNameToString(nextDeclarationName);
74156             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
74157             if (firstDeclaration) {
74158                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
74159             }
74160         }
74161         function areDeclarationFlagsIdentical(left, right) {
74162             if ((left.kind === 160 /* Parameter */ && right.kind === 249 /* VariableDeclaration */) ||
74163                 (left.kind === 249 /* VariableDeclaration */ && right.kind === 160 /* Parameter */)) {
74164                 // Differences in optionality between parameters and variables are allowed.
74165                 return true;
74166             }
74167             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
74168                 return false;
74169             }
74170             var interestingFlags = 8 /* Private */ |
74171                 16 /* Protected */ |
74172                 256 /* Async */ |
74173                 128 /* Abstract */ |
74174                 64 /* Readonly */ |
74175                 32 /* Static */;
74176             return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags);
74177         }
74178         function checkVariableDeclaration(node) {
74179             ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end });
74180             checkGrammarVariableDeclaration(node);
74181             checkVariableLikeDeclaration(node);
74182             ts.tracing.pop();
74183         }
74184         function checkBindingElement(node) {
74185             checkGrammarBindingElement(node);
74186             return checkVariableLikeDeclaration(node);
74187         }
74188         function checkVariableStatement(node) {
74189             // Grammar checking
74190             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
74191                 checkGrammarForDisallowedLetOrConstStatement(node);
74192             ts.forEach(node.declarationList.declarations, checkSourceElement);
74193         }
74194         function checkExpressionStatement(node) {
74195             // Grammar checking
74196             checkGrammarStatementInAmbientContext(node);
74197             checkExpression(node.expression);
74198         }
74199         function checkIfStatement(node) {
74200             // Grammar checking
74201             checkGrammarStatementInAmbientContext(node);
74202             var type = checkTruthinessExpression(node.expression);
74203             checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
74204             checkSourceElement(node.thenStatement);
74205             if (node.thenStatement.kind === 231 /* EmptyStatement */) {
74206                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
74207             }
74208             checkSourceElement(node.elseStatement);
74209         }
74210         function checkTestingKnownTruthyCallableType(condExpr, body, type) {
74211             if (!strictNullChecks) {
74212                 return;
74213             }
74214             var testedNode = ts.isIdentifier(condExpr)
74215                 ? condExpr
74216                 : ts.isPropertyAccessExpression(condExpr)
74217                     ? condExpr.name
74218                     : undefined;
74219             if (!testedNode) {
74220                 return;
74221             }
74222             var possiblyFalsy = getFalsyFlags(type);
74223             if (possiblyFalsy) {
74224                 return;
74225             }
74226             // While it technically should be invalid for any known-truthy value
74227             // to be tested, we de-scope to functions unrefenced in the block as a
74228             // heuristic to identify the most common bugs. There are too many
74229             // false positives for values sourced from type definitions without
74230             // strictNullChecks otherwise.
74231             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
74232             if (callSignatures.length === 0) {
74233                 return;
74234             }
74235             var testedFunctionSymbol = getSymbolAtLocation(testedNode);
74236             if (!testedFunctionSymbol) {
74237                 return;
74238             }
74239             var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
74240                 if (ts.isIdentifier(childNode)) {
74241                     var childSymbol = getSymbolAtLocation(childNode);
74242                     if (childSymbol && childSymbol === testedFunctionSymbol) {
74243                         // If the test was a simple identifier, the above check is sufficient
74244                         if (ts.isIdentifier(condExpr)) {
74245                             return true;
74246                         }
74247                         // Otherwise we need to ensure the symbol is called on the same target
74248                         var testedExpression = testedNode.parent;
74249                         var childExpression = childNode.parent;
74250                         while (testedExpression && childExpression) {
74251                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
74252                                 testedExpression.kind === 107 /* ThisKeyword */ && childExpression.kind === 107 /* ThisKeyword */) {
74253                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
74254                             }
74255                             if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
74256                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
74257                                     return false;
74258                                 }
74259                                 childExpression = childExpression.expression;
74260                                 testedExpression = testedExpression.expression;
74261                             }
74262                             else {
74263                                 return false;
74264                             }
74265                         }
74266                     }
74267                 }
74268                 return ts.forEachChild(childNode, check);
74269             });
74270             if (!functionIsUsedInBody) {
74271                 error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
74272             }
74273         }
74274         function checkDoStatement(node) {
74275             // Grammar checking
74276             checkGrammarStatementInAmbientContext(node);
74277             checkSourceElement(node.statement);
74278             checkTruthinessExpression(node.expression);
74279         }
74280         function checkWhileStatement(node) {
74281             // Grammar checking
74282             checkGrammarStatementInAmbientContext(node);
74283             checkTruthinessExpression(node.expression);
74284             checkSourceElement(node.statement);
74285         }
74286         function checkTruthinessOfType(type, node) {
74287             if (type.flags & 16384 /* Void */) {
74288                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
74289             }
74290             return type;
74291         }
74292         function checkTruthinessExpression(node, checkMode) {
74293             return checkTruthinessOfType(checkExpression(node, checkMode), node);
74294         }
74295         function checkForStatement(node) {
74296             // Grammar checking
74297             if (!checkGrammarStatementInAmbientContext(node)) {
74298                 if (node.initializer && node.initializer.kind === 250 /* VariableDeclarationList */) {
74299                     checkGrammarVariableDeclarationList(node.initializer);
74300                 }
74301             }
74302             if (node.initializer) {
74303                 if (node.initializer.kind === 250 /* VariableDeclarationList */) {
74304                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
74305                 }
74306                 else {
74307                     checkExpression(node.initializer);
74308                 }
74309             }
74310             if (node.condition)
74311                 checkTruthinessExpression(node.condition);
74312             if (node.incrementor)
74313                 checkExpression(node.incrementor);
74314             checkSourceElement(node.statement);
74315             if (node.locals) {
74316                 registerForUnusedIdentifiersCheck(node);
74317             }
74318         }
74319         function checkForOfStatement(node) {
74320             checkGrammarForInOrForOfStatement(node);
74321             if (node.awaitModifier) {
74322                 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
74323                 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
74324                     // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
74325                     checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
74326                 }
74327             }
74328             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
74329                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
74330                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
74331             }
74332             // Check the LHS and RHS
74333             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
74334             // via checkRightHandSideOfForOf.
74335             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
74336             // Then check that the RHS is assignable to it.
74337             if (node.initializer.kind === 250 /* VariableDeclarationList */) {
74338                 checkForInOrForOfVariableDeclaration(node);
74339             }
74340             else {
74341                 var varExpr = node.initializer;
74342                 var iteratedType = checkRightHandSideOfForOf(node);
74343                 // There may be a destructuring assignment on the left side
74344                 if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) {
74345                     // iteratedType may be undefined. In this case, we still want to check the structure of
74346                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
74347                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
74348                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
74349                 }
74350                 else {
74351                     var leftType = checkExpression(varExpr);
74352                     checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access);
74353                     // iteratedType will be undefined if the rightType was missing properties/signatures
74354                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
74355                     // because we accessed properties from anyType, or it may have led to an error inside
74356                     // getElementTypeOfIterable.
74357                     if (iteratedType) {
74358                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
74359                     }
74360                 }
74361             }
74362             checkSourceElement(node.statement);
74363             if (node.locals) {
74364                 registerForUnusedIdentifiersCheck(node);
74365             }
74366         }
74367         function checkForInStatement(node) {
74368             // Grammar checking
74369             checkGrammarForInOrForOfStatement(node);
74370             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
74371             // TypeScript 1.0 spec (April 2014): 5.4
74372             // In a 'for-in' statement of the form
74373             // for (let VarDecl in Expr) Statement
74374             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
74375             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
74376             if (node.initializer.kind === 250 /* VariableDeclarationList */) {
74377                 var variable = node.initializer.declarations[0];
74378                 if (variable && ts.isBindingPattern(variable.name)) {
74379                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
74380                 }
74381                 checkForInOrForOfVariableDeclaration(node);
74382             }
74383             else {
74384                 // In a 'for-in' statement of the form
74385                 // for (Var in Expr) Statement
74386                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
74387                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
74388                 var varExpr = node.initializer;
74389                 var leftType = checkExpression(varExpr);
74390                 if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) {
74391                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
74392                 }
74393                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
74394                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
74395                 }
74396                 else {
74397                     // run check only former check succeeded to avoid cascading errors
74398                     checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access);
74399                 }
74400             }
74401             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
74402             // in this case error about missing name is already reported - do not report extra one
74403             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
74404                 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));
74405             }
74406             checkSourceElement(node.statement);
74407             if (node.locals) {
74408                 registerForUnusedIdentifiersCheck(node);
74409             }
74410         }
74411         function checkForInOrForOfVariableDeclaration(iterationStatement) {
74412             var variableDeclarationList = iterationStatement.initializer;
74413             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
74414             if (variableDeclarationList.declarations.length >= 1) {
74415                 var decl = variableDeclarationList.declarations[0];
74416                 checkVariableDeclaration(decl);
74417             }
74418         }
74419         function checkRightHandSideOfForOf(statement) {
74420             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
74421             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
74422         }
74423         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
74424             if (isTypeAny(inputType)) {
74425                 return inputType;
74426             }
74427             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
74428         }
74429         /**
74430          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
74431          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
74432          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
74433          */
74434         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
74435             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
74436             if (inputType === neverType) {
74437                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
74438                 return undefined;
74439             }
74440             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
74441             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
74442             var possibleOutOfBounds = compilerOptions.noUncheckedIndexedAccess && !!(use & 128 /* PossiblyOutOfBounds */);
74443             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
74444             // or higher, when inside of an async generator or for-await-if, or when
74445             // downlevelIteration is requested.
74446             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
74447                 // We only report errors for an invalid iterable type in ES2015 or higher.
74448                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
74449                 if (checkAssignability) {
74450                     if (iterationTypes) {
74451                         var diagnostic = use & 8 /* ForOfFlag */ ? ts.Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 :
74452                             use & 32 /* SpreadFlag */ ? ts.Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 :
74453                                 use & 64 /* DestructuringFlag */ ? ts.Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 :
74454                                     use & 16 /* YieldStarFlag */ ? ts.Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 :
74455                                         undefined;
74456                         if (diagnostic) {
74457                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
74458                         }
74459                     }
74460                 }
74461                 if (iterationTypes || uplevelIteration) {
74462                     return possibleOutOfBounds ? includeUndefinedInIndexSignature(iterationTypes && iterationTypes.yieldType) : (iterationTypes && iterationTypes.yieldType);
74463                 }
74464             }
74465             var arrayType = inputType;
74466             var reportedError = false;
74467             var hasStringConstituent = false;
74468             // If strings are permitted, remove any string-like constituents from the array type.
74469             // This allows us to find other non-string element types from an array unioned with
74470             // a string.
74471             if (use & 4 /* AllowsStringInputFlag */) {
74472                 if (arrayType.flags & 1048576 /* Union */) {
74473                     // After we remove all types that are StringLike, we will know if there was a string constituent
74474                     // based on whether the result of filter is a new array.
74475                     var arrayTypes = inputType.types;
74476                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 402653316 /* StringLike */); });
74477                     if (filteredTypes !== arrayTypes) {
74478                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
74479                     }
74480                 }
74481                 else if (arrayType.flags & 402653316 /* StringLike */) {
74482                     arrayType = neverType;
74483                 }
74484                 hasStringConstituent = arrayType !== inputType;
74485                 if (hasStringConstituent) {
74486                     if (languageVersion < 1 /* ES5 */) {
74487                         if (errorNode) {
74488                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
74489                             reportedError = true;
74490                         }
74491                     }
74492                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
74493                     // arrayOrStringType was a string.
74494                     if (arrayType.flags & 131072 /* Never */) {
74495                         return possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType;
74496                     }
74497                 }
74498             }
74499             if (!isArrayLikeType(arrayType)) {
74500                 if (errorNode && !reportedError) {
74501                     // Which error we report depends on whether we allow strings or if there was a
74502                     // string constituent. For example, if the input type is number | string, we
74503                     // want to say that number is not an array type. But if the input was just
74504                     // number and string input is allowed, we want to say that number is not an
74505                     // array type or a string type.
74506                     var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
74507                     var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
74508                         ? downlevelIteration
74509                             ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
74510                             : yieldType
74511                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
74512                                 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
74513                         : downlevelIteration
74514                             ? [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, true]
74515                             : yieldType
74516                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
74517                                 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
74518                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
74519                 }
74520                 return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined;
74521             }
74522             var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
74523             if (hasStringConstituent && arrayElementType) {
74524                 // This is just an optimization for the case where arrayOrStringType is string | string[]
74525                 if (arrayElementType.flags & 402653316 /* StringLike */ && !compilerOptions.noUncheckedIndexedAccess) {
74526                     return stringType;
74527                 }
74528                 return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */);
74529             }
74530             return (use & 128 /* PossiblyOutOfBounds */) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType;
74531         }
74532         /**
74533          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
74534          */
74535         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
74536             if (isTypeAny(inputType)) {
74537                 return undefined;
74538             }
74539             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
74540             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
74541         }
74542         function createIterationTypes(yieldType, returnType, nextType) {
74543             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
74544             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
74545             // as it is combined via `getIntersectionType` when merging iteration types.
74546             if (yieldType === void 0) { yieldType = neverType; }
74547             if (returnType === void 0) { returnType = neverType; }
74548             if (nextType === void 0) { nextType = unknownType; }
74549             // Use the cache only for intrinsic types to keep it small as they are likely to be
74550             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
74551             // are also cached on the type they are requested for, so we shouldn't need to maintain
74552             // the cache for less-frequently used types.
74553             if (yieldType.flags & 67359327 /* Intrinsic */ &&
74554                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
74555                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
74556                 var id = getTypeListId([yieldType, returnType, nextType]);
74557                 var iterationTypes = iterationTypesCache.get(id);
74558                 if (!iterationTypes) {
74559                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
74560                     iterationTypesCache.set(id, iterationTypes);
74561                 }
74562                 return iterationTypes;
74563             }
74564             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
74565         }
74566         /**
74567          * Combines multiple `IterationTypes` records.
74568          *
74569          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
74570          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
74571          * for the combined iteration types.
74572          */
74573         function combineIterationTypes(array) {
74574             var yieldTypes;
74575             var returnTypes;
74576             var nextTypes;
74577             for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
74578                 var iterationTypes = array_10[_i];
74579                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
74580                     continue;
74581                 }
74582                 if (iterationTypes === anyIterationTypes) {
74583                     return anyIterationTypes;
74584                 }
74585                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
74586                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
74587                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
74588             }
74589             if (yieldTypes || returnTypes || nextTypes) {
74590                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
74591             }
74592             return noIterationTypes;
74593         }
74594         function getCachedIterationTypes(type, cacheKey) {
74595             return type[cacheKey];
74596         }
74597         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
74598             return type[cacheKey] = cachedTypes;
74599         }
74600         /**
74601          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
74602          *
74603          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
74604          *
74605          * Another thing to note is that at any step of this process, we could run into a dead end,
74606          * meaning either the property is missing, or we run into the anyType. If either of these things
74607          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
74608          * is missing, and the previous step did not result in `any`, then we also give an error if the
74609          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
74610          * type.
74611          *
74612          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
74613          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
74614          * method.
74615          *
74616          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
74617          *
74618          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
74619          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
74620          */
74621         function getIterationTypesOfIterable(type, use, errorNode) {
74622             if (isTypeAny(type)) {
74623                 return anyIterationTypes;
74624             }
74625             if (!(type.flags & 1048576 /* Union */)) {
74626                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
74627                 if (iterationTypes_1 === noIterationTypes) {
74628                     if (errorNode) {
74629                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
74630                     }
74631                     return undefined;
74632                 }
74633                 return iterationTypes_1;
74634             }
74635             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
74636             var cachedTypes = getCachedIterationTypes(type, cacheKey);
74637             if (cachedTypes)
74638                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
74639             var allIterationTypes;
74640             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
74641                 var constituent = _a[_i];
74642                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
74643                 if (iterationTypes_2 === noIterationTypes) {
74644                     if (errorNode) {
74645                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
74646                     }
74647                     setCachedIterationTypes(type, cacheKey, noIterationTypes);
74648                     return undefined;
74649                 }
74650                 else {
74651                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
74652                 }
74653             }
74654             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
74655             setCachedIterationTypes(type, cacheKey, iterationTypes);
74656             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
74657         }
74658         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
74659             if (iterationTypes === noIterationTypes)
74660                 return noIterationTypes;
74661             if (iterationTypes === anyIterationTypes)
74662                 return anyIterationTypes;
74663             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
74664             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
74665         }
74666         /**
74667          * Gets the *yield*, *return*, and *next* types from a non-union type.
74668          *
74669          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
74670          * returned to indicate to the caller that it should report an error. Otherwise, an
74671          * `IterationTypes` record is returned.
74672          *
74673          * NOTE: You probably don't want to call this directly and should be calling
74674          * `getIterationTypesOfIterable` instead.
74675          */
74676         function getIterationTypesOfIterableWorker(type, use, errorNode) {
74677             if (isTypeAny(type)) {
74678                 return anyIterationTypes;
74679             }
74680             if (use & 2 /* AllowsAsyncIterablesFlag */) {
74681                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
74682                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
74683                 if (iterationTypes) {
74684                     return iterationTypes;
74685                 }
74686             }
74687             if (use & 1 /* AllowsSyncIterablesFlag */) {
74688                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
74689                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
74690                 if (iterationTypes) {
74691                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
74692                         // for a sync iterable in an async context, only use the cached types if they are valid.
74693                         if (iterationTypes !== noIterationTypes) {
74694                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
74695                         }
74696                     }
74697                     else {
74698                         return iterationTypes;
74699                     }
74700                 }
74701             }
74702             if (use & 2 /* AllowsAsyncIterablesFlag */) {
74703                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
74704                 if (iterationTypes !== noIterationTypes) {
74705                     return iterationTypes;
74706                 }
74707             }
74708             if (use & 1 /* AllowsSyncIterablesFlag */) {
74709                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
74710                 if (iterationTypes !== noIterationTypes) {
74711                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
74712                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
74713                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
74714                             : noIterationTypes);
74715                     }
74716                     else {
74717                         return iterationTypes;
74718                     }
74719                 }
74720             }
74721             return noIterationTypes;
74722         }
74723         /**
74724          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
74725          * `AsyncIterable`-like type from the cache.
74726          *
74727          * NOTE: You probably don't want to call this directly and should be calling
74728          * `getIterationTypesOfIterable` instead.
74729          */
74730         function getIterationTypesOfIterableCached(type, resolver) {
74731             return getCachedIterationTypes(type, resolver.iterableCacheKey);
74732         }
74733         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
74734             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
74735                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
74736             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
74737         }
74738         /**
74739          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
74740          * type from from common heuristics.
74741          *
74742          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
74743          * returned. If we found iteration types, an `IterationTypes` record is returned.
74744          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
74745          * exhaustive analysis.
74746          *
74747          * NOTE: You probably don't want to call this directly and should be calling
74748          * `getIterationTypesOfIterable` instead.
74749          */
74750         function getIterationTypesOfIterableFast(type, resolver) {
74751             // As an optimization, if the type is an instantiation of one of the following global types, then
74752             // just grab its related type argument:
74753             // - `Iterable<T>` or `AsyncIterable<T>`
74754             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
74755             var globalType;
74756             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
74757                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
74758                 var yieldType = getTypeArguments(type)[0];
74759                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
74760                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
74761                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
74762                 // different definitions.
74763                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
74764                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
74765             }
74766             // As an optimization, if the type is an instantiation of the following global type, then
74767             // just grab its related type arguments:
74768             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
74769             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
74770                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
74771                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
74772             }
74773         }
74774         /**
74775          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
74776          * type from its members.
74777          *
74778          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
74779          * record is returned. Otherwise, `noIterationTypes` is returned.
74780          *
74781          * NOTE: You probably don't want to call this directly and should be calling
74782          * `getIterationTypesOfIterable` instead.
74783          */
74784         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
74785             var _a;
74786             var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
74787             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
74788             if (isTypeAny(methodType)) {
74789                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
74790             }
74791             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
74792             if (!ts.some(signatures)) {
74793                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
74794             }
74795             var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature));
74796             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
74797             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
74798         }
74799         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
74800             var message = allowAsyncIterables
74801                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
74802                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
74803             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
74804         }
74805         /**
74806          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
74807          *
74808          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
74809          * record is returned. Otherwise, `undefined` is returned.
74810          */
74811         function getIterationTypesOfIterator(type, resolver, errorNode) {
74812             if (isTypeAny(type)) {
74813                 return anyIterationTypes;
74814             }
74815             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
74816                 getIterationTypesOfIteratorFast(type, resolver) ||
74817                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
74818             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
74819         }
74820         /**
74821          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
74822          * cache.
74823          *
74824          * NOTE: You probably don't want to call this directly and should be calling
74825          * `getIterationTypesOfIterator` instead.
74826          */
74827         function getIterationTypesOfIteratorCached(type, resolver) {
74828             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
74829         }
74830         /**
74831          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
74832          * cache or from common heuristics.
74833          *
74834          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
74835          * returned. If we found iteration types, an `IterationTypes` record is returned.
74836          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
74837          * exhaustive analysis.
74838          *
74839          * NOTE: You probably don't want to call this directly and should be calling
74840          * `getIterationTypesOfIterator` instead.
74841          */
74842         function getIterationTypesOfIteratorFast(type, resolver) {
74843             // As an optimization, if the type is an instantiation of one of the following global types,
74844             // then just grab its related type argument:
74845             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
74846             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
74847             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
74848             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
74849             if (isReferenceToType(type, globalType)) {
74850                 var yieldType = getTypeArguments(type)[0];
74851                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
74852                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
74853                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
74854                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
74855                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
74856                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
74857                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
74858             }
74859             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
74860                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
74861                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
74862                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
74863             }
74864         }
74865         function isIteratorResult(type, kind) {
74866             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
74867             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
74868             // > If the end was not reached `done` is `false` and a value is available.
74869             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
74870             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
74871             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
74872         }
74873         function isYieldIteratorResult(type) {
74874             return isIteratorResult(type, 0 /* Yield */);
74875         }
74876         function isReturnIteratorResult(type) {
74877             return isIteratorResult(type, 1 /* Return */);
74878         }
74879         /**
74880          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
74881          *
74882          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
74883          * returned to indicate to the caller that it should handle the error. Otherwise, an
74884          * `IterationTypes` record is returned.
74885          */
74886         function getIterationTypesOfIteratorResult(type) {
74887             if (isTypeAny(type)) {
74888                 return anyIterationTypes;
74889             }
74890             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
74891             if (cachedTypes) {
74892                 return cachedTypes;
74893             }
74894             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
74895             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
74896             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
74897                 var yieldType_1 = getTypeArguments(type)[0];
74898                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
74899             }
74900             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
74901                 var returnType_1 = getTypeArguments(type)[0];
74902                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
74903             }
74904             // Choose any constituents that can produce the requested iteration type.
74905             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
74906             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
74907             var returnIteratorResult = filterType(type, isReturnIteratorResult);
74908             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
74909             if (!yieldType && !returnType) {
74910                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
74911             }
74912             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
74913             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
74914             // > `value` property may be absent from the conforming object if it does not inherit an explicit
74915             // > `value` property.
74916             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
74917         }
74918         /**
74919          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
74920          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
74921          *
74922          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
74923          * record is returned. Otherwise, we return `undefined`.
74924          */
74925         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
74926             var _a, _b, _c, _d;
74927             var method = getPropertyOfType(type, methodName);
74928             // Ignore 'return' or 'throw' if they are missing.
74929             if (!method && methodName !== "next") {
74930                 return undefined;
74931             }
74932             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
74933                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
74934                 : undefined;
74935             if (isTypeAny(methodType)) {
74936                 // `return()` and `throw()` don't provide a *next* type.
74937                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
74938             }
74939             // Both async and non-async iterators *must* have a `next` method.
74940             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
74941             if (methodSignatures.length === 0) {
74942                 if (errorNode) {
74943                     var diagnostic = methodName === "next"
74944                         ? resolver.mustHaveANextMethodDiagnostic
74945                         : resolver.mustBeAMethodDiagnostic;
74946                     error(errorNode, diagnostic, methodName);
74947                 }
74948                 return methodName === "next" ? anyIterationTypes : undefined;
74949             }
74950             // If the method signature comes exclusively from the global iterator or generator type,
74951             // create iteration types from its type arguments like `getIterationTypesOfIteratorFast`
74952             // does (so as to remove `undefined` from the next and return types). We arrive here when
74953             // a contextual type for a generator was not a direct reference to one of those global types,
74954             // but looking up `methodType` referred to one of them (and nothing else). E.g., in
74955             // `interface SpecialIterator extends Iterator<number> {}`, `SpecialIterator` is not a
74956             // reference to `Iterator`, but its `next` member derives exclusively from `Iterator`.
74957             if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) {
74958                 var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
74959                 var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false);
74960                 var isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) === null || _a === void 0 ? void 0 : _a.members) === null || _b === void 0 ? void 0 : _b.get(methodName)) === methodType.symbol;
74961                 var isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) === null || _c === void 0 ? void 0 : _c.members) === null || _d === void 0 ? void 0 : _d.get(methodName)) === methodType.symbol;
74962                 if (isGeneratorMethod || isIteratorMethod) {
74963                     var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType;
74964                     var mapper = methodType.mapper;
74965                     return createIterationTypes(getMappedType(globalType.typeParameters[0], mapper), getMappedType(globalType.typeParameters[1], mapper), methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : undefined);
74966                 }
74967             }
74968             // Extract the first parameter and return type of each signature.
74969             var methodParameterTypes;
74970             var methodReturnTypes;
74971             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
74972                 var signature = methodSignatures_1[_i];
74973                 if (methodName !== "throw" && ts.some(signature.parameters)) {
74974                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
74975                 }
74976                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
74977             }
74978             // Resolve the *next* or *return* type from the first parameter of a `next()` or
74979             // `return()` method, respectively.
74980             var returnTypes;
74981             var nextType;
74982             if (methodName !== "throw") {
74983                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
74984                 if (methodName === "next") {
74985                     // The value of `next(value)` is *not* awaited by async generators
74986                     nextType = methodParameterType;
74987                 }
74988                 else if (methodName === "return") {
74989                     // The value of `return(value)` *is* awaited by async generators
74990                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
74991                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
74992                 }
74993             }
74994             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
74995             var yieldType;
74996             var methodReturnType = methodReturnTypes ? getIntersectionType(methodReturnTypes) : neverType;
74997             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
74998             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
74999             if (iterationTypes === noIterationTypes) {
75000                 if (errorNode) {
75001                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
75002                 }
75003                 yieldType = anyType;
75004                 returnTypes = ts.append(returnTypes, anyType);
75005             }
75006             else {
75007                 yieldType = iterationTypes.yieldType;
75008                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
75009             }
75010             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
75011         }
75012         /**
75013          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
75014          * type from its members.
75015          *
75016          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
75017          * record is returned. Otherwise, `noIterationTypes` is returned.
75018          *
75019          * NOTE: You probably don't want to call this directly and should be calling
75020          * `getIterationTypesOfIterator` instead.
75021          */
75022         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
75023             var iterationTypes = combineIterationTypes([
75024                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
75025                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
75026                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
75027             ]);
75028             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
75029         }
75030         /**
75031          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
75032          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
75033          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
75034          */
75035         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
75036             if (isTypeAny(returnType)) {
75037                 return undefined;
75038             }
75039             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
75040             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
75041         }
75042         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
75043             if (isTypeAny(type)) {
75044                 return anyIterationTypes;
75045             }
75046             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
75047             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
75048             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
75049                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
75050         }
75051         function checkBreakOrContinueStatement(node) {
75052             // Grammar checking
75053             if (!checkGrammarStatementInAmbientContext(node))
75054                 checkGrammarBreakOrContinueStatement(node);
75055             // TODO: Check that target label is valid
75056         }
75057         function unwrapReturnType(returnType, functionFlags) {
75058             var _a, _b;
75059             var isGenerator = !!(functionFlags & 1 /* Generator */);
75060             var isAsync = !!(functionFlags & 2 /* Async */);
75061             return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
75062                 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
75063                     returnType;
75064         }
75065         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
75066             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
75067             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
75068         }
75069         function checkReturnStatement(node) {
75070             var _a;
75071             // Grammar checking
75072             if (checkGrammarStatementInAmbientContext(node)) {
75073                 return;
75074             }
75075             var func = ts.getContainingFunction(node);
75076             if (!func) {
75077                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
75078                 return;
75079             }
75080             var signature = getSignatureFromDeclaration(func);
75081             var returnType = getReturnTypeOfSignature(signature);
75082             var functionFlags = ts.getFunctionFlags(func);
75083             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
75084                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
75085                 if (func.kind === 168 /* SetAccessor */) {
75086                     if (node.expression) {
75087                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
75088                     }
75089                 }
75090                 else if (func.kind === 166 /* Constructor */) {
75091                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
75092                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
75093                     }
75094                 }
75095                 else if (getReturnTypeFromAnnotation(func)) {
75096                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
75097                     var unwrappedExprType = functionFlags & 2 /* Async */
75098                         ? 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)
75099                         : exprType;
75100                     if (unwrappedReturnType) {
75101                         // If the function has a return type, but promisedType is
75102                         // undefined, an error will be reported in checkAsyncFunctionReturnType
75103                         // so we don't need to report one here.
75104                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
75105                     }
75106                 }
75107             }
75108             else if (func.kind !== 166 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
75109                 // The function has a return type, but the return statement doesn't have an expression.
75110                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
75111             }
75112         }
75113         function checkWithStatement(node) {
75114             // Grammar checking for withStatement
75115             if (!checkGrammarStatementInAmbientContext(node)) {
75116                 if (node.flags & 32768 /* AwaitContext */) {
75117                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
75118                 }
75119             }
75120             checkExpression(node.expression);
75121             var sourceFile = ts.getSourceFileOfNode(node);
75122             if (!hasParseDiagnostics(sourceFile)) {
75123                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
75124                 var end = node.statement.pos;
75125                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
75126             }
75127         }
75128         function checkSwitchStatement(node) {
75129             // Grammar checking
75130             checkGrammarStatementInAmbientContext(node);
75131             var firstDefaultClause;
75132             var hasDuplicateDefaultClause = false;
75133             var expressionType = checkExpression(node.expression);
75134             var expressionIsLiteral = isLiteralType(expressionType);
75135             ts.forEach(node.caseBlock.clauses, function (clause) {
75136                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
75137                 if (clause.kind === 285 /* DefaultClause */ && !hasDuplicateDefaultClause) {
75138                     if (firstDefaultClause === undefined) {
75139                         firstDefaultClause = clause;
75140                     }
75141                     else {
75142                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
75143                         hasDuplicateDefaultClause = true;
75144                     }
75145                 }
75146                 if (produceDiagnostics && clause.kind === 284 /* CaseClause */) {
75147                     // TypeScript 1.0 spec (April 2014): 5.9
75148                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
75149                     // to or from the type of the 'switch' expression.
75150                     var caseType = checkExpression(clause.expression);
75151                     var caseIsLiteral = isLiteralType(caseType);
75152                     var comparedExpressionType = expressionType;
75153                     if (!caseIsLiteral || !expressionIsLiteral) {
75154                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
75155                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
75156                     }
75157                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
75158                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
75159                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
75160                     }
75161                 }
75162                 ts.forEach(clause.statements, checkSourceElement);
75163                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
75164                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
75165                 }
75166             });
75167             if (node.caseBlock.locals) {
75168                 registerForUnusedIdentifiersCheck(node.caseBlock);
75169             }
75170         }
75171         function checkLabeledStatement(node) {
75172             // Grammar checking
75173             if (!checkGrammarStatementInAmbientContext(node)) {
75174                 ts.findAncestor(node.parent, function (current) {
75175                     if (ts.isFunctionLike(current)) {
75176                         return "quit";
75177                     }
75178                     if (current.kind === 245 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
75179                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
75180                         return true;
75181                     }
75182                     return false;
75183                 });
75184             }
75185             // ensure that label is unique
75186             checkSourceElement(node.statement);
75187         }
75188         function checkThrowStatement(node) {
75189             // Grammar checking
75190             if (!checkGrammarStatementInAmbientContext(node)) {
75191                 if (ts.isIdentifier(node.expression) && !node.expression.escapedText) {
75192                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
75193                 }
75194             }
75195             if (node.expression) {
75196                 checkExpression(node.expression);
75197             }
75198         }
75199         function checkTryStatement(node) {
75200             // Grammar checking
75201             checkGrammarStatementInAmbientContext(node);
75202             checkBlock(node.tryBlock);
75203             var catchClause = node.catchClause;
75204             if (catchClause) {
75205                 // Grammar checking
75206                 if (catchClause.variableDeclaration) {
75207                     var declaration = catchClause.variableDeclaration;
75208                     if (declaration.type) {
75209                         var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false);
75210                         if (type && !(type.flags & 3 /* AnyOrUnknown */)) {
75211                             grammarErrorOnFirstToken(declaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified);
75212                         }
75213                     }
75214                     else if (declaration.initializer) {
75215                         grammarErrorOnFirstToken(declaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
75216                     }
75217                     else {
75218                         var blockLocals_1 = catchClause.block.locals;
75219                         if (blockLocals_1) {
75220                             ts.forEachKey(catchClause.locals, function (caughtName) {
75221                                 var blockLocal = blockLocals_1.get(caughtName);
75222                                 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
75223                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
75224                                 }
75225                             });
75226                         }
75227                     }
75228                 }
75229                 checkBlock(catchClause.block);
75230             }
75231             if (node.finallyBlock) {
75232                 checkBlock(node.finallyBlock);
75233             }
75234         }
75235         function checkIndexConstraints(type) {
75236             var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
75237             var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
75238             var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
75239             var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
75240             if (stringIndexType || numberIndexType) {
75241                 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
75242                     var propType = getTypeOfSymbol(prop);
75243                     checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
75244                     checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
75245                 });
75246                 var classDeclaration = type.symbol.valueDeclaration;
75247                 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
75248                     for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
75249                         var member = _a[_i];
75250                         // Only process instance properties with computed names here.
75251                         // Static properties cannot be in conflict with indexers,
75252                         // and properties with literal names were already checked.
75253                         if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
75254                             var symbol = getSymbolOfNode(member);
75255                             var propType = getTypeOfSymbol(symbol);
75256                             checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
75257                             checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
75258                         }
75259                     }
75260                 }
75261             }
75262             var errorNode;
75263             if (stringIndexType && numberIndexType) {
75264                 errorNode = declaredNumberIndexer || declaredStringIndexer;
75265                 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
75266                 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
75267                     var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
75268                     errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
75269                 }
75270             }
75271             if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
75272                 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
75273             }
75274             function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
75275                 // ESSymbol properties apply to neither string nor numeric indexers.
75276                 if (!indexType || ts.isKnownSymbol(prop)) {
75277                     return;
75278                 }
75279                 var propDeclaration = prop.valueDeclaration;
75280                 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
75281                 if (name && ts.isPrivateIdentifier(name)) {
75282                     return;
75283                 }
75284                 // index is numeric and property name is not valid numeric literal
75285                 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
75286                     return;
75287                 }
75288                 // perform property check if property or indexer is declared in 'type'
75289                 // this allows us to rule out cases when both property and indexer are inherited from the base class
75290                 var errorNode;
75291                 if (propDeclaration && name &&
75292                     (propDeclaration.kind === 216 /* BinaryExpression */ ||
75293                         name.kind === 158 /* ComputedPropertyName */ ||
75294                         prop.parent === containingType.symbol)) {
75295                     errorNode = propDeclaration;
75296                 }
75297                 else if (indexDeclaration) {
75298                     errorNode = indexDeclaration;
75299                 }
75300                 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
75301                     // for interfaces property and indexer might be inherited from different bases
75302                     // check if any base class already has both property and indexer.
75303                     // check should be performed only if 'type' is the first type that brings property\indexer together
75304                     var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
75305                     errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
75306                 }
75307                 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
75308                     var errorMessage = indexKind === 0 /* String */
75309                         ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
75310                         : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
75311                     error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
75312                 }
75313             }
75314         }
75315         function checkTypeNameIsReserved(name, message) {
75316             // TS 1.0 spec (April 2014): 3.6.1
75317             // The predefined type keywords are reserved and cannot be used as names of user defined types.
75318             switch (name.escapedText) {
75319                 case "any":
75320                 case "unknown":
75321                 case "number":
75322                 case "bigint":
75323                 case "boolean":
75324                 case "string":
75325                 case "symbol":
75326                 case "void":
75327                 case "object":
75328                     error(name, message, name.escapedText);
75329             }
75330         }
75331         /**
75332          * The name cannot be used as 'Object' of user defined types with special target.
75333          */
75334         function checkClassNameCollisionWithObject(name) {
75335             if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
75336                 && moduleKind < ts.ModuleKind.ES2015) {
75337                 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
75338             }
75339         }
75340         /**
75341          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
75342          */
75343         function checkTypeParameters(typeParameterDeclarations) {
75344             if (typeParameterDeclarations) {
75345                 var seenDefault = false;
75346                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
75347                     var node = typeParameterDeclarations[i];
75348                     checkTypeParameter(node);
75349                     if (produceDiagnostics) {
75350                         if (node.default) {
75351                             seenDefault = true;
75352                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
75353                         }
75354                         else if (seenDefault) {
75355                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
75356                         }
75357                         for (var j = 0; j < i; j++) {
75358                             if (typeParameterDeclarations[j].symbol === node.symbol) {
75359                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
75360                             }
75361                         }
75362                     }
75363                 }
75364             }
75365         }
75366         /** Check that type parameter defaults only reference previously declared type parameters */
75367         function checkTypeParametersNotReferenced(root, typeParameters, index) {
75368             visit(root);
75369             function visit(node) {
75370                 if (node.kind === 173 /* TypeReference */) {
75371                     var type = getTypeFromTypeReference(node);
75372                     if (type.flags & 262144 /* TypeParameter */) {
75373                         for (var i = index; i < typeParameters.length; i++) {
75374                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
75375                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
75376                             }
75377                         }
75378                     }
75379                 }
75380                 ts.forEachChild(node, visit);
75381             }
75382         }
75383         /** Check that type parameter lists are identical across multiple declarations */
75384         function checkTypeParameterListsIdentical(symbol) {
75385             if (symbol.declarations.length === 1) {
75386                 return;
75387             }
75388             var links = getSymbolLinks(symbol);
75389             if (!links.typeParametersChecked) {
75390                 links.typeParametersChecked = true;
75391                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
75392                 if (declarations.length <= 1) {
75393                     return;
75394                 }
75395                 var type = getDeclaredTypeOfSymbol(symbol);
75396                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
75397                     // Report an error on every conflicting declaration.
75398                     var name = symbolToString(symbol);
75399                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
75400                         var declaration = declarations_6[_i];
75401                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
75402                     }
75403                 }
75404             }
75405         }
75406         function areTypeParametersIdentical(declarations, targetParameters) {
75407             var maxTypeArgumentCount = ts.length(targetParameters);
75408             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
75409             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
75410                 var declaration = declarations_7[_i];
75411                 // If this declaration has too few or too many type parameters, we report an error
75412                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
75413                 var numTypeParameters = sourceParameters.length;
75414                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
75415                     return false;
75416                 }
75417                 for (var i = 0; i < numTypeParameters; i++) {
75418                     var source = sourceParameters[i];
75419                     var target = targetParameters[i];
75420                     // If the type parameter node does not have the same as the resolved type
75421                     // parameter at this position, we report an error.
75422                     if (source.name.escapedText !== target.symbol.escapedName) {
75423                         return false;
75424                     }
75425                     // If the type parameter node does not have an identical constraint as the resolved
75426                     // type parameter at this position, we report an error.
75427                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
75428                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
75429                     var targetConstraint = getConstraintOfTypeParameter(target);
75430                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
75431                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
75432                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
75433                         return false;
75434                     }
75435                     // If the type parameter node has a default and it is not identical to the default
75436                     // for the type parameter at this position, we report an error.
75437                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
75438                     var targetDefault = getDefaultFromTypeParameter(target);
75439                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
75440                         return false;
75441                     }
75442                 }
75443             }
75444             return true;
75445         }
75446         function checkClassExpression(node) {
75447             checkClassLikeDeclaration(node);
75448             checkNodeDeferred(node);
75449             return getTypeOfSymbol(getSymbolOfNode(node));
75450         }
75451         function checkClassExpressionDeferred(node) {
75452             ts.forEach(node.members, checkSourceElement);
75453             registerForUnusedIdentifiersCheck(node);
75454         }
75455         function checkClassDeclaration(node) {
75456             if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) {
75457                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
75458             }
75459             checkClassLikeDeclaration(node);
75460             ts.forEach(node.members, checkSourceElement);
75461             registerForUnusedIdentifiersCheck(node);
75462         }
75463         function checkClassLikeDeclaration(node) {
75464             checkGrammarClassLikeDeclaration(node);
75465             checkDecorators(node);
75466             if (node.name) {
75467                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
75468                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
75469                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
75470                 if (!(node.flags & 8388608 /* Ambient */)) {
75471                     checkClassNameCollisionWithObject(node.name);
75472                 }
75473             }
75474             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
75475             checkExportsOnMergedDeclarations(node);
75476             var symbol = getSymbolOfNode(node);
75477             var type = getDeclaredTypeOfSymbol(symbol);
75478             var typeWithThis = getTypeWithThisArgument(type);
75479             var staticType = getTypeOfSymbol(symbol);
75480             checkTypeParameterListsIdentical(symbol);
75481             checkFunctionOrConstructorSymbol(symbol);
75482             checkClassForDuplicateDeclarations(node);
75483             // Only check for reserved static identifiers on non-ambient context.
75484             if (!(node.flags & 8388608 /* Ambient */)) {
75485                 checkClassForStaticPropertyNameConflicts(node);
75486             }
75487             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
75488             if (baseTypeNode) {
75489                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
75490                 if (languageVersion < 2 /* ES2015 */) {
75491                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
75492                 }
75493                 // check both @extends and extends if both are specified.
75494                 var extendsNode = ts.getClassExtendsHeritageElement(node);
75495                 if (extendsNode && extendsNode !== baseTypeNode) {
75496                     checkExpression(extendsNode.expression);
75497                 }
75498                 var baseTypes = getBaseTypes(type);
75499                 if (baseTypes.length && produceDiagnostics) {
75500                     var baseType_1 = baseTypes[0];
75501                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
75502                     var staticBaseType = getApparentType(baseConstructorType);
75503                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
75504                     checkSourceElement(baseTypeNode.expression);
75505                     if (ts.some(baseTypeNode.typeArguments)) {
75506                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
75507                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
75508                             var constructor = _a[_i];
75509                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
75510                                 break;
75511                             }
75512                         }
75513                     }
75514                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
75515                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
75516                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
75517                     }
75518                     else {
75519                         // Report static side error only when instance type is assignable
75520                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
75521                     }
75522                     if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
75523                         error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
75524                     }
75525                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
75526                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
75527                         // that all instantiated base constructor signatures return the same type.
75528                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
75529                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
75530                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
75531                         }
75532                     }
75533                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
75534                 }
75535             }
75536             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
75537             if (implementedTypeNodes) {
75538                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
75539                     var typeRefNode = implementedTypeNodes_1[_b];
75540                     if (!ts.isEntityNameExpression(typeRefNode.expression)) {
75541                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
75542                     }
75543                     checkTypeReferenceNode(typeRefNode);
75544                     if (produceDiagnostics) {
75545                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
75546                         if (t !== errorType) {
75547                             if (isValidBaseType(t)) {
75548                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
75549                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
75550                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
75551                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
75552                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
75553                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
75554                                 }
75555                             }
75556                             else {
75557                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
75558                             }
75559                         }
75560                     }
75561                 }
75562             }
75563             if (produceDiagnostics) {
75564                 checkIndexConstraints(type);
75565                 checkTypeForDuplicateIndexSignatures(node);
75566                 checkPropertyInitialization(node);
75567             }
75568         }
75569         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
75570             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
75571             var issuedMemberError = false;
75572             var _loop_23 = function (member) {
75573                 if (ts.hasStaticModifier(member)) {
75574                     return "continue";
75575                 }
75576                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
75577                 if (declaredProp) {
75578                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
75579                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
75580                     if (prop && baseProp) {
75581                         var rootChain = function () { return ts.chainDiagnosticMessages(
75582                         /*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)); };
75583                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
75584                             issuedMemberError = true;
75585                         }
75586                     }
75587                 }
75588             };
75589             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
75590                 var member = _a[_i];
75591                 _loop_23(member);
75592             }
75593             if (!issuedMemberError) {
75594                 // check again with diagnostics to generate a less-specific error
75595                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
75596             }
75597         }
75598         function checkBaseTypeAccessibility(type, node) {
75599             var signatures = getSignaturesOfType(type, 1 /* Construct */);
75600             if (signatures.length) {
75601                 var declaration = signatures[0].declaration;
75602                 if (declaration && ts.hasEffectiveModifier(declaration, 8 /* Private */)) {
75603                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
75604                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
75605                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
75606                     }
75607                 }
75608             }
75609         }
75610         function getTargetSymbol(s) {
75611             // if symbol is instantiated its flags are not copied from the 'target'
75612             // so we'll need to get back original 'target' symbol to work with correct set of flags
75613             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
75614         }
75615         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
75616             return ts.filter(symbol.declarations, function (d) {
75617                 return d.kind === 252 /* ClassDeclaration */ || d.kind === 253 /* InterfaceDeclaration */;
75618             });
75619         }
75620         function checkKindsOfPropertyMemberOverrides(type, baseType) {
75621             // TypeScript 1.0 spec (April 2014): 8.2.3
75622             // A derived class inherits all members from its base class it doesn't override.
75623             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
75624             // Both public and private property members are inherited, but only public property members can be overridden.
75625             // A property member in a derived class is said to override a property member in a base class
75626             // when the derived class property member has the same name and kind(instance or static)
75627             // as the base class property member.
75628             // The type of an overriding property member must be assignable(section 3.8.4)
75629             // to the type of the overridden property member, or otherwise a compile - time error occurs.
75630             // Base class instance member functions can be overridden by derived class instance member functions,
75631             // but not by other kinds of members.
75632             // Base class instance member variables and accessors can be overridden by
75633             // derived class instance member variables and accessors, but not by other kinds of members.
75634             // NOTE: assignability is checked in checkClassDeclaration
75635             var baseProperties = getPropertiesOfType(baseType);
75636             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
75637                 var baseProperty = baseProperties_1[_i];
75638                 var base = getTargetSymbol(baseProperty);
75639                 if (base.flags & 4194304 /* Prototype */) {
75640                     continue;
75641                 }
75642                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
75643                 if (!baseSymbol) {
75644                     continue;
75645                 }
75646                 var derived = getTargetSymbol(baseSymbol);
75647                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
75648                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
75649                 // In order to resolve whether the inherited method was overridden in the base class or not,
75650                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
75651                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
75652                 if (derived === base) {
75653                     // derived class inherits base without override/redeclaration
75654                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
75655                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
75656                     // If there is no declaration for the derived class (as in the case of class expressions),
75657                     // then the class cannot be declared abstract.
75658                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasSyntacticModifier(derivedClassDecl, 128 /* Abstract */))) {
75659                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
75660                         // (The class may have more than one base type via declaration merging with an interface with the
75661                         // same name.)
75662                         for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
75663                             var otherBaseType = _b[_a];
75664                             if (otherBaseType === baseType)
75665                                 continue;
75666                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
75667                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
75668                             if (derivedElsewhere && derivedElsewhere !== base) {
75669                                 continue basePropertyCheck;
75670                             }
75671                         }
75672                         if (derivedClassDecl.kind === 221 /* ClassExpression */) {
75673                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
75674                         }
75675                         else {
75676                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
75677                         }
75678                     }
75679                 }
75680                 else {
75681                     // derived overrides base.
75682                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
75683                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
75684                         // either base or derived property is private - not override, skip it
75685                         continue;
75686                     }
75687                     var errorMessage = void 0;
75688                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
75689                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
75690                     if (basePropertyFlags && derivedPropertyFlags) {
75691                         // property/accessor is overridden with property/accessor
75692                         if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
75693                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 253 /* InterfaceDeclaration */
75694                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
75695                             // when the base property is abstract or from an interface, base/derived flags don't need to match
75696                             // same when the derived property is from an assignment
75697                             continue;
75698                         }
75699                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
75700                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
75701                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
75702                             var errorMessage_1 = overriddenInstanceProperty ?
75703                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
75704                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
75705                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
75706                         }
75707                         else if (compilerOptions.useDefineForClassFields) {
75708                             var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 163 /* PropertyDeclaration */ && !d.initializer; });
75709                             if (uninitialized
75710                                 && !(derived.flags & 33554432 /* Transient */)
75711                                 && !(baseDeclarationFlags & 128 /* Abstract */)
75712                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
75713                                 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
75714                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
75715                                 var propName = uninitialized.name;
75716                                 if (uninitialized.exclamationToken
75717                                     || !constructor
75718                                     || !ts.isIdentifier(propName)
75719                                     || !strictNullChecks
75720                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
75721                                     var errorMessage_2 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration;
75722                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
75723                                 }
75724                             }
75725                         }
75726                         // correct case
75727                         continue;
75728                     }
75729                     else if (isPrototypeProperty(base)) {
75730                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
75731                             // method is overridden with method or property -- correct case
75732                             continue;
75733                         }
75734                         else {
75735                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
75736                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
75737                         }
75738                     }
75739                     else if (base.flags & 98304 /* Accessor */) {
75740                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
75741                     }
75742                     else {
75743                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
75744                     }
75745                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
75746                 }
75747             }
75748         }
75749         function getNonInterhitedProperties(type, baseTypes, properties) {
75750             if (!ts.length(baseTypes)) {
75751                 return properties;
75752             }
75753             var seen = new ts.Map();
75754             ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
75755             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
75756                 var base = baseTypes_2[_i];
75757                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
75758                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
75759                     var prop = properties_4[_a];
75760                     var existing = seen.get(prop.escapedName);
75761                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
75762                         seen.delete(prop.escapedName);
75763                     }
75764                 }
75765             }
75766             return ts.arrayFrom(seen.values());
75767         }
75768         function checkInheritedPropertiesAreIdentical(type, typeNode) {
75769             var baseTypes = getBaseTypes(type);
75770             if (baseTypes.length < 2) {
75771                 return true;
75772             }
75773             var seen = new ts.Map();
75774             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
75775             var ok = true;
75776             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
75777                 var base = baseTypes_3[_i];
75778                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
75779                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
75780                     var prop = properties_6[_a];
75781                     var existing = seen.get(prop.escapedName);
75782                     if (!existing) {
75783                         seen.set(prop.escapedName, { prop: prop, containingType: base });
75784                     }
75785                     else {
75786                         var isInheritedProperty = existing.containingType !== type;
75787                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
75788                             ok = false;
75789                             var typeName1 = typeToString(existing.containingType);
75790                             var typeName2 = typeToString(base);
75791                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
75792                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
75793                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
75794                         }
75795                     }
75796                 }
75797             }
75798             return ok;
75799         }
75800         function checkPropertyInitialization(node) {
75801             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
75802                 return;
75803             }
75804             var constructor = findConstructorDeclaration(node);
75805             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
75806                 var member = _a[_i];
75807                 if (ts.getEffectiveModifierFlags(member) & 2 /* Ambient */) {
75808                     continue;
75809                 }
75810                 if (isInstancePropertyWithoutInitializer(member)) {
75811                     var propName = member.name;
75812                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
75813                         var type = getTypeOfSymbol(getSymbolOfNode(member));
75814                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
75815                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
75816                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
75817                             }
75818                         }
75819                     }
75820                 }
75821             }
75822         }
75823         function isInstancePropertyWithoutInitializer(node) {
75824             return node.kind === 163 /* PropertyDeclaration */ &&
75825                 !ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
75826                 !node.exclamationToken &&
75827                 !node.initializer;
75828         }
75829         function isPropertyInitializedInConstructor(propName, propType, constructor) {
75830             var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), propName);
75831             ts.setParent(reference.expression, reference);
75832             ts.setParent(reference, constructor);
75833             reference.flowNode = constructor.returnFlowNode;
75834             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
75835             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
75836         }
75837         function checkInterfaceDeclaration(node) {
75838             // Grammar checking
75839             if (!checkGrammarDecoratorsAndModifiers(node))
75840                 checkGrammarInterfaceDeclaration(node);
75841             checkTypeParameters(node.typeParameters);
75842             if (produceDiagnostics) {
75843                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
75844                 checkExportsOnMergedDeclarations(node);
75845                 var symbol = getSymbolOfNode(node);
75846                 checkTypeParameterListsIdentical(symbol);
75847                 // Only check this symbol once
75848                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */);
75849                 if (node === firstInterfaceDecl) {
75850                     var type = getDeclaredTypeOfSymbol(symbol);
75851                     var typeWithThis = getTypeWithThisArgument(type);
75852                     // run subsequent checks only if first set succeeded
75853                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
75854                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
75855                             var baseType = _a[_i];
75856                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
75857                         }
75858                         checkIndexConstraints(type);
75859                     }
75860                 }
75861                 checkObjectTypeForDuplicateDeclarations(node);
75862             }
75863             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
75864                 if (!ts.isEntityNameExpression(heritageElement.expression)) {
75865                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
75866                 }
75867                 checkTypeReferenceNode(heritageElement);
75868             });
75869             ts.forEach(node.members, checkSourceElement);
75870             if (produceDiagnostics) {
75871                 checkTypeForDuplicateIndexSignatures(node);
75872                 registerForUnusedIdentifiersCheck(node);
75873             }
75874         }
75875         function checkTypeAliasDeclaration(node) {
75876             // Grammar checking
75877             checkGrammarDecoratorsAndModifiers(node);
75878             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
75879             checkExportsOnMergedDeclarations(node);
75880             checkTypeParameters(node.typeParameters);
75881             if (node.type.kind === 136 /* IntrinsicKeyword */) {
75882                 if (!intrinsicTypeKinds.has(node.name.escapedText) || ts.length(node.typeParameters) !== 1) {
75883                     error(node.type, ts.Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types);
75884                 }
75885             }
75886             else {
75887                 checkSourceElement(node.type);
75888                 registerForUnusedIdentifiersCheck(node);
75889             }
75890         }
75891         function computeEnumMemberValues(node) {
75892             var nodeLinks = getNodeLinks(node);
75893             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
75894                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
75895                 var autoValue = 0;
75896                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
75897                     var member = _a[_i];
75898                     var value = computeMemberValue(member, autoValue);
75899                     getNodeLinks(member).enumMemberValue = value;
75900                     autoValue = typeof value === "number" ? value + 1 : undefined;
75901                 }
75902             }
75903         }
75904         function computeMemberValue(member, autoValue) {
75905             if (ts.isComputedNonLiteralName(member.name)) {
75906                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
75907             }
75908             else {
75909                 var text = ts.getTextOfPropertyName(member.name);
75910                 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
75911                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
75912                 }
75913             }
75914             if (member.initializer) {
75915                 return computeConstantValue(member);
75916             }
75917             // In ambient non-const numeric enum declarations, enum members without initializers are
75918             // considered computed members (as opposed to having auto-incremented values).
75919             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
75920                 return undefined;
75921             }
75922             // If the member declaration specifies no value, the member is considered a constant enum member.
75923             // If the member is the first member in the enum declaration, it is assigned the value zero.
75924             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
75925             // occurs if the immediately preceding member is not a constant enum member.
75926             if (autoValue !== undefined) {
75927                 return autoValue;
75928             }
75929             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
75930             return undefined;
75931         }
75932         function computeConstantValue(member) {
75933             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
75934             var isConstEnum = ts.isEnumConst(member.parent);
75935             var initializer = member.initializer;
75936             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
75937             if (value !== undefined) {
75938                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
75939                     error(initializer, isNaN(value) ?
75940                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
75941                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
75942                 }
75943             }
75944             else if (enumKind === 1 /* Literal */) {
75945                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
75946                 return 0;
75947             }
75948             else if (isConstEnum) {
75949                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
75950             }
75951             else if (member.parent.flags & 8388608 /* Ambient */) {
75952                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
75953             }
75954             else {
75955                 // Only here do we need to check that the initializer is assignable to the enum type.
75956                 var source = checkExpression(initializer);
75957                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
75958                     error(initializer, ts.Diagnostics.Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead, typeToString(source));
75959                 }
75960                 else {
75961                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
75962                 }
75963             }
75964             return value;
75965             function evaluate(expr) {
75966                 switch (expr.kind) {
75967                     case 214 /* PrefixUnaryExpression */:
75968                         var value_2 = evaluate(expr.operand);
75969                         if (typeof value_2 === "number") {
75970                             switch (expr.operator) {
75971                                 case 39 /* PlusToken */: return value_2;
75972                                 case 40 /* MinusToken */: return -value_2;
75973                                 case 54 /* TildeToken */: return ~value_2;
75974                             }
75975                         }
75976                         break;
75977                     case 216 /* BinaryExpression */:
75978                         var left = evaluate(expr.left);
75979                         var right = evaluate(expr.right);
75980                         if (typeof left === "number" && typeof right === "number") {
75981                             switch (expr.operatorToken.kind) {
75982                                 case 51 /* BarToken */: return left | right;
75983                                 case 50 /* AmpersandToken */: return left & right;
75984                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
75985                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
75986                                 case 47 /* LessThanLessThanToken */: return left << right;
75987                                 case 52 /* CaretToken */: return left ^ right;
75988                                 case 41 /* AsteriskToken */: return left * right;
75989                                 case 43 /* SlashToken */: return left / right;
75990                                 case 39 /* PlusToken */: return left + right;
75991                                 case 40 /* MinusToken */: return left - right;
75992                                 case 44 /* PercentToken */: return left % right;
75993                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
75994                             }
75995                         }
75996                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
75997                             return left + right;
75998                         }
75999                         break;
76000                     case 10 /* StringLiteral */:
76001                     case 14 /* NoSubstitutionTemplateLiteral */:
76002                         return expr.text;
76003                     case 8 /* NumericLiteral */:
76004                         checkGrammarNumericLiteral(expr);
76005                         return +expr.text;
76006                     case 207 /* ParenthesizedExpression */:
76007                         return evaluate(expr.expression);
76008                     case 78 /* Identifier */:
76009                         var identifier = expr;
76010                         if (isInfinityOrNaNString(identifier.escapedText)) {
76011                             return +(identifier.escapedText);
76012                         }
76013                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
76014                     case 202 /* ElementAccessExpression */:
76015                     case 201 /* PropertyAccessExpression */:
76016                         var ex = expr;
76017                         if (isConstantMemberAccess(ex)) {
76018                             var type = getTypeOfExpression(ex.expression);
76019                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
76020                                 var name = void 0;
76021                                 if (ex.kind === 201 /* PropertyAccessExpression */) {
76022                                     name = ex.name.escapedText;
76023                                 }
76024                                 else {
76025                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
76026                                 }
76027                                 return evaluateEnumMember(expr, type.symbol, name);
76028                             }
76029                         }
76030                         break;
76031                 }
76032                 return undefined;
76033             }
76034             function evaluateEnumMember(expr, enumSymbol, name) {
76035                 var memberSymbol = enumSymbol.exports.get(name);
76036                 if (memberSymbol) {
76037                     var declaration = memberSymbol.valueDeclaration;
76038                     if (declaration !== member) {
76039                         if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
76040                             return getEnumMemberValue(declaration);
76041                         }
76042                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
76043                         return 0;
76044                     }
76045                     else {
76046                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
76047                     }
76048                 }
76049                 return undefined;
76050             }
76051         }
76052         function isConstantMemberAccess(node) {
76053             return node.kind === 78 /* Identifier */ ||
76054                 node.kind === 201 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
76055                 node.kind === 202 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
76056                     ts.isStringLiteralLike(node.argumentExpression);
76057         }
76058         function checkEnumDeclaration(node) {
76059             if (!produceDiagnostics) {
76060                 return;
76061             }
76062             // Grammar checking
76063             checkGrammarDecoratorsAndModifiers(node);
76064             checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
76065             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
76066             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
76067             checkExportsOnMergedDeclarations(node);
76068             node.members.forEach(checkEnumMember);
76069             computeEnumMemberValues(node);
76070             // Spec 2014 - Section 9.3:
76071             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
76072             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
76073             // for the first member.
76074             //
76075             // Only perform this check once per symbol
76076             var enumSymbol = getSymbolOfNode(node);
76077             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
76078             if (node === firstDeclaration) {
76079                 if (enumSymbol.declarations.length > 1) {
76080                     var enumIsConst_1 = ts.isEnumConst(node);
76081                     // check that const is placed\omitted on all enum declarations
76082                     ts.forEach(enumSymbol.declarations, function (decl) {
76083                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
76084                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
76085                         }
76086                     });
76087                 }
76088                 var seenEnumMissingInitialInitializer_1 = false;
76089                 ts.forEach(enumSymbol.declarations, function (declaration) {
76090                     // return true if we hit a violation of the rule, false otherwise
76091                     if (declaration.kind !== 255 /* EnumDeclaration */) {
76092                         return false;
76093                     }
76094                     var enumDeclaration = declaration;
76095                     if (!enumDeclaration.members.length) {
76096                         return false;
76097                     }
76098                     var firstEnumMember = enumDeclaration.members[0];
76099                     if (!firstEnumMember.initializer) {
76100                         if (seenEnumMissingInitialInitializer_1) {
76101                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
76102                         }
76103                         else {
76104                             seenEnumMissingInitialInitializer_1 = true;
76105                         }
76106                     }
76107                 });
76108             }
76109         }
76110         function checkEnumMember(node) {
76111             if (ts.isPrivateIdentifier(node.name)) {
76112                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
76113             }
76114         }
76115         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
76116             var declarations = symbol.declarations;
76117             for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
76118                 var declaration = declarations_8[_i];
76119                 if ((declaration.kind === 252 /* ClassDeclaration */ ||
76120                     (declaration.kind === 251 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
76121                     !(declaration.flags & 8388608 /* Ambient */)) {
76122                     return declaration;
76123                 }
76124             }
76125             return undefined;
76126         }
76127         function inSameLexicalScope(node1, node2) {
76128             var container1 = ts.getEnclosingBlockScopeContainer(node1);
76129             var container2 = ts.getEnclosingBlockScopeContainer(node2);
76130             if (isGlobalSourceFile(container1)) {
76131                 return isGlobalSourceFile(container2);
76132             }
76133             else if (isGlobalSourceFile(container2)) {
76134                 return false;
76135             }
76136             else {
76137                 return container1 === container2;
76138             }
76139         }
76140         function checkModuleDeclaration(node) {
76141             if (produceDiagnostics) {
76142                 // Grammar checking
76143                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
76144                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
76145                 if (isGlobalAugmentation && !inAmbientContext) {
76146                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
76147                 }
76148                 var isAmbientExternalModule = ts.isAmbientModule(node);
76149                 var contextErrorMessage = isAmbientExternalModule
76150                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
76151                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
76152                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
76153                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
76154                     return;
76155                 }
76156                 if (!checkGrammarDecoratorsAndModifiers(node)) {
76157                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
76158                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
76159                     }
76160                 }
76161                 if (ts.isIdentifier(node.name)) {
76162                     checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
76163                     checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
76164                 }
76165                 checkExportsOnMergedDeclarations(node);
76166                 var symbol = getSymbolOfNode(node);
76167                 // The following checks only apply on a non-ambient instantiated module declaration.
76168                 if (symbol.flags & 512 /* ValueModule */
76169                     && !inAmbientContext
76170                     && symbol.declarations.length > 1
76171                     && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
76172                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
76173                     if (firstNonAmbientClassOrFunc) {
76174                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
76175                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
76176                         }
76177                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
76178                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
76179                         }
76180                     }
76181                     // if the module merges with a class declaration in the same lexical scope,
76182                     // we need to track this to ensure the correct emit.
76183                     var mergedClass = ts.getDeclarationOfKind(symbol, 252 /* ClassDeclaration */);
76184                     if (mergedClass &&
76185                         inSameLexicalScope(node, mergedClass)) {
76186                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
76187                     }
76188                 }
76189                 if (isAmbientExternalModule) {
76190                     if (ts.isExternalModuleAugmentation(node)) {
76191                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
76192                         // otherwise we'll be swamped in cascading errors.
76193                         // We can detect if augmentation was applied using following rules:
76194                         // - augmentation for a global scope is always applied
76195                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
76196                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
76197                         if (checkBody && node.body) {
76198                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
76199                                 var statement = _a[_i];
76200                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
76201                             }
76202                         }
76203                     }
76204                     else if (isGlobalSourceFile(node.parent)) {
76205                         if (isGlobalAugmentation) {
76206                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
76207                         }
76208                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
76209                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
76210                         }
76211                     }
76212                     else {
76213                         if (isGlobalAugmentation) {
76214                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
76215                         }
76216                         else {
76217                             // Node is not an augmentation and is not located on the script level.
76218                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
76219                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
76220                         }
76221                     }
76222                 }
76223             }
76224             if (node.body) {
76225                 checkSourceElement(node.body);
76226                 if (!ts.isGlobalScopeAugmentation(node)) {
76227                     registerForUnusedIdentifiersCheck(node);
76228                 }
76229             }
76230         }
76231         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
76232             switch (node.kind) {
76233                 case 232 /* VariableStatement */:
76234                     // error each individual name in variable statement instead of marking the entire variable statement
76235                     for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
76236                         var decl = _a[_i];
76237                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
76238                     }
76239                     break;
76240                 case 266 /* ExportAssignment */:
76241                 case 267 /* ExportDeclaration */:
76242                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
76243                     break;
76244                 case 260 /* ImportEqualsDeclaration */:
76245                 case 261 /* ImportDeclaration */:
76246                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
76247                     break;
76248                 case 198 /* BindingElement */:
76249                 case 249 /* VariableDeclaration */:
76250                     var name = node.name;
76251                     if (ts.isBindingPattern(name)) {
76252                         for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
76253                             var el = _c[_b];
76254                             // mark individual names in binding pattern
76255                             checkModuleAugmentationElement(el, isGlobalAugmentation);
76256                         }
76257                         break;
76258                     }
76259                 // falls through
76260                 case 252 /* ClassDeclaration */:
76261                 case 255 /* EnumDeclaration */:
76262                 case 251 /* FunctionDeclaration */:
76263                 case 253 /* InterfaceDeclaration */:
76264                 case 256 /* ModuleDeclaration */:
76265                 case 254 /* TypeAliasDeclaration */:
76266                     if (isGlobalAugmentation) {
76267                         return;
76268                     }
76269                     var symbol = getSymbolOfNode(node);
76270                     if (symbol) {
76271                         // module augmentations cannot introduce new names on the top level scope of the module
76272                         // this is done it two steps
76273                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
76274                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
76275                         var reportError = !(symbol.flags & 33554432 /* Transient */);
76276                         if (!reportError) {
76277                             // symbol should not originate in augmentation
76278                             reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
76279                         }
76280                     }
76281                     break;
76282             }
76283         }
76284         function getFirstNonModuleExportsIdentifier(node) {
76285             switch (node.kind) {
76286                 case 78 /* Identifier */:
76287                     return node;
76288                 case 157 /* QualifiedName */:
76289                     do {
76290                         node = node.left;
76291                     } while (node.kind !== 78 /* Identifier */);
76292                     return node;
76293                 case 201 /* PropertyAccessExpression */:
76294                     do {
76295                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
76296                             return node.name;
76297                         }
76298                         node = node.expression;
76299                     } while (node.kind !== 78 /* Identifier */);
76300                     return node;
76301             }
76302         }
76303         function checkExternalImportOrExportDeclaration(node) {
76304             var moduleName = ts.getExternalModuleName(node);
76305             if (!moduleName || ts.nodeIsMissing(moduleName)) {
76306                 // Should be a parse error.
76307                 return false;
76308             }
76309             if (!ts.isStringLiteral(moduleName)) {
76310                 error(moduleName, ts.Diagnostics.String_literal_expected);
76311                 return false;
76312             }
76313             var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
76314             if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule) {
76315                 error(moduleName, node.kind === 267 /* ExportDeclaration */ ?
76316                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
76317                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
76318                 return false;
76319             }
76320             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
76321                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
76322                 // no need to do this again.
76323                 if (!isTopLevelInExternalModuleAugmentation(node)) {
76324                     // TypeScript 1.0 spec (April 2013): 12.1.6
76325                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
76326                     // other external modules only through top - level external module names.
76327                     // Relative external module names are not permitted.
76328                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
76329                     return false;
76330                 }
76331             }
76332             return true;
76333         }
76334         function checkAliasSymbol(node) {
76335             var symbol = getSymbolOfNode(node);
76336             var target = resolveAlias(symbol);
76337             if (target !== unknownSymbol) {
76338                 // For external modules, `symbol` represents the local symbol for an alias.
76339                 // This local symbol will merge any other local declarations (excluding other aliases)
76340                 // and symbol.flags will contains combined representation for all merged declaration.
76341                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
76342                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
76343                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
76344                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
76345                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
76346                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
76347                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
76348                 if (target.flags & excludedMeanings) {
76349                     var message = node.kind === 270 /* ExportSpecifier */ ?
76350                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
76351                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
76352                     error(node, message, symbolToString(symbol));
76353                 }
76354                 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
76355                 if (compilerOptions.isolatedModules
76356                     && node.kind === 270 /* ExportSpecifier */
76357                     && !node.parent.parent.isTypeOnly
76358                     && !(target.flags & 111551 /* Value */)
76359                     && !(node.flags & 8388608 /* Ambient */)) {
76360                     error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
76361                 }
76362                 if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) {
76363                     errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName);
76364                 }
76365             }
76366         }
76367         function checkImportBinding(node) {
76368             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
76369             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
76370             checkAliasSymbol(node);
76371             if (node.kind === 265 /* ImportSpecifier */ &&
76372                 ts.idText(node.propertyName || node.name) === "default" &&
76373                 compilerOptions.esModuleInterop &&
76374                 moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
76375                 checkExternalEmitHelpers(node, 262144 /* ImportDefault */);
76376             }
76377         }
76378         function checkImportDeclaration(node) {
76379             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
76380                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
76381                 return;
76382             }
76383             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
76384                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
76385             }
76386             if (checkExternalImportOrExportDeclaration(node)) {
76387                 var importClause = node.importClause;
76388                 if (importClause && !checkGrammarImportClause(importClause)) {
76389                     if (importClause.name) {
76390                         checkImportBinding(importClause);
76391                     }
76392                     if (importClause.namedBindings) {
76393                         if (importClause.namedBindings.kind === 263 /* NamespaceImport */) {
76394                             checkImportBinding(importClause.namedBindings);
76395                             if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) {
76396                                 // import * as ns from "foo";
76397                                 checkExternalEmitHelpers(node, 131072 /* ImportStar */);
76398                             }
76399                         }
76400                         else {
76401                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
76402                             if (moduleExisted) {
76403                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
76404                             }
76405                         }
76406                     }
76407                 }
76408             }
76409         }
76410         function checkImportEqualsDeclaration(node) {
76411             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
76412                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
76413                 return;
76414             }
76415             checkGrammarDecoratorsAndModifiers(node);
76416             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
76417                 checkImportBinding(node);
76418                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
76419                     markExportAsReferenced(node);
76420                 }
76421                 if (node.moduleReference.kind !== 272 /* ExternalModuleReference */) {
76422                     var target = resolveAlias(getSymbolOfNode(node));
76423                     if (target !== unknownSymbol) {
76424                         if (target.flags & 111551 /* Value */) {
76425                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
76426                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
76427                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
76428                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
76429                             }
76430                         }
76431                         if (target.flags & 788968 /* Type */) {
76432                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
76433                         }
76434                     }
76435                 }
76436                 else {
76437                     if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
76438                         // Import equals declaration is deprecated in es6 or above
76439                         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);
76440                     }
76441                 }
76442             }
76443         }
76444         function checkExportDeclaration(node) {
76445             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
76446                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
76447                 return;
76448             }
76449             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
76450                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
76451             }
76452             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
76453                 checkExternalEmitHelpers(node, 4194304 /* CreateBinding */);
76454             }
76455             checkGrammarExportDeclaration(node);
76456             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
76457                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
76458                     // export { x, y }
76459                     // export { x, y } from "foo"
76460                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
76461                     var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
76462                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 257 /* ModuleBlock */ &&
76463                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
76464                     if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
76465                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
76466                     }
76467                 }
76468                 else {
76469                     // export * from "foo"
76470                     // export * as ns from "foo";
76471                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
76472                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
76473                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
76474                     }
76475                     else if (node.exportClause) {
76476                         checkAliasSymbol(node.exportClause);
76477                     }
76478                     if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
76479                         if (node.exportClause) {
76480                             // export * as ns from "foo";
76481                             // For ES2015 modules, we emit it as a pair of `import * as a_1 ...; export { a_1 as ns }` and don't need the helper.
76482                             // We only use the helper here when in esModuleInterop
76483                             if (compilerOptions.esModuleInterop) {
76484                                 checkExternalEmitHelpers(node, 131072 /* ImportStar */);
76485                             }
76486                         }
76487                         else {
76488                             // export * from "foo"
76489                             checkExternalEmitHelpers(node, 65536 /* ExportStar */);
76490                         }
76491                     }
76492                 }
76493             }
76494         }
76495         function checkGrammarExportDeclaration(node) {
76496             var _a;
76497             var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 268 /* NamedExports */;
76498             if (isTypeOnlyExportStar) {
76499                 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
76500             }
76501             return !isTypeOnlyExportStar;
76502         }
76503         function checkGrammarModuleElementContext(node, errorMessage) {
76504             var isInAppropriateContext = node.parent.kind === 297 /* SourceFile */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 256 /* ModuleDeclaration */;
76505             if (!isInAppropriateContext) {
76506                 grammarErrorOnFirstToken(node, errorMessage);
76507             }
76508             return !isInAppropriateContext;
76509         }
76510         function importClauseContainsReferencedImport(importClause) {
76511             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
76512                 return !!getSymbolOfNode(declaration).isReferenced;
76513             });
76514         }
76515         function importClauseContainsConstEnumUsedAsValue(importClause) {
76516             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
76517                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
76518             });
76519         }
76520         function checkImportsForTypeOnlyConversion(sourceFile) {
76521             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
76522                 var statement = _a[_i];
76523                 if (ts.isImportDeclaration(statement) &&
76524                     statement.importClause &&
76525                     !statement.importClause.isTypeOnly &&
76526                     importClauseContainsReferencedImport(statement.importClause) &&
76527                     !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
76528                     !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
76529                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
76530                 }
76531             }
76532         }
76533         function checkExportSpecifier(node) {
76534             checkAliasSymbol(node);
76535             if (ts.getEmitDeclarations(compilerOptions)) {
76536                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
76537             }
76538             if (!node.parent.parent.moduleSpecifier) {
76539                 var exportedName = node.propertyName || node.name;
76540                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
76541                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
76542                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
76543                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
76544                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
76545                 }
76546                 else {
76547                     markExportAsReferenced(node);
76548                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
76549                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
76550                         checkExpressionCached(node.propertyName || node.name);
76551                     }
76552                 }
76553             }
76554             else {
76555                 if (compilerOptions.esModuleInterop &&
76556                     moduleKind !== ts.ModuleKind.System &&
76557                     moduleKind < ts.ModuleKind.ES2015 &&
76558                     ts.idText(node.propertyName || node.name) === "default") {
76559                     checkExternalEmitHelpers(node, 262144 /* ImportDefault */);
76560                 }
76561             }
76562         }
76563         function checkExportAssignment(node) {
76564             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
76565                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
76566                 return;
76567             }
76568             var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent;
76569             if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
76570                 if (node.isExportEquals) {
76571                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
76572                 }
76573                 else {
76574                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
76575                 }
76576                 return;
76577             }
76578             // Grammar checking
76579             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
76580                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
76581             }
76582             if (node.expression.kind === 78 /* Identifier */) {
76583                 var id = node.expression;
76584                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
76585                 if (sym) {
76586                     markAliasReferenced(sym, id);
76587                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
76588                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
76589                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
76590                         // However if it is a value, we need to check it's being used correctly
76591                         checkExpressionCached(node.expression);
76592                     }
76593                 }
76594                 else {
76595                     checkExpressionCached(node.expression); // doesn't resolve, check as expression to mark as error
76596                 }
76597                 if (ts.getEmitDeclarations(compilerOptions)) {
76598                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
76599                 }
76600             }
76601             else {
76602                 checkExpressionCached(node.expression);
76603             }
76604             checkExternalModuleExports(container);
76605             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
76606                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
76607             }
76608             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
76609                 if (moduleKind >= ts.ModuleKind.ES2015) {
76610                     // export assignment is not supported in es6 modules
76611                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
76612                 }
76613                 else if (moduleKind === ts.ModuleKind.System) {
76614                     // system modules does not support export assignment
76615                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
76616                 }
76617             }
76618         }
76619         function hasExportedMembers(moduleSymbol) {
76620             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
76621         }
76622         function checkExternalModuleExports(node) {
76623             var moduleSymbol = getSymbolOfNode(node);
76624             var links = getSymbolLinks(moduleSymbol);
76625             if (!links.exportsChecked) {
76626                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
76627                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
76628                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
76629                     if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
76630                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
76631                     }
76632                 }
76633                 // Checks for export * conflicts
76634                 var exports_2 = getExportsOfModule(moduleSymbol);
76635                 if (exports_2) {
76636                     exports_2.forEach(function (_a, id) {
76637                         var declarations = _a.declarations, flags = _a.flags;
76638                         if (id === "__export") {
76639                             return;
76640                         }
76641                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
76642                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
76643                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
76644                             return;
76645                         }
76646                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
76647                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
76648                             // it is legal to merge type alias with other values
76649                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
76650                             return;
76651                         }
76652                         if (exportedDeclarationsCount > 1) {
76653                             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
76654                                 var declaration = declarations_9[_i];
76655                                 if (isNotOverload(declaration)) {
76656                                     diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
76657                                 }
76658                             }
76659                         }
76660                     });
76661                 }
76662                 links.exportsChecked = true;
76663             }
76664         }
76665         function checkSourceElement(node) {
76666             if (node) {
76667                 var saveCurrentNode = currentNode;
76668                 currentNode = node;
76669                 instantiationCount = 0;
76670                 checkSourceElementWorker(node);
76671                 currentNode = saveCurrentNode;
76672             }
76673         }
76674         function checkSourceElementWorker(node) {
76675             if (ts.isInJSFile(node)) {
76676                 ts.forEach(node.jsDoc, function (_a) {
76677                     var tags = _a.tags;
76678                     return ts.forEach(tags, checkSourceElement);
76679                 });
76680             }
76681             var kind = node.kind;
76682             if (cancellationToken) {
76683                 // Only bother checking on a few construct kinds.  We don't want to be excessively
76684                 // hitting the cancellation token on every node we check.
76685                 switch (kind) {
76686                     case 256 /* ModuleDeclaration */:
76687                     case 252 /* ClassDeclaration */:
76688                     case 253 /* InterfaceDeclaration */:
76689                     case 251 /* FunctionDeclaration */:
76690                         cancellationToken.throwIfCancellationRequested();
76691                 }
76692             }
76693             if (kind >= 232 /* FirstStatement */ && kind <= 248 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
76694                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
76695             }
76696             switch (kind) {
76697                 case 159 /* TypeParameter */:
76698                     return checkTypeParameter(node);
76699                 case 160 /* Parameter */:
76700                     return checkParameter(node);
76701                 case 163 /* PropertyDeclaration */:
76702                     return checkPropertyDeclaration(node);
76703                 case 162 /* PropertySignature */:
76704                     return checkPropertySignature(node);
76705                 case 174 /* FunctionType */:
76706                 case 175 /* ConstructorType */:
76707                 case 169 /* CallSignature */:
76708                 case 170 /* ConstructSignature */:
76709                 case 171 /* IndexSignature */:
76710                     return checkSignatureDeclaration(node);
76711                 case 165 /* MethodDeclaration */:
76712                 case 164 /* MethodSignature */:
76713                     return checkMethodDeclaration(node);
76714                 case 166 /* Constructor */:
76715                     return checkConstructorDeclaration(node);
76716                 case 167 /* GetAccessor */:
76717                 case 168 /* SetAccessor */:
76718                     return checkAccessorDeclaration(node);
76719                 case 173 /* TypeReference */:
76720                     return checkTypeReferenceNode(node);
76721                 case 172 /* TypePredicate */:
76722                     return checkTypePredicate(node);
76723                 case 176 /* TypeQuery */:
76724                     return checkTypeQuery(node);
76725                 case 177 /* TypeLiteral */:
76726                     return checkTypeLiteral(node);
76727                 case 178 /* ArrayType */:
76728                     return checkArrayType(node);
76729                 case 179 /* TupleType */:
76730                     return checkTupleType(node);
76731                 case 182 /* UnionType */:
76732                 case 183 /* IntersectionType */:
76733                     return checkUnionOrIntersectionType(node);
76734                 case 186 /* ParenthesizedType */:
76735                 case 180 /* OptionalType */:
76736                 case 181 /* RestType */:
76737                     return checkSourceElement(node.type);
76738                 case 187 /* ThisType */:
76739                     return checkThisType(node);
76740                 case 188 /* TypeOperator */:
76741                     return checkTypeOperator(node);
76742                 case 184 /* ConditionalType */:
76743                     return checkConditionalType(node);
76744                 case 185 /* InferType */:
76745                     return checkInferType(node);
76746                 case 193 /* TemplateLiteralType */:
76747                     return checkTemplateLiteralType(node);
76748                 case 195 /* ImportType */:
76749                     return checkImportType(node);
76750                 case 192 /* NamedTupleMember */:
76751                     return checkNamedTupleMember(node);
76752                 case 315 /* JSDocAugmentsTag */:
76753                     return checkJSDocAugmentsTag(node);
76754                 case 316 /* JSDocImplementsTag */:
76755                     return checkJSDocImplementsTag(node);
76756                 case 331 /* JSDocTypedefTag */:
76757                 case 324 /* JSDocCallbackTag */:
76758                 case 325 /* JSDocEnumTag */:
76759                     return checkJSDocTypeAliasTag(node);
76760                 case 330 /* JSDocTemplateTag */:
76761                     return checkJSDocTemplateTag(node);
76762                 case 329 /* JSDocTypeTag */:
76763                     return checkJSDocTypeTag(node);
76764                 case 326 /* JSDocParameterTag */:
76765                     return checkJSDocParameterTag(node);
76766                 case 333 /* JSDocPropertyTag */:
76767                     return checkJSDocPropertyTag(node);
76768                 case 308 /* JSDocFunctionType */:
76769                     checkJSDocFunctionType(node);
76770                 // falls through
76771                 case 306 /* JSDocNonNullableType */:
76772                 case 305 /* JSDocNullableType */:
76773                 case 303 /* JSDocAllType */:
76774                 case 304 /* JSDocUnknownType */:
76775                 case 312 /* JSDocTypeLiteral */:
76776                     checkJSDocTypeIsInJsFile(node);
76777                     ts.forEachChild(node, checkSourceElement);
76778                     return;
76779                 case 309 /* JSDocVariadicType */:
76780                     checkJSDocVariadicType(node);
76781                     return;
76782                 case 301 /* JSDocTypeExpression */:
76783                     return checkSourceElement(node.type);
76784                 case 189 /* IndexedAccessType */:
76785                     return checkIndexedAccessType(node);
76786                 case 190 /* MappedType */:
76787                     return checkMappedType(node);
76788                 case 251 /* FunctionDeclaration */:
76789                     return checkFunctionDeclaration(node);
76790                 case 230 /* Block */:
76791                 case 257 /* ModuleBlock */:
76792                     return checkBlock(node);
76793                 case 232 /* VariableStatement */:
76794                     return checkVariableStatement(node);
76795                 case 233 /* ExpressionStatement */:
76796                     return checkExpressionStatement(node);
76797                 case 234 /* IfStatement */:
76798                     return checkIfStatement(node);
76799                 case 235 /* DoStatement */:
76800                     return checkDoStatement(node);
76801                 case 236 /* WhileStatement */:
76802                     return checkWhileStatement(node);
76803                 case 237 /* ForStatement */:
76804                     return checkForStatement(node);
76805                 case 238 /* ForInStatement */:
76806                     return checkForInStatement(node);
76807                 case 239 /* ForOfStatement */:
76808                     return checkForOfStatement(node);
76809                 case 240 /* ContinueStatement */:
76810                 case 241 /* BreakStatement */:
76811                     return checkBreakOrContinueStatement(node);
76812                 case 242 /* ReturnStatement */:
76813                     return checkReturnStatement(node);
76814                 case 243 /* WithStatement */:
76815                     return checkWithStatement(node);
76816                 case 244 /* SwitchStatement */:
76817                     return checkSwitchStatement(node);
76818                 case 245 /* LabeledStatement */:
76819                     return checkLabeledStatement(node);
76820                 case 246 /* ThrowStatement */:
76821                     return checkThrowStatement(node);
76822                 case 247 /* TryStatement */:
76823                     return checkTryStatement(node);
76824                 case 249 /* VariableDeclaration */:
76825                     return checkVariableDeclaration(node);
76826                 case 198 /* BindingElement */:
76827                     return checkBindingElement(node);
76828                 case 252 /* ClassDeclaration */:
76829                     return checkClassDeclaration(node);
76830                 case 253 /* InterfaceDeclaration */:
76831                     return checkInterfaceDeclaration(node);
76832                 case 254 /* TypeAliasDeclaration */:
76833                     return checkTypeAliasDeclaration(node);
76834                 case 255 /* EnumDeclaration */:
76835                     return checkEnumDeclaration(node);
76836                 case 256 /* ModuleDeclaration */:
76837                     return checkModuleDeclaration(node);
76838                 case 261 /* ImportDeclaration */:
76839                     return checkImportDeclaration(node);
76840                 case 260 /* ImportEqualsDeclaration */:
76841                     return checkImportEqualsDeclaration(node);
76842                 case 267 /* ExportDeclaration */:
76843                     return checkExportDeclaration(node);
76844                 case 266 /* ExportAssignment */:
76845                     return checkExportAssignment(node);
76846                 case 231 /* EmptyStatement */:
76847                 case 248 /* DebuggerStatement */:
76848                     checkGrammarStatementInAmbientContext(node);
76849                     return;
76850                 case 271 /* MissingDeclaration */:
76851                     return checkMissingDeclaration(node);
76852             }
76853         }
76854         function checkJSDocTypeIsInJsFile(node) {
76855             if (!ts.isInJSFile(node)) {
76856                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
76857             }
76858         }
76859         function checkJSDocVariadicType(node) {
76860             checkJSDocTypeIsInJsFile(node);
76861             checkSourceElement(node.type);
76862             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
76863             var parent = node.parent;
76864             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
76865                 if (ts.last(parent.parent.parameters) !== parent) {
76866                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
76867                 }
76868                 return;
76869             }
76870             if (!ts.isJSDocTypeExpression(parent)) {
76871                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
76872             }
76873             var paramTag = node.parent.parent;
76874             if (!ts.isJSDocParameterTag(paramTag)) {
76875                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
76876                 return;
76877             }
76878             var param = ts.getParameterSymbolFromJSDoc(paramTag);
76879             if (!param) {
76880                 // We will error in `checkJSDocParameterTag`.
76881                 return;
76882             }
76883             var host = ts.getHostSignatureFromJSDoc(paramTag);
76884             if (!host || ts.last(host.parameters).symbol !== param) {
76885                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
76886             }
76887         }
76888         function getTypeFromJSDocVariadicType(node) {
76889             var type = getTypeFromTypeNode(node.type);
76890             var parent = node.parent;
76891             var paramTag = node.parent.parent;
76892             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
76893                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
76894                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
76895                 if (host_1) {
76896                     /*
76897                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
76898                     So in the following situation we will not create an array type:
76899                         /** @param {...number} a * /
76900                         function f(a) {}
76901                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
76902                     */
76903                     var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
76904                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
76905                     if (!lastParamDeclaration ||
76906                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
76907                         return createArrayType(type);
76908                     }
76909                 }
76910             }
76911             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
76912                 return createArrayType(type);
76913             }
76914             return addOptionality(type);
76915         }
76916         // Function and class expression bodies are checked after all statements in the enclosing body. This is
76917         // to ensure constructs like the following are permitted:
76918         //     const foo = function () {
76919         //        const s = foo();
76920         //        return "hello";
76921         //     }
76922         // Here, performing a full type check of the body of the function expression whilst in the process of
76923         // determining the type of foo would cause foo to be given type any because of the recursive reference.
76924         // Delaying the type check of the body ensures foo has been assigned a type.
76925         function checkNodeDeferred(node) {
76926             var enclosingFile = ts.getSourceFileOfNode(node);
76927             var links = getNodeLinks(enclosingFile);
76928             if (!(links.flags & 1 /* TypeChecked */)) {
76929                 links.deferredNodes = links.deferredNodes || new ts.Map();
76930                 var id = getNodeId(node);
76931                 links.deferredNodes.set(id, node);
76932             }
76933         }
76934         function checkDeferredNodes(context) {
76935             var links = getNodeLinks(context);
76936             if (links.deferredNodes) {
76937                 links.deferredNodes.forEach(checkDeferredNode);
76938             }
76939         }
76940         function checkDeferredNode(node) {
76941             var saveCurrentNode = currentNode;
76942             currentNode = node;
76943             instantiationCount = 0;
76944             switch (node.kind) {
76945                 case 203 /* CallExpression */:
76946                 case 204 /* NewExpression */:
76947                 case 205 /* TaggedTemplateExpression */:
76948                 case 161 /* Decorator */:
76949                 case 275 /* JsxOpeningElement */:
76950                     // These node kinds are deferred checked when overload resolution fails
76951                     // To save on work, we ensure the arguments are checked just once, in
76952                     // a deferred way
76953                     resolveUntypedCall(node);
76954                     break;
76955                 case 208 /* FunctionExpression */:
76956                 case 209 /* ArrowFunction */:
76957                 case 165 /* MethodDeclaration */:
76958                 case 164 /* MethodSignature */:
76959                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
76960                     break;
76961                 case 167 /* GetAccessor */:
76962                 case 168 /* SetAccessor */:
76963                     checkAccessorDeclaration(node);
76964                     break;
76965                 case 221 /* ClassExpression */:
76966                     checkClassExpressionDeferred(node);
76967                     break;
76968                 case 274 /* JsxSelfClosingElement */:
76969                     checkJsxSelfClosingElementDeferred(node);
76970                     break;
76971                 case 273 /* JsxElement */:
76972                     checkJsxElementDeferred(node);
76973                     break;
76974             }
76975             currentNode = saveCurrentNode;
76976         }
76977         function checkSourceFile(node) {
76978             var tracingData = ["check" /* Check */, "checkSourceFile", { path: node.path }];
76979             ts.tracing.begin.apply(ts.tracing, tracingData);
76980             ts.performance.mark("beforeCheck");
76981             checkSourceFileWorker(node);
76982             ts.performance.mark("afterCheck");
76983             ts.performance.measure("Check", "beforeCheck", "afterCheck");
76984             ts.tracing.end.apply(ts.tracing, tracingData);
76985         }
76986         function unusedIsError(kind, isAmbient) {
76987             if (isAmbient) {
76988                 return false;
76989             }
76990             switch (kind) {
76991                 case 0 /* Local */:
76992                     return !!compilerOptions.noUnusedLocals;
76993                 case 1 /* Parameter */:
76994                     return !!compilerOptions.noUnusedParameters;
76995                 default:
76996                     return ts.Debug.assertNever(kind);
76997             }
76998         }
76999         function getPotentiallyUnusedIdentifiers(sourceFile) {
77000             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
77001         }
77002         // Fully type check a source file and collect the relevant diagnostics.
77003         function checkSourceFileWorker(node) {
77004             var links = getNodeLinks(node);
77005             if (!(links.flags & 1 /* TypeChecked */)) {
77006                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
77007                     return;
77008                 }
77009                 // Grammar checking
77010                 checkGrammarSourceFile(node);
77011                 ts.clear(potentialThisCollisions);
77012                 ts.clear(potentialNewTargetCollisions);
77013                 ts.clear(potentialWeakMapCollisions);
77014                 ts.forEach(node.statements, checkSourceElement);
77015                 checkSourceElement(node.endOfFileToken);
77016                 checkDeferredNodes(node);
77017                 if (ts.isExternalOrCommonJsModule(node)) {
77018                     registerForUnusedIdentifiersCheck(node);
77019                 }
77020                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
77021                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
77022                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
77023                             diagnostics.add(diag);
77024                         }
77025                     });
77026                 }
77027                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
77028                     !node.isDeclarationFile &&
77029                     ts.isExternalModule(node)) {
77030                     checkImportsForTypeOnlyConversion(node);
77031                 }
77032                 if (ts.isExternalOrCommonJsModule(node)) {
77033                     checkExternalModuleExports(node);
77034                 }
77035                 if (potentialThisCollisions.length) {
77036                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
77037                     ts.clear(potentialThisCollisions);
77038                 }
77039                 if (potentialNewTargetCollisions.length) {
77040                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
77041                     ts.clear(potentialNewTargetCollisions);
77042                 }
77043                 if (potentialWeakMapCollisions.length) {
77044                     ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
77045                     ts.clear(potentialWeakMapCollisions);
77046                 }
77047                 links.flags |= 1 /* TypeChecked */;
77048             }
77049         }
77050         function getDiagnostics(sourceFile, ct) {
77051             try {
77052                 // Record the cancellation token so it can be checked later on during checkSourceElement.
77053                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
77054                 // this call is done.
77055                 cancellationToken = ct;
77056                 return getDiagnosticsWorker(sourceFile);
77057             }
77058             finally {
77059                 cancellationToken = undefined;
77060             }
77061         }
77062         function getDiagnosticsWorker(sourceFile) {
77063             throwIfNonDiagnosticsProducing();
77064             if (sourceFile) {
77065                 // Some global diagnostics are deferred until they are needed and
77066                 // may not be reported in the first call to getGlobalDiagnostics.
77067                 // We should catch these changes and report them.
77068                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
77069                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
77070                 checkSourceFile(sourceFile);
77071                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
77072                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
77073                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
77074                     // If the arrays are not the same reference, new diagnostics were added.
77075                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
77076                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
77077                 }
77078                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
77079                     // If the arrays are the same reference, but the length has changed, a single
77080                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
77081                     // same array.
77082                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
77083                 }
77084                 return semanticDiagnostics;
77085             }
77086             // Global diagnostics are always added when a file is not provided to
77087             // getDiagnostics
77088             ts.forEach(host.getSourceFiles(), checkSourceFile);
77089             return diagnostics.getDiagnostics();
77090         }
77091         function getGlobalDiagnostics() {
77092             throwIfNonDiagnosticsProducing();
77093             return diagnostics.getGlobalDiagnostics();
77094         }
77095         function throwIfNonDiagnosticsProducing() {
77096             if (!produceDiagnostics) {
77097                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
77098             }
77099         }
77100         // Language service support
77101         function getSymbolsInScope(location, meaning) {
77102             if (location.flags & 16777216 /* InWithStatement */) {
77103                 // We cannot answer semantic questions within a with block, do not proceed any further
77104                 return [];
77105             }
77106             var symbols = ts.createSymbolTable();
77107             var isStatic = false;
77108             populateSymbols();
77109             symbols.delete("this" /* This */); // Not a symbol, a keyword
77110             return symbolsToArray(symbols);
77111             function populateSymbols() {
77112                 while (location) {
77113                     if (location.locals && !isGlobalSourceFile(location)) {
77114                         copySymbols(location.locals, meaning);
77115                     }
77116                     switch (location.kind) {
77117                         case 297 /* SourceFile */:
77118                             if (!ts.isExternalOrCommonJsModule(location))
77119                                 break;
77120                         // falls through
77121                         case 256 /* ModuleDeclaration */:
77122                             copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
77123                             break;
77124                         case 255 /* EnumDeclaration */:
77125                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
77126                             break;
77127                         case 221 /* ClassExpression */:
77128                             var className = location.name;
77129                             if (className) {
77130                                 copySymbol(location.symbol, meaning);
77131                             }
77132                         // this fall-through is necessary because we would like to handle
77133                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
77134                         // falls through
77135                         case 252 /* ClassDeclaration */:
77136                         case 253 /* InterfaceDeclaration */:
77137                             // If we didn't come from static member of class or interface,
77138                             // add the type parameters into the symbol table
77139                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
77140                             // Note: that the memberFlags come from previous iteration.
77141                             if (!isStatic) {
77142                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
77143                             }
77144                             break;
77145                         case 208 /* FunctionExpression */:
77146                             var funcName = location.name;
77147                             if (funcName) {
77148                                 copySymbol(location.symbol, meaning);
77149                             }
77150                             break;
77151                     }
77152                     if (ts.introducesArgumentsExoticObject(location)) {
77153                         copySymbol(argumentsSymbol, meaning);
77154                     }
77155                     isStatic = ts.hasSyntacticModifier(location, 32 /* Static */);
77156                     location = location.parent;
77157                 }
77158                 copySymbols(globals, meaning);
77159             }
77160             /**
77161              * Copy the given symbol into symbol tables if the symbol has the given meaning
77162              * and it doesn't already existed in the symbol table
77163              * @param key a key for storing in symbol table; if undefined, use symbol.name
77164              * @param symbol the symbol to be added into symbol table
77165              * @param meaning meaning of symbol to filter by before adding to symbol table
77166              */
77167             function copySymbol(symbol, meaning) {
77168                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
77169                     var id = symbol.escapedName;
77170                     // We will copy all symbol regardless of its reserved name because
77171                     // symbolsToArray will check whether the key is a reserved name and
77172                     // it will not copy symbol with reserved name to the array
77173                     if (!symbols.has(id)) {
77174                         symbols.set(id, symbol);
77175                     }
77176                 }
77177             }
77178             function copySymbols(source, meaning) {
77179                 if (meaning) {
77180                     source.forEach(function (symbol) {
77181                         copySymbol(symbol, meaning);
77182                     });
77183                 }
77184             }
77185         }
77186         function isTypeDeclarationName(name) {
77187             return name.kind === 78 /* Identifier */ &&
77188                 isTypeDeclaration(name.parent) &&
77189                 ts.getNameOfDeclaration(name.parent) === name;
77190         }
77191         function isTypeDeclaration(node) {
77192             switch (node.kind) {
77193                 case 159 /* TypeParameter */:
77194                 case 252 /* ClassDeclaration */:
77195                 case 253 /* InterfaceDeclaration */:
77196                 case 254 /* TypeAliasDeclaration */:
77197                 case 255 /* EnumDeclaration */:
77198                 case 331 /* JSDocTypedefTag */:
77199                 case 324 /* JSDocCallbackTag */:
77200                 case 325 /* JSDocEnumTag */:
77201                     return true;
77202                 case 262 /* ImportClause */:
77203                     return node.isTypeOnly;
77204                 case 265 /* ImportSpecifier */:
77205                 case 270 /* ExportSpecifier */:
77206                     return node.parent.parent.isTypeOnly;
77207                 default:
77208                     return false;
77209             }
77210         }
77211         // True if the given identifier is part of a type reference
77212         function isTypeReferenceIdentifier(node) {
77213             while (node.parent.kind === 157 /* QualifiedName */) {
77214                 node = node.parent;
77215             }
77216             return node.parent.kind === 173 /* TypeReference */;
77217         }
77218         function isHeritageClauseElementIdentifier(node) {
77219             while (node.parent.kind === 201 /* PropertyAccessExpression */) {
77220                 node = node.parent;
77221             }
77222             return node.parent.kind === 223 /* ExpressionWithTypeArguments */;
77223         }
77224         function isJSDocEntryNameReference(node) {
77225             while (node.parent.kind === 157 /* QualifiedName */) {
77226                 node = node.parent;
77227             }
77228             while (node.parent.kind === 201 /* PropertyAccessExpression */) {
77229                 node = node.parent;
77230             }
77231             return node.parent.kind === 302 /* JSDocNameReference */;
77232         }
77233         function forEachEnclosingClass(node, callback) {
77234             var result;
77235             while (true) {
77236                 node = ts.getContainingClass(node);
77237                 if (!node)
77238                     break;
77239                 if (result = callback(node))
77240                     break;
77241             }
77242             return result;
77243         }
77244         function isNodeUsedDuringClassInitialization(node) {
77245             return !!ts.findAncestor(node, function (element) {
77246                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
77247                     return true;
77248                 }
77249                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
77250                     return "quit";
77251                 }
77252                 return false;
77253             });
77254         }
77255         function isNodeWithinClass(node, classDeclaration) {
77256             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
77257         }
77258         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
77259             while (nodeOnRightSide.parent.kind === 157 /* QualifiedName */) {
77260                 nodeOnRightSide = nodeOnRightSide.parent;
77261             }
77262             if (nodeOnRightSide.parent.kind === 260 /* ImportEqualsDeclaration */) {
77263                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
77264             }
77265             if (nodeOnRightSide.parent.kind === 266 /* ExportAssignment */) {
77266                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
77267             }
77268             return undefined;
77269         }
77270         function isInRightSideOfImportOrExportAssignment(node) {
77271             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
77272         }
77273         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
77274             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
77275             switch (specialPropertyAssignmentKind) {
77276                 case 1 /* ExportsProperty */:
77277                 case 3 /* PrototypeProperty */:
77278                     return getSymbolOfNode(entityName.parent);
77279                 case 4 /* ThisProperty */:
77280                 case 2 /* ModuleExports */:
77281                 case 5 /* Property */:
77282                     return getSymbolOfNode(entityName.parent.parent);
77283             }
77284         }
77285         function isImportTypeQualifierPart(node) {
77286             var parent = node.parent;
77287             while (ts.isQualifiedName(parent)) {
77288                 node = parent;
77289                 parent = parent.parent;
77290             }
77291             if (parent && parent.kind === 195 /* ImportType */ && parent.qualifier === node) {
77292                 return parent;
77293             }
77294             return undefined;
77295         }
77296         function getSymbolOfNameOrPropertyAccessExpression(name) {
77297             if (ts.isDeclarationName(name)) {
77298                 return getSymbolOfNode(name.parent);
77299             }
77300             if (ts.isInJSFile(name) &&
77301                 name.parent.kind === 201 /* PropertyAccessExpression */ &&
77302                 name.parent === name.parent.parent.left) {
77303                 // Check if this is a special property assignment
77304                 if (!ts.isPrivateIdentifier(name)) {
77305                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
77306                     if (specialPropertyAssignmentSymbol) {
77307                         return specialPropertyAssignmentSymbol;
77308                     }
77309                 }
77310             }
77311             if (name.parent.kind === 266 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
77312                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
77313                 var success = resolveEntityName(name, 
77314                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
77315                 if (success && success !== unknownSymbol) {
77316                     return success;
77317                 }
77318             }
77319             else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
77320                 // Since we already checked for ExportAssignment, this really could only be an Import
77321                 var importEqualsDeclaration = ts.getAncestor(name, 260 /* ImportEqualsDeclaration */);
77322                 ts.Debug.assert(importEqualsDeclaration !== undefined);
77323                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
77324             }
77325             if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
77326                 var possibleImportNode = isImportTypeQualifierPart(name);
77327                 if (possibleImportNode) {
77328                     getTypeFromTypeNode(possibleImportNode);
77329                     var sym = getNodeLinks(name).resolvedSymbol;
77330                     return sym === unknownSymbol ? undefined : sym;
77331                 }
77332             }
77333             while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
77334                 name = name.parent;
77335             }
77336             if (isHeritageClauseElementIdentifier(name)) {
77337                 var meaning = 0 /* None */;
77338                 // In an interface or class, we're definitely interested in a type.
77339                 if (name.parent.kind === 223 /* ExpressionWithTypeArguments */) {
77340                     meaning = 788968 /* Type */;
77341                     // In a class 'extends' clause we are also looking for a value.
77342                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
77343                         meaning |= 111551 /* Value */;
77344                     }
77345                 }
77346                 else {
77347                     meaning = 1920 /* Namespace */;
77348                 }
77349                 meaning |= 2097152 /* Alias */;
77350                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
77351                 if (entityNameSymbol) {
77352                     return entityNameSymbol;
77353                 }
77354             }
77355             if (name.parent.kind === 326 /* JSDocParameterTag */) {
77356                 return ts.getParameterSymbolFromJSDoc(name.parent);
77357             }
77358             if (name.parent.kind === 159 /* TypeParameter */ && name.parent.parent.kind === 330 /* JSDocTemplateTag */) {
77359                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
77360                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
77361                 return typeParameter && typeParameter.symbol;
77362             }
77363             if (ts.isExpressionNode(name)) {
77364                 if (ts.nodeIsMissing(name)) {
77365                     // Missing entity name.
77366                     return undefined;
77367                 }
77368                 if (name.kind === 78 /* Identifier */) {
77369                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
77370                         var symbol = getIntrinsicTagSymbol(name.parent);
77371                         return symbol === unknownSymbol ? undefined : symbol;
77372                     }
77373                     return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
77374                 }
77375                 else if (name.kind === 201 /* PropertyAccessExpression */ || name.kind === 157 /* QualifiedName */) {
77376                     var links = getNodeLinks(name);
77377                     if (links.resolvedSymbol) {
77378                         return links.resolvedSymbol;
77379                     }
77380                     if (name.kind === 201 /* PropertyAccessExpression */) {
77381                         checkPropertyAccessExpression(name);
77382                     }
77383                     else {
77384                         checkQualifiedName(name);
77385                     }
77386                     return links.resolvedSymbol;
77387                 }
77388             }
77389             else if (isTypeReferenceIdentifier(name)) {
77390                 var meaning = name.parent.kind === 173 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
77391                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
77392             }
77393             else if (isJSDocEntryNameReference(name)) {
77394                 var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */;
77395                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name));
77396             }
77397             if (name.parent.kind === 172 /* TypePredicate */) {
77398                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
77399             }
77400             // Do we want to return undefined here?
77401             return undefined;
77402         }
77403         function getSymbolAtLocation(node, ignoreErrors) {
77404             if (node.kind === 297 /* SourceFile */) {
77405                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
77406             }
77407             var parent = node.parent;
77408             var grandParent = parent.parent;
77409             if (node.flags & 16777216 /* InWithStatement */) {
77410                 // We cannot answer semantic questions within a with block, do not proceed any further
77411                 return undefined;
77412             }
77413             if (isDeclarationNameOrImportPropertyName(node)) {
77414                 // This is a declaration, call getSymbolOfNode
77415                 var parentSymbol = getSymbolOfNode(parent);
77416                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
77417                     ? getImmediateAliasedSymbol(parentSymbol)
77418                     : parentSymbol;
77419             }
77420             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
77421                 return getSymbolOfNode(parent.parent);
77422             }
77423             if (node.kind === 78 /* Identifier */) {
77424                 if (isInRightSideOfImportOrExportAssignment(node)) {
77425                     return getSymbolOfNameOrPropertyAccessExpression(node);
77426                 }
77427                 else if (parent.kind === 198 /* BindingElement */ &&
77428                     grandParent.kind === 196 /* ObjectBindingPattern */ &&
77429                     node === parent.propertyName) {
77430                     var typeOfPattern = getTypeOfNode(grandParent);
77431                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
77432                     if (propertyDeclaration) {
77433                         return propertyDeclaration;
77434                     }
77435                 }
77436             }
77437             switch (node.kind) {
77438                 case 78 /* Identifier */:
77439                 case 79 /* PrivateIdentifier */:
77440                 case 201 /* PropertyAccessExpression */:
77441                 case 157 /* QualifiedName */:
77442                     return getSymbolOfNameOrPropertyAccessExpression(node);
77443                 case 107 /* ThisKeyword */:
77444                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
77445                     if (ts.isFunctionLike(container)) {
77446                         var sig = getSignatureFromDeclaration(container);
77447                         if (sig.thisParameter) {
77448                             return sig.thisParameter;
77449                         }
77450                     }
77451                     if (ts.isInExpressionContext(node)) {
77452                         return checkExpression(node).symbol;
77453                     }
77454                 // falls through
77455                 case 187 /* ThisType */:
77456                     return getTypeFromThisTypeNode(node).symbol;
77457                 case 105 /* SuperKeyword */:
77458                     return checkExpression(node).symbol;
77459                 case 132 /* ConstructorKeyword */:
77460                     // constructor keyword for an overload, should take us to the definition if it exist
77461                     var constructorDeclaration = node.parent;
77462                     if (constructorDeclaration && constructorDeclaration.kind === 166 /* Constructor */) {
77463                         return constructorDeclaration.parent.symbol;
77464                     }
77465                     return undefined;
77466                 case 10 /* StringLiteral */:
77467                 case 14 /* NoSubstitutionTemplateLiteral */:
77468                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
77469                     // 2). External module name in an import declaration
77470                     // 3). Dynamic import call or require in javascript
77471                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
77472                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
77473                         ((node.parent.kind === 261 /* ImportDeclaration */ || node.parent.kind === 267 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
77474                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
77475                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
77476                         return resolveExternalModuleName(node, node, ignoreErrors);
77477                     }
77478                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
77479                         return getSymbolOfNode(parent);
77480                     }
77481                 // falls through
77482                 case 8 /* NumericLiteral */:
77483                     // index access
77484                     var objectType = ts.isElementAccessExpression(parent)
77485                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
77486                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
77487                             ? getTypeFromTypeNode(grandParent.objectType)
77488                             : undefined;
77489                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
77490                 case 87 /* DefaultKeyword */:
77491                 case 97 /* FunctionKeyword */:
77492                 case 38 /* EqualsGreaterThanToken */:
77493                 case 83 /* ClassKeyword */:
77494                     return getSymbolOfNode(node.parent);
77495                 case 195 /* ImportType */:
77496                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
77497                 case 92 /* ExportKeyword */:
77498                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
77499                 default:
77500                     return undefined;
77501             }
77502         }
77503         function getShorthandAssignmentValueSymbol(location) {
77504             if (location && location.kind === 289 /* ShorthandPropertyAssignment */) {
77505                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
77506             }
77507             return undefined;
77508         }
77509         /** Returns the target of an export specifier without following aliases */
77510         function getExportSpecifierLocalTargetSymbol(node) {
77511             if (ts.isExportSpecifier(node)) {
77512                 return node.parent.parent.moduleSpecifier ?
77513                     getExternalModuleMember(node.parent.parent, node) :
77514                     resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
77515             }
77516             else {
77517                 return resolveEntityName(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
77518             }
77519         }
77520         function getTypeOfNode(node) {
77521             if (ts.isSourceFile(node) && !ts.isExternalModule(node)) {
77522                 return errorType;
77523             }
77524             if (node.flags & 16777216 /* InWithStatement */) {
77525                 // We cannot answer semantic questions within a with block, do not proceed any further
77526                 return errorType;
77527             }
77528             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
77529             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
77530             if (ts.isPartOfTypeNode(node)) {
77531                 var typeFromTypeNode = getTypeFromTypeNode(node);
77532                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
77533             }
77534             if (ts.isExpressionNode(node)) {
77535                 return getRegularTypeOfExpression(node);
77536             }
77537             if (classType && !classDecl.isImplements) {
77538                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
77539                 // extends clause of a class. We handle that case here.
77540                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
77541                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
77542             }
77543             if (isTypeDeclaration(node)) {
77544                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
77545                 var symbol = getSymbolOfNode(node);
77546                 return getDeclaredTypeOfSymbol(symbol);
77547             }
77548             if (isTypeDeclarationName(node)) {
77549                 var symbol = getSymbolAtLocation(node);
77550                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
77551             }
77552             if (ts.isDeclaration(node)) {
77553                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
77554                 var symbol = getSymbolOfNode(node);
77555                 return getTypeOfSymbol(symbol);
77556             }
77557             if (isDeclarationNameOrImportPropertyName(node)) {
77558                 var symbol = getSymbolAtLocation(node);
77559                 if (symbol) {
77560                     return getTypeOfSymbol(symbol);
77561                 }
77562                 return errorType;
77563             }
77564             if (ts.isBindingPattern(node)) {
77565                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
77566             }
77567             if (isInRightSideOfImportOrExportAssignment(node)) {
77568                 var symbol = getSymbolAtLocation(node);
77569                 if (symbol) {
77570                     var declaredType = getDeclaredTypeOfSymbol(symbol);
77571                     return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
77572                 }
77573             }
77574             return errorType;
77575         }
77576         // Gets the type of object literal or array literal of destructuring assignment.
77577         // { a } from
77578         //     for ( { a } of elems) {
77579         //     }
77580         // [ a ] from
77581         //     [a] = [ some array ...]
77582         function getTypeOfAssignmentPattern(expr) {
77583             ts.Debug.assert(expr.kind === 200 /* ObjectLiteralExpression */ || expr.kind === 199 /* ArrayLiteralExpression */);
77584             // If this is from "for of"
77585             //     for ( { a } of elems) {
77586             //     }
77587             if (expr.parent.kind === 239 /* ForOfStatement */) {
77588                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
77589                 return checkDestructuringAssignment(expr, iteratedType || errorType);
77590             }
77591             // If this is from "for" initializer
77592             //     for ({a } = elems[0];.....) { }
77593             if (expr.parent.kind === 216 /* BinaryExpression */) {
77594                 var iteratedType = getTypeOfExpression(expr.parent.right);
77595                 return checkDestructuringAssignment(expr, iteratedType || errorType);
77596             }
77597             // If this is from nested object binding pattern
77598             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
77599             if (expr.parent.kind === 288 /* PropertyAssignment */) {
77600                 var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
77601                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType;
77602                 var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent);
77603                 return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex);
77604             }
77605             // Array literal assignment - array destructuring pattern
77606             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
77607             //    [{ property1: p1, property2 }] = elems;
77608             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
77609             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
77610             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
77611         }
77612         // Gets the property symbol corresponding to the property in destructuring assignment
77613         // 'property1' from
77614         //     for ( { property1: a } of elems) {
77615         //     }
77616         // 'property1' at location 'a' from:
77617         //     [a] = [ property1, property2 ]
77618         function getPropertySymbolOfDestructuringAssignment(location) {
77619             // Get the type of the object or array literal and then look for property of given name in the type
77620             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
77621             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
77622         }
77623         function getRegularTypeOfExpression(expr) {
77624             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
77625                 expr = expr.parent;
77626             }
77627             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
77628         }
77629         /**
77630          * Gets either the static or instance type of a class element, based on
77631          * whether the element is declared as "static".
77632          */
77633         function getParentTypeOfClassElement(node) {
77634             var classSymbol = getSymbolOfNode(node.parent);
77635             return ts.hasSyntacticModifier(node, 32 /* Static */)
77636                 ? getTypeOfSymbol(classSymbol)
77637                 : getDeclaredTypeOfSymbol(classSymbol);
77638         }
77639         function getClassElementPropertyKeyType(element) {
77640             var name = element.name;
77641             switch (name.kind) {
77642                 case 78 /* Identifier */:
77643                     return getLiteralType(ts.idText(name));
77644                 case 8 /* NumericLiteral */:
77645                 case 10 /* StringLiteral */:
77646                     return getLiteralType(name.text);
77647                 case 158 /* ComputedPropertyName */:
77648                     var nameType = checkComputedPropertyName(name);
77649                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
77650                 default:
77651                     return ts.Debug.fail("Unsupported property name.");
77652             }
77653         }
77654         // Return the list of properties of the given type, augmented with properties from Function
77655         // if the type has call or construct signatures
77656         function getAugmentedPropertiesOfType(type) {
77657             type = getApparentType(type);
77658             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
77659             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
77660                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
77661                     undefined;
77662             if (functionType) {
77663                 ts.forEach(getPropertiesOfType(functionType), function (p) {
77664                     if (!propsByName.has(p.escapedName)) {
77665                         propsByName.set(p.escapedName, p);
77666                     }
77667                 });
77668             }
77669             return getNamedMembers(propsByName);
77670         }
77671         function typeHasCallOrConstructSignatures(type) {
77672             return ts.typeHasCallOrConstructSignatures(type, checker);
77673         }
77674         function getRootSymbols(symbol) {
77675             var roots = getImmediateRootSymbols(symbol);
77676             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
77677         }
77678         function getImmediateRootSymbols(symbol) {
77679             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
77680                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
77681             }
77682             else if (symbol.flags & 33554432 /* Transient */) {
77683                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
77684                 return leftSpread ? [leftSpread, rightSpread]
77685                     : syntheticOrigin ? [syntheticOrigin]
77686                         : ts.singleElementArray(tryGetAliasTarget(symbol));
77687             }
77688             return undefined;
77689         }
77690         function tryGetAliasTarget(symbol) {
77691             var target;
77692             var next = symbol;
77693             while (next = getSymbolLinks(next).target) {
77694                 target = next;
77695             }
77696             return target;
77697         }
77698         // Emitter support
77699         function isArgumentsLocalBinding(nodeIn) {
77700             // Note: does not handle isShorthandPropertyAssignment (and probably a few more)
77701             if (ts.isGeneratedIdentifier(nodeIn))
77702                 return false;
77703             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
77704             if (!node)
77705                 return false;
77706             var parent = node.parent;
77707             if (!parent)
77708                 return false;
77709             var isPropertyName = ((ts.isPropertyAccessExpression(parent)
77710                 || ts.isPropertyAssignment(parent))
77711                 && parent.name === node);
77712             return !isPropertyName && getReferencedValueSymbol(node) === argumentsSymbol;
77713         }
77714         function moduleExportsSomeValue(moduleReferenceExpression) {
77715             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
77716             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
77717                 // If the module is not found or is shorthand, assume that it may export a value.
77718                 return true;
77719             }
77720             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
77721             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
77722             // otherwise it will return moduleSymbol itself
77723             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
77724             var symbolLinks = getSymbolLinks(moduleSymbol);
77725             if (symbolLinks.exportsSomeValue === undefined) {
77726                 // for export assignments - check if resolved symbol for RHS is itself a value
77727                 // otherwise - check if at least one export is value
77728                 symbolLinks.exportsSomeValue = hasExportAssignment
77729                     ? !!(moduleSymbol.flags & 111551 /* Value */)
77730                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
77731             }
77732             return symbolLinks.exportsSomeValue;
77733             function isValue(s) {
77734                 s = resolveSymbol(s);
77735                 return s && !!(s.flags & 111551 /* Value */);
77736             }
77737         }
77738         function isNameOfModuleOrEnumDeclaration(node) {
77739             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
77740         }
77741         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
77742         // node of the exported entity's container. Otherwise, return undefined.
77743         function getReferencedExportContainer(nodeIn, prefixLocals) {
77744             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
77745             if (node) {
77746                 // When resolving the export container for the name of a module or enum
77747                 // declaration, we need to start resolution at the declaration's container.
77748                 // Otherwise, we could incorrectly resolve the export container as the
77749                 // declaration if it contains an exported member with the same name.
77750                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
77751                 if (symbol) {
77752                     if (symbol.flags & 1048576 /* ExportValue */) {
77753                         // If we reference an exported entity within the same module declaration, then whether
77754                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
77755                         // kinds that we do NOT prefix.
77756                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
77757                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
77758                             return undefined;
77759                         }
77760                         symbol = exportSymbol;
77761                     }
77762                     var parentSymbol_1 = getParentOfSymbol(symbol);
77763                     if (parentSymbol_1) {
77764                         if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 297 /* SourceFile */) {
77765                             var symbolFile = parentSymbol_1.valueDeclaration;
77766                             var referenceFile = ts.getSourceFileOfNode(node);
77767                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
77768                             var symbolIsUmdExport = symbolFile !== referenceFile;
77769                             return symbolIsUmdExport ? undefined : symbolFile;
77770                         }
77771                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
77772                     }
77773                 }
77774             }
77775         }
77776         // When resolved as an expression identifier, if the given node references an import, return the declaration of
77777         // that import. Otherwise, return undefined.
77778         function getReferencedImportDeclaration(nodeIn) {
77779             if (nodeIn.generatedImportReference) {
77780                 return nodeIn.generatedImportReference;
77781             }
77782             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
77783             if (node) {
77784                 var symbol = getReferencedValueSymbol(node);
77785                 // We should only get the declaration of an alias if there isn't a local value
77786                 // declaration for the symbol
77787                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
77788                     return getDeclarationOfAliasSymbol(symbol);
77789                 }
77790             }
77791             return undefined;
77792         }
77793         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
77794             return ts.isBindingElement(symbol.valueDeclaration)
77795                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 287 /* CatchClause */;
77796         }
77797         function isSymbolOfDeclarationWithCollidingName(symbol) {
77798             if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
77799                 var links = getSymbolLinks(symbol);
77800                 if (links.isDeclarationWithCollidingName === undefined) {
77801                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
77802                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
77803                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
77804                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
77805                             // redeclaration - always should be renamed
77806                             links.isDeclarationWithCollidingName = true;
77807                         }
77808                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
77809                             // binding is captured in the function
77810                             // should be renamed if:
77811                             // - binding is not top level - top level bindings never collide with anything
77812                             // AND
77813                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
77814                             //     let a, b
77815                             //     { let x = 1; a = () => x; }
77816                             //     { let x = 100; b = () => x; }
77817                             //     console.log(a()); // should print '1'
77818                             //     console.log(b()); // should print '100'
77819                             //     OR
77820                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
77821                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
77822                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
77823                             //       they will not collide with anything
77824                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
77825                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
77826                             var inLoopBodyBlock = container.kind === 230 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
77827                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
77828                         }
77829                         else {
77830                             links.isDeclarationWithCollidingName = false;
77831                         }
77832                     }
77833                 }
77834                 return links.isDeclarationWithCollidingName;
77835             }
77836             return false;
77837         }
77838         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
77839         // a name that either hides an existing name or might hide it when compiled downlevel,
77840         // return the declaration of that entity. Otherwise, return undefined.
77841         function getReferencedDeclarationWithCollidingName(nodeIn) {
77842             if (!ts.isGeneratedIdentifier(nodeIn)) {
77843                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
77844                 if (node) {
77845                     var symbol = getReferencedValueSymbol(node);
77846                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
77847                         return symbol.valueDeclaration;
77848                     }
77849                 }
77850             }
77851             return undefined;
77852         }
77853         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
77854         // existing name or might hide a name when compiled downlevel
77855         function isDeclarationWithCollidingName(nodeIn) {
77856             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
77857             if (node) {
77858                 var symbol = getSymbolOfNode(node);
77859                 if (symbol) {
77860                     return isSymbolOfDeclarationWithCollidingName(symbol);
77861                 }
77862             }
77863             return false;
77864         }
77865         function isValueAliasDeclaration(node) {
77866             switch (node.kind) {
77867                 case 260 /* ImportEqualsDeclaration */:
77868                     return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
77869                 case 262 /* ImportClause */:
77870                 case 263 /* NamespaceImport */:
77871                 case 265 /* ImportSpecifier */:
77872                 case 270 /* ExportSpecifier */:
77873                     var symbol = getSymbolOfNode(node) || unknownSymbol;
77874                     return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
77875                 case 267 /* ExportDeclaration */:
77876                     var exportClause = node.exportClause;
77877                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
77878                         ts.some(exportClause.elements, isValueAliasDeclaration));
77879                 case 266 /* ExportAssignment */:
77880                     return node.expression && node.expression.kind === 78 /* Identifier */ ?
77881                         isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
77882                         true;
77883             }
77884             return false;
77885         }
77886         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
77887             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
77888             if (node === undefined || node.parent.kind !== 297 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
77889                 // parent is not source file or it is not reference to internal module
77890                 return false;
77891             }
77892             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
77893             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
77894         }
77895         function isAliasResolvedToValue(symbol) {
77896             var target = resolveAlias(symbol);
77897             if (target === unknownSymbol) {
77898                 return true;
77899             }
77900             // const enums and modules that contain only const enums are not considered values from the emit perspective
77901             // unless 'preserveConstEnums' option is set to true
77902             return !!(target.flags & 111551 /* Value */) &&
77903                 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
77904         }
77905         function isConstEnumOrConstEnumOnlyModule(s) {
77906             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
77907         }
77908         function isReferencedAliasDeclaration(node, checkChildren) {
77909             if (isAliasSymbolDeclaration(node)) {
77910                 var symbol = getSymbolOfNode(node);
77911                 if (symbol && getSymbolLinks(symbol).referenced) {
77912                     return true;
77913                 }
77914                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
77915                 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ &&
77916                     target.flags & 111551 /* Value */ &&
77917                     (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
77918                     // An `export import ... =` of a value symbol is always considered referenced
77919                     return true;
77920                 }
77921             }
77922             if (checkChildren) {
77923                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
77924             }
77925             return false;
77926         }
77927         function isImplementationOfOverload(node) {
77928             if (ts.nodeIsPresent(node.body)) {
77929                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
77930                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
77931                 var symbol = getSymbolOfNode(node);
77932                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
77933                 // If this function body corresponds to function with multiple signature, it is implementation of overload
77934                 // e.g.: function foo(a: string): string;
77935                 //       function foo(a: number): number;
77936                 //       function foo(a: any) { // This is implementation of the overloads
77937                 //           return a;
77938                 //       }
77939                 return signaturesOfSymbol.length > 1 ||
77940                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
77941                     // e.g.: function foo(a: string): string;
77942                     //       function foo(a: any) { // This is implementation of the overloads
77943                     //           return a;
77944                     //       }
77945                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
77946             }
77947             return false;
77948         }
77949         function isRequiredInitializedParameter(parameter) {
77950             return !!strictNullChecks &&
77951                 !isOptionalParameter(parameter) &&
77952                 !ts.isJSDocParameterTag(parameter) &&
77953                 !!parameter.initializer &&
77954                 !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */);
77955         }
77956         function isOptionalUninitializedParameterProperty(parameter) {
77957             return strictNullChecks &&
77958                 isOptionalParameter(parameter) &&
77959                 !parameter.initializer &&
77960                 ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */);
77961         }
77962         function isOptionalUninitializedParameter(parameter) {
77963             return !!strictNullChecks &&
77964                 isOptionalParameter(parameter) &&
77965                 !parameter.initializer;
77966         }
77967         function isExpandoFunctionDeclaration(node) {
77968             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
77969             if (!declaration) {
77970                 return false;
77971             }
77972             var symbol = getSymbolOfNode(declaration);
77973             if (!symbol || !(symbol.flags & 16 /* Function */)) {
77974                 return false;
77975             }
77976             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
77977         }
77978         function getPropertiesOfContainerFunction(node) {
77979             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
77980             if (!declaration) {
77981                 return ts.emptyArray;
77982             }
77983             var symbol = getSymbolOfNode(declaration);
77984             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
77985         }
77986         function getNodeCheckFlags(node) {
77987             return getNodeLinks(node).flags || 0;
77988         }
77989         function getEnumMemberValue(node) {
77990             computeEnumMemberValues(node.parent);
77991             return getNodeLinks(node).enumMemberValue;
77992         }
77993         function canHaveConstantValue(node) {
77994             switch (node.kind) {
77995                 case 291 /* EnumMember */:
77996                 case 201 /* PropertyAccessExpression */:
77997                 case 202 /* ElementAccessExpression */:
77998                     return true;
77999             }
78000             return false;
78001         }
78002         function getConstantValue(node) {
78003             if (node.kind === 291 /* EnumMember */) {
78004                 return getEnumMemberValue(node);
78005             }
78006             var symbol = getNodeLinks(node).resolvedSymbol;
78007             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
78008                 // inline property\index accesses only for const enums
78009                 var member = symbol.valueDeclaration;
78010                 if (ts.isEnumConst(member.parent)) {
78011                     return getEnumMemberValue(member);
78012                 }
78013             }
78014             return undefined;
78015         }
78016         function isFunctionType(type) {
78017             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
78018         }
78019         function getTypeReferenceSerializationKind(typeNameIn, location) {
78020             var _a;
78021             // ensure both `typeName` and `location` are parse tree nodes.
78022             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
78023             if (!typeName)
78024                 return ts.TypeReferenceSerializationKind.Unknown;
78025             if (location) {
78026                 location = ts.getParseTreeNode(location);
78027                 if (!location)
78028                     return ts.TypeReferenceSerializationKind.Unknown;
78029             }
78030             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
78031             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, location);
78032             var isTypeOnly = ((_a = valueSymbol === null || valueSymbol === void 0 ? void 0 : valueSymbol.declarations) === null || _a === void 0 ? void 0 : _a.every(ts.isTypeOnlyImportOrExportDeclaration)) || false;
78033             var resolvedSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol;
78034             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
78035             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
78036             if (resolvedSymbol && resolvedSymbol === typeSymbol) {
78037                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
78038                 if (globalPromiseSymbol && resolvedSymbol === globalPromiseSymbol) {
78039                     return ts.TypeReferenceSerializationKind.Promise;
78040                 }
78041                 var constructorType = getTypeOfSymbol(resolvedSymbol);
78042                 if (constructorType && isConstructorType(constructorType)) {
78043                     return isTypeOnly ? ts.TypeReferenceSerializationKind.TypeWithCallSignature : ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
78044                 }
78045             }
78046             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
78047             if (!typeSymbol) {
78048                 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
78049             }
78050             var type = getDeclaredTypeOfSymbol(typeSymbol);
78051             if (type === errorType) {
78052                 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
78053             }
78054             else if (type.flags & 3 /* AnyOrUnknown */) {
78055                 return ts.TypeReferenceSerializationKind.ObjectType;
78056             }
78057             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
78058                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
78059             }
78060             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
78061                 return ts.TypeReferenceSerializationKind.BooleanType;
78062             }
78063             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
78064                 return ts.TypeReferenceSerializationKind.NumberLikeType;
78065             }
78066             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
78067                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
78068             }
78069             else if (isTypeAssignableToKind(type, 402653316 /* StringLike */)) {
78070                 return ts.TypeReferenceSerializationKind.StringLikeType;
78071             }
78072             else if (isTupleType(type)) {
78073                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
78074             }
78075             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
78076                 return ts.TypeReferenceSerializationKind.ESSymbolType;
78077             }
78078             else if (isFunctionType(type)) {
78079                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
78080             }
78081             else if (isArrayType(type)) {
78082                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
78083             }
78084             else {
78085                 return ts.TypeReferenceSerializationKind.ObjectType;
78086             }
78087         }
78088         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
78089             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
78090             if (!declaration) {
78091                 return ts.factory.createToken(128 /* AnyKeyword */);
78092             }
78093             // Get type of the symbol if this is the valid symbol otherwise get type at location
78094             var symbol = getSymbolOfNode(declaration);
78095             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
78096                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
78097                 : errorType;
78098             if (type.flags & 8192 /* UniqueESSymbol */ &&
78099                 type.symbol === symbol) {
78100                 flags |= 1048576 /* AllowUniqueESSymbolType */;
78101             }
78102             if (addUndefined) {
78103                 type = getOptionalType(type);
78104             }
78105             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
78106         }
78107         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
78108             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
78109             if (!signatureDeclaration) {
78110                 return ts.factory.createToken(128 /* AnyKeyword */);
78111             }
78112             var signature = getSignatureFromDeclaration(signatureDeclaration);
78113             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
78114         }
78115         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
78116             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
78117             if (!expr) {
78118                 return ts.factory.createToken(128 /* AnyKeyword */);
78119             }
78120             var type = getWidenedType(getRegularTypeOfExpression(expr));
78121             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
78122         }
78123         function hasGlobalName(name) {
78124             return globals.has(ts.escapeLeadingUnderscores(name));
78125         }
78126         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
78127             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
78128             if (resolvedSymbol) {
78129                 return resolvedSymbol;
78130             }
78131             var location = reference;
78132             if (startInDeclarationContainer) {
78133                 // When resolving the name of a declaration as a value, we need to start resolution
78134                 // at a point outside of the declaration.
78135                 var parent = reference.parent;
78136                 if (ts.isDeclaration(parent) && reference === parent.name) {
78137                     location = getDeclarationContainer(parent);
78138                 }
78139             }
78140             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
78141         }
78142         function getReferencedValueDeclaration(referenceIn) {
78143             if (!ts.isGeneratedIdentifier(referenceIn)) {
78144                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
78145                 if (reference) {
78146                     var symbol = getReferencedValueSymbol(reference);
78147                     if (symbol) {
78148                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
78149                     }
78150                 }
78151             }
78152             return undefined;
78153         }
78154         function isLiteralConstDeclaration(node) {
78155             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
78156                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
78157             }
78158             return false;
78159         }
78160         function literalTypeToNode(type, enclosing, tracker) {
78161             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
78162                 : type === trueType ? ts.factory.createTrue() : type === falseType && ts.factory.createFalse();
78163             if (enumResult)
78164                 return enumResult;
78165             var literalValue = type.value;
78166             return typeof literalValue === "object" ? ts.factory.createBigIntLiteral(literalValue) :
78167                 typeof literalValue === "number" ? ts.factory.createNumericLiteral(literalValue) :
78168                     ts.factory.createStringLiteral(literalValue);
78169         }
78170         function createLiteralConstValue(node, tracker) {
78171             var type = getTypeOfSymbol(getSymbolOfNode(node));
78172             return literalTypeToNode(type, node, tracker);
78173         }
78174         function getJsxFactoryEntity(location) {
78175             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
78176         }
78177         function getJsxFragmentFactoryEntity(location) {
78178             if (location) {
78179                 var file = ts.getSourceFileOfNode(location);
78180                 if (file) {
78181                     if (file.localJsxFragmentFactory) {
78182                         return file.localJsxFragmentFactory;
78183                     }
78184                     var jsxFragPragmas = file.pragmas.get("jsxfrag");
78185                     var jsxFragPragma = ts.isArray(jsxFragPragmas) ? jsxFragPragmas[0] : jsxFragPragmas;
78186                     if (jsxFragPragma) {
78187                         file.localJsxFragmentFactory = ts.parseIsolatedEntityName(jsxFragPragma.arguments.factory, languageVersion);
78188                         return file.localJsxFragmentFactory;
78189                     }
78190                 }
78191             }
78192             if (compilerOptions.jsxFragmentFactory) {
78193                 return ts.parseIsolatedEntityName(compilerOptions.jsxFragmentFactory, languageVersion);
78194             }
78195         }
78196         function createResolver() {
78197             // this variable and functions that use it are deliberately moved here from the outer scope
78198             // to avoid scope pollution
78199             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
78200             var fileToDirective;
78201             if (resolvedTypeReferenceDirectives) {
78202                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
78203                 fileToDirective = new ts.Map();
78204                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
78205                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
78206                         return;
78207                     }
78208                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
78209                     if (file) {
78210                         // Add the transitive closure of path references loaded by this file (as long as they are not)
78211                         // part of an existing type reference.
78212                         addReferencedFilesToTypeDirective(file, key);
78213                     }
78214                 });
78215             }
78216             return {
78217                 getReferencedExportContainer: getReferencedExportContainer,
78218                 getReferencedImportDeclaration: getReferencedImportDeclaration,
78219                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
78220                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
78221                 isValueAliasDeclaration: function (nodeIn) {
78222                     var node = ts.getParseTreeNode(nodeIn);
78223                     // Synthesized nodes are always treated like values.
78224                     return node ? isValueAliasDeclaration(node) : true;
78225                 },
78226                 hasGlobalName: hasGlobalName,
78227                 isReferencedAliasDeclaration: function (nodeIn, checkChildren) {
78228                     var node = ts.getParseTreeNode(nodeIn);
78229                     // Synthesized nodes are always treated as referenced.
78230                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
78231                 },
78232                 getNodeCheckFlags: function (nodeIn) {
78233                     var node = ts.getParseTreeNode(nodeIn);
78234                     return node ? getNodeCheckFlags(node) : 0;
78235                 },
78236                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
78237                 isDeclarationVisible: isDeclarationVisible,
78238                 isImplementationOfOverload: isImplementationOfOverload,
78239                 isRequiredInitializedParameter: isRequiredInitializedParameter,
78240                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
78241                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
78242                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
78243                 createTypeOfDeclaration: createTypeOfDeclaration,
78244                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
78245                 createTypeOfExpression: createTypeOfExpression,
78246                 createLiteralConstValue: createLiteralConstValue,
78247                 isSymbolAccessible: isSymbolAccessible,
78248                 isEntityNameVisible: isEntityNameVisible,
78249                 getConstantValue: function (nodeIn) {
78250                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
78251                     return node ? getConstantValue(node) : undefined;
78252                 },
78253                 collectLinkedAliases: collectLinkedAliases,
78254                 getReferencedValueDeclaration: getReferencedValueDeclaration,
78255                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
78256                 isOptionalParameter: isOptionalParameter,
78257                 moduleExportsSomeValue: moduleExportsSomeValue,
78258                 isArgumentsLocalBinding: isArgumentsLocalBinding,
78259                 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
78260                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
78261                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
78262                 isLiteralConstDeclaration: isLiteralConstDeclaration,
78263                 isLateBound: function (nodeIn) {
78264                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
78265                     var symbol = node && getSymbolOfNode(node);
78266                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
78267                 },
78268                 getJsxFactoryEntity: getJsxFactoryEntity,
78269                 getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity,
78270                 getAllAccessorDeclarations: function (accessor) {
78271                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
78272                     var otherKind = accessor.kind === 168 /* SetAccessor */ ? 167 /* GetAccessor */ : 168 /* SetAccessor */;
78273                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
78274                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
78275                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
78276                     var setAccessor = accessor.kind === 168 /* SetAccessor */ ? accessor : otherAccessor;
78277                     var getAccessor = accessor.kind === 167 /* GetAccessor */ ? accessor : otherAccessor;
78278                     return {
78279                         firstAccessor: firstAccessor,
78280                         secondAccessor: secondAccessor,
78281                         setAccessor: setAccessor,
78282                         getAccessor: getAccessor
78283                     };
78284                 },
78285                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
78286                 isBindingCapturedByNode: function (node, decl) {
78287                     var parseNode = ts.getParseTreeNode(node);
78288                     var parseDecl = ts.getParseTreeNode(decl);
78289                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
78290                 },
78291                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
78292                     var n = ts.getParseTreeNode(node);
78293                     ts.Debug.assert(n && n.kind === 297 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
78294                     var sym = getSymbolOfNode(node);
78295                     if (!sym) {
78296                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
78297                     }
78298                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
78299                 },
78300                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
78301             };
78302             function isImportRequiredByAugmentation(node) {
78303                 var file = ts.getSourceFileOfNode(node);
78304                 if (!file.symbol)
78305                     return false;
78306                 var importTarget = getExternalModuleFileFromDeclaration(node);
78307                 if (!importTarget)
78308                     return false;
78309                 if (importTarget === file)
78310                     return false;
78311                 var exports = getExportsOfModule(file.symbol);
78312                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
78313                     var s = _a[_i];
78314                     if (s.mergeId) {
78315                         var merged = getMergedSymbol(s);
78316                         for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
78317                             var d = _c[_b];
78318                             var declFile = ts.getSourceFileOfNode(d);
78319                             if (declFile === importTarget) {
78320                                 return true;
78321                             }
78322                         }
78323                     }
78324                 }
78325                 return false;
78326             }
78327             function isInHeritageClause(node) {
78328                 return node.parent && node.parent.kind === 223 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 286 /* HeritageClause */;
78329             }
78330             // defined here to avoid outer scope pollution
78331             function getTypeReferenceDirectivesForEntityName(node) {
78332                 // program does not have any files with type reference directives - bail out
78333                 if (!fileToDirective) {
78334                     return undefined;
78335                 }
78336                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
78337                 // qualified names can only be used as types\namespaces
78338                 // identifiers are treated as values only if they appear in type queries
78339                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
78340                 if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 201 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
78341                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
78342                 }
78343                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
78344                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
78345             }
78346             // defined here to avoid outer scope pollution
78347             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
78348                 // program does not have any files with type reference directives - bail out
78349                 if (!fileToDirective) {
78350                     return undefined;
78351                 }
78352                 if (!isSymbolFromTypeDeclarationFile(symbol)) {
78353                     return undefined;
78354                 }
78355                 // check what declarations in the symbol can contribute to the target meaning
78356                 var typeReferenceDirectives;
78357                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
78358                     var decl = _a[_i];
78359                     // check meaning of the local symbol to see if declaration needs to be analyzed further
78360                     if (decl.symbol && decl.symbol.flags & meaning) {
78361                         var file = ts.getSourceFileOfNode(decl);
78362                         var typeReferenceDirective = fileToDirective.get(file.path);
78363                         if (typeReferenceDirective) {
78364                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
78365                         }
78366                         else {
78367                             // found at least one entry that does not originate from type reference directive
78368                             return undefined;
78369                         }
78370                     }
78371                 }
78372                 return typeReferenceDirectives;
78373             }
78374             function isSymbolFromTypeDeclarationFile(symbol) {
78375                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
78376                 if (!symbol.declarations) {
78377                     return false;
78378                 }
78379                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
78380                 // external modules cannot define or contribute to type declaration files
78381                 var current = symbol;
78382                 while (true) {
78383                     var parent = getParentOfSymbol(current);
78384                     if (parent) {
78385                         current = parent;
78386                     }
78387                     else {
78388                         break;
78389                     }
78390                 }
78391                 if (current.valueDeclaration && current.valueDeclaration.kind === 297 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
78392                     return false;
78393                 }
78394                 // check that at least one declaration of top level symbol originates from type declaration file
78395                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
78396                     var decl = _a[_i];
78397                     var file = ts.getSourceFileOfNode(decl);
78398                     if (fileToDirective.has(file.path)) {
78399                         return true;
78400                     }
78401                 }
78402                 return false;
78403             }
78404             function addReferencedFilesToTypeDirective(file, key) {
78405                 if (fileToDirective.has(file.path))
78406                     return;
78407                 fileToDirective.set(file.path, key);
78408                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
78409                     var fileName = _a[_i].fileName;
78410                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.fileName);
78411                     var referencedFile = host.getSourceFile(resolvedFile);
78412                     if (referencedFile) {
78413                         addReferencedFilesToTypeDirective(referencedFile, key);
78414                     }
78415                 }
78416             }
78417         }
78418         function getExternalModuleFileFromDeclaration(declaration) {
78419             var specifier = declaration.kind === 256 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
78420             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
78421             if (!moduleSymbol) {
78422                 return undefined;
78423             }
78424             return ts.getDeclarationOfKind(moduleSymbol, 297 /* SourceFile */);
78425         }
78426         function initializeTypeChecker() {
78427             // Bind all source files and propagate errors
78428             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
78429                 var file = _a[_i];
78430                 ts.bindSourceFile(file, compilerOptions);
78431             }
78432             amalgamatedDuplicates = new ts.Map();
78433             // Initialize global symbol table
78434             var augmentations;
78435             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
78436                 var file = _c[_b];
78437                 if (file.redirectInfo) {
78438                     continue;
78439                 }
78440                 if (!ts.isExternalOrCommonJsModule(file)) {
78441                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
78442                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
78443                     var fileGlobalThisSymbol = file.locals.get("globalThis");
78444                     if (fileGlobalThisSymbol) {
78445                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
78446                             var declaration = _e[_d];
78447                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
78448                         }
78449                     }
78450                     mergeSymbolTable(globals, file.locals);
78451                 }
78452                 if (file.jsGlobalAugmentations) {
78453                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
78454                 }
78455                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
78456                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
78457                 }
78458                 if (file.moduleAugmentations.length) {
78459                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
78460                 }
78461                 if (file.symbol && file.symbol.globalExports) {
78462                     // Merge in UMD exports with first-in-wins semantics (see #9771)
78463                     var source = file.symbol.globalExports;
78464                     source.forEach(function (sourceSymbol, id) {
78465                         if (!globals.has(id)) {
78466                             globals.set(id, sourceSymbol);
78467                         }
78468                     });
78469                 }
78470             }
78471             // We do global augmentations separately from module augmentations (and before creating global types) because they
78472             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
78473             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
78474             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
78475             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
78476             //       did module augmentations prior to finalizing the global types.
78477             if (augmentations) {
78478                 // merge _global_ module augmentations.
78479                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
78480                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
78481                     var list = augmentations_1[_f];
78482                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
78483                         var augmentation = list_1[_g];
78484                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
78485                             continue;
78486                         mergeModuleAugmentation(augmentation);
78487                     }
78488                 }
78489             }
78490             // Setup global builtins
78491             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
78492             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
78493             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
78494             getSymbolLinks(unknownSymbol).type = errorType;
78495             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
78496             // Initialize special types
78497             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
78498             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
78499             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
78500             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
78501             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
78502             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
78503             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
78504             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
78505             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
78506             anyArrayType = createArrayType(anyType);
78507             autoArrayType = createArrayType(autoType);
78508             if (autoArrayType === emptyObjectType) {
78509                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
78510                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
78511             }
78512             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
78513             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
78514             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
78515             if (augmentations) {
78516                 // merge _nonglobal_ module augmentations.
78517                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
78518                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
78519                     var list = augmentations_2[_h];
78520                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
78521                         var augmentation = list_2[_j];
78522                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
78523                             continue;
78524                         mergeModuleAugmentation(augmentation);
78525                     }
78526                 }
78527             }
78528             amalgamatedDuplicates.forEach(function (_a) {
78529                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
78530                 // If not many things conflict, issue individual errors
78531                 if (conflictingSymbols.size < 8) {
78532                     conflictingSymbols.forEach(function (_a, symbolName) {
78533                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
78534                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
78535                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
78536                             var node = firstFileLocations_1[_i];
78537                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
78538                         }
78539                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
78540                             var node = secondFileLocations_1[_b];
78541                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
78542                         }
78543                     });
78544                 }
78545                 else {
78546                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
78547                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
78548                     diagnostics.add(ts.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)));
78549                     diagnostics.add(ts.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)));
78550                 }
78551             });
78552             amalgamatedDuplicates = undefined;
78553         }
78554         function checkExternalEmitHelpers(location, helpers) {
78555             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
78556                 var sourceFile = ts.getSourceFileOfNode(location);
78557                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
78558                     var helpersModule = resolveHelpersModule(sourceFile, location);
78559                     if (helpersModule !== unknownSymbol) {
78560                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
78561                         for (var helper = 1 /* FirstEmitHelper */; helper <= 4194304 /* LastEmitHelper */; helper <<= 1) {
78562                             if (uncheckedHelpers & helper) {
78563                                 var name = getHelperName(helper);
78564                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
78565                                 if (!symbol) {
78566                                     error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name);
78567                                 }
78568                             }
78569                         }
78570                     }
78571                     requestedExternalEmitHelpers |= helpers;
78572                 }
78573             }
78574         }
78575         function getHelperName(helper) {
78576             switch (helper) {
78577                 case 1 /* Extends */: return "__extends";
78578                 case 2 /* Assign */: return "__assign";
78579                 case 4 /* Rest */: return "__rest";
78580                 case 8 /* Decorate */: return "__decorate";
78581                 case 16 /* Metadata */: return "__metadata";
78582                 case 32 /* Param */: return "__param";
78583                 case 64 /* Awaiter */: return "__awaiter";
78584                 case 128 /* Generator */: return "__generator";
78585                 case 256 /* Values */: return "__values";
78586                 case 512 /* Read */: return "__read";
78587                 case 1024 /* Spread */: return "__spread";
78588                 case 2048 /* SpreadArrays */: return "__spreadArrays";
78589                 case 4096 /* Await */: return "__await";
78590                 case 8192 /* AsyncGenerator */: return "__asyncGenerator";
78591                 case 16384 /* AsyncDelegator */: return "__asyncDelegator";
78592                 case 32768 /* AsyncValues */: return "__asyncValues";
78593                 case 65536 /* ExportStar */: return "__exportStar";
78594                 case 131072 /* ImportStar */: return "__importStar";
78595                 case 262144 /* ImportDefault */: return "__importDefault";
78596                 case 524288 /* MakeTemplateObject */: return "__makeTemplateObject";
78597                 case 1048576 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
78598                 case 2097152 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
78599                 case 4194304 /* CreateBinding */: return "__createBinding";
78600                 default: return ts.Debug.fail("Unrecognized helper");
78601             }
78602         }
78603         function resolveHelpersModule(node, errorNode) {
78604             if (!externalHelpersModule) {
78605                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
78606             }
78607             return externalHelpersModule;
78608         }
78609         // GRAMMAR CHECKING
78610         function checkGrammarDecoratorsAndModifiers(node) {
78611             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
78612         }
78613         function checkGrammarDecorators(node) {
78614             if (!node.decorators) {
78615                 return false;
78616             }
78617             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
78618                 if (node.kind === 165 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
78619                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
78620                 }
78621                 else {
78622                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
78623                 }
78624             }
78625             else if (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */) {
78626                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
78627                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
78628                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
78629                 }
78630             }
78631             return false;
78632         }
78633         function checkGrammarModifiers(node) {
78634             var quickResult = reportObviousModifierErrors(node);
78635             if (quickResult !== undefined) {
78636                 return quickResult;
78637             }
78638             var lastStatic, lastDeclare, lastAsync, lastReadonly;
78639             var flags = 0 /* None */;
78640             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
78641                 var modifier = _a[_i];
78642                 if (modifier.kind !== 142 /* ReadonlyKeyword */) {
78643                     if (node.kind === 162 /* PropertySignature */ || node.kind === 164 /* MethodSignature */) {
78644                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
78645                     }
78646                     if (node.kind === 171 /* IndexSignature */) {
78647                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
78648                     }
78649                 }
78650                 switch (modifier.kind) {
78651                     case 84 /* ConstKeyword */:
78652                         if (node.kind !== 255 /* EnumDeclaration */) {
78653                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84 /* ConstKeyword */));
78654                         }
78655                         break;
78656                     case 122 /* PublicKeyword */:
78657                     case 121 /* ProtectedKeyword */:
78658                     case 120 /* PrivateKeyword */:
78659                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
78660                         if (flags & 28 /* AccessibilityModifier */) {
78661                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
78662                         }
78663                         else if (flags & 32 /* Static */) {
78664                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
78665                         }
78666                         else if (flags & 64 /* Readonly */) {
78667                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
78668                         }
78669                         else if (flags & 256 /* Async */) {
78670                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
78671                         }
78672                         else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
78673                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
78674                         }
78675                         else if (flags & 128 /* Abstract */) {
78676                             if (modifier.kind === 120 /* PrivateKeyword */) {
78677                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
78678                             }
78679                             else {
78680                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
78681                             }
78682                         }
78683                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
78684                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
78685                         }
78686                         flags |= ts.modifierToFlag(modifier.kind);
78687                         break;
78688                     case 123 /* StaticKeyword */:
78689                         if (flags & 32 /* Static */) {
78690                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
78691                         }
78692                         else if (flags & 64 /* Readonly */) {
78693                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
78694                         }
78695                         else if (flags & 256 /* Async */) {
78696                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
78697                         }
78698                         else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
78699                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
78700                         }
78701                         else if (node.kind === 160 /* Parameter */) {
78702                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
78703                         }
78704                         else if (flags & 128 /* Abstract */) {
78705                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
78706                         }
78707                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
78708                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
78709                         }
78710                         flags |= 32 /* Static */;
78711                         lastStatic = modifier;
78712                         break;
78713                     case 142 /* ReadonlyKeyword */:
78714                         if (flags & 64 /* Readonly */) {
78715                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
78716                         }
78717                         else if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */ && node.kind !== 171 /* IndexSignature */ && node.kind !== 160 /* Parameter */) {
78718                             // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
78719                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
78720                         }
78721                         flags |= 64 /* Readonly */;
78722                         lastReadonly = modifier;
78723                         break;
78724                     case 92 /* ExportKeyword */:
78725                         if (flags & 1 /* Export */) {
78726                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
78727                         }
78728                         else if (flags & 2 /* Ambient */) {
78729                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
78730                         }
78731                         else if (flags & 128 /* Abstract */) {
78732                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
78733                         }
78734                         else if (flags & 256 /* Async */) {
78735                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
78736                         }
78737                         else if (ts.isClassLike(node.parent)) {
78738                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export");
78739                         }
78740                         else if (node.kind === 160 /* Parameter */) {
78741                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
78742                         }
78743                         flags |= 1 /* Export */;
78744                         break;
78745                     case 87 /* DefaultKeyword */:
78746                         var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent;
78747                         if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
78748                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
78749                         }
78750                         flags |= 512 /* Default */;
78751                         break;
78752                     case 133 /* DeclareKeyword */:
78753                         if (flags & 2 /* Ambient */) {
78754                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
78755                         }
78756                         else if (flags & 256 /* Async */) {
78757                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
78758                         }
78759                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
78760                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare");
78761                         }
78762                         else if (node.kind === 160 /* Parameter */) {
78763                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
78764                         }
78765                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 257 /* ModuleBlock */) {
78766                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
78767                         }
78768                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
78769                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
78770                         }
78771                         flags |= 2 /* Ambient */;
78772                         lastDeclare = modifier;
78773                         break;
78774                     case 125 /* AbstractKeyword */:
78775                         if (flags & 128 /* Abstract */) {
78776                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
78777                         }
78778                         if (node.kind !== 252 /* ClassDeclaration */) {
78779                             if (node.kind !== 165 /* MethodDeclaration */ &&
78780                                 node.kind !== 163 /* PropertyDeclaration */ &&
78781                                 node.kind !== 167 /* GetAccessor */ &&
78782                                 node.kind !== 168 /* SetAccessor */) {
78783                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
78784                             }
78785                             if (!(node.parent.kind === 252 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) {
78786                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
78787                             }
78788                             if (flags & 32 /* Static */) {
78789                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
78790                             }
78791                             if (flags & 8 /* Private */) {
78792                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
78793                             }
78794                             if (flags & 256 /* Async */ && lastAsync) {
78795                                 return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
78796                             }
78797                         }
78798                         if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) {
78799                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
78800                         }
78801                         flags |= 128 /* Abstract */;
78802                         break;
78803                     case 129 /* AsyncKeyword */:
78804                         if (flags & 256 /* Async */) {
78805                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
78806                         }
78807                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
78808                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
78809                         }
78810                         else if (node.kind === 160 /* Parameter */) {
78811                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
78812                         }
78813                         if (flags & 128 /* Abstract */) {
78814                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
78815                         }
78816                         flags |= 256 /* Async */;
78817                         lastAsync = modifier;
78818                         break;
78819                 }
78820             }
78821             if (node.kind === 166 /* Constructor */) {
78822                 if (flags & 32 /* Static */) {
78823                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
78824                 }
78825                 if (flags & 128 /* Abstract */) {
78826                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
78827                 }
78828                 else if (flags & 256 /* Async */) {
78829                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
78830                 }
78831                 else if (flags & 64 /* Readonly */) {
78832                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
78833                 }
78834                 return false;
78835             }
78836             else if ((node.kind === 261 /* ImportDeclaration */ || node.kind === 260 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
78837                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
78838             }
78839             else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
78840                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
78841             }
78842             else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
78843                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
78844             }
78845             if (flags & 256 /* Async */) {
78846                 return checkGrammarAsyncModifier(node, lastAsync);
78847             }
78848             return false;
78849         }
78850         /**
78851          * true | false: Early return this value from checkGrammarModifiers.
78852          * undefined: Need to do full checking on the modifiers.
78853          */
78854         function reportObviousModifierErrors(node) {
78855             return !node.modifiers
78856                 ? false
78857                 : shouldReportBadModifier(node)
78858                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
78859                     : undefined;
78860         }
78861         function shouldReportBadModifier(node) {
78862             switch (node.kind) {
78863                 case 167 /* GetAccessor */:
78864                 case 168 /* SetAccessor */:
78865                 case 166 /* Constructor */:
78866                 case 163 /* PropertyDeclaration */:
78867                 case 162 /* PropertySignature */:
78868                 case 165 /* MethodDeclaration */:
78869                 case 164 /* MethodSignature */:
78870                 case 171 /* IndexSignature */:
78871                 case 256 /* ModuleDeclaration */:
78872                 case 261 /* ImportDeclaration */:
78873                 case 260 /* ImportEqualsDeclaration */:
78874                 case 267 /* ExportDeclaration */:
78875                 case 266 /* ExportAssignment */:
78876                 case 208 /* FunctionExpression */:
78877                 case 209 /* ArrowFunction */:
78878                 case 160 /* Parameter */:
78879                     return false;
78880                 default:
78881                     if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
78882                         return false;
78883                     }
78884                     switch (node.kind) {
78885                         case 251 /* FunctionDeclaration */:
78886                             return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */);
78887                         case 252 /* ClassDeclaration */:
78888                             return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */);
78889                         case 253 /* InterfaceDeclaration */:
78890                         case 232 /* VariableStatement */:
78891                         case 254 /* TypeAliasDeclaration */:
78892                             return true;
78893                         case 255 /* EnumDeclaration */:
78894                             return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */);
78895                         default:
78896                             ts.Debug.fail();
78897                             return false;
78898                     }
78899             }
78900         }
78901         function nodeHasAnyModifiersExcept(node, allowedModifier) {
78902             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
78903         }
78904         function checkGrammarAsyncModifier(node, asyncModifier) {
78905             switch (node.kind) {
78906                 case 165 /* MethodDeclaration */:
78907                 case 251 /* FunctionDeclaration */:
78908                 case 208 /* FunctionExpression */:
78909                 case 209 /* ArrowFunction */:
78910                     return false;
78911             }
78912             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
78913         }
78914         function checkGrammarForDisallowedTrailingComma(list, diag) {
78915             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
78916             if (list && list.hasTrailingComma) {
78917                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
78918             }
78919             return false;
78920         }
78921         function checkGrammarTypeParameterList(typeParameters, file) {
78922             if (typeParameters && typeParameters.length === 0) {
78923                 var start = typeParameters.pos - "<".length;
78924                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
78925                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
78926             }
78927             return false;
78928         }
78929         function checkGrammarParameterList(parameters) {
78930             var seenOptionalParameter = false;
78931             var parameterCount = parameters.length;
78932             for (var i = 0; i < parameterCount; i++) {
78933                 var parameter = parameters[i];
78934                 if (parameter.dotDotDotToken) {
78935                     if (i !== (parameterCount - 1)) {
78936                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
78937                     }
78938                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
78939                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
78940                     }
78941                     if (parameter.questionToken) {
78942                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
78943                     }
78944                     if (parameter.initializer) {
78945                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
78946                     }
78947                 }
78948                 else if (isOptionalParameter(parameter)) {
78949                     seenOptionalParameter = true;
78950                     if (parameter.questionToken && parameter.initializer) {
78951                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
78952                     }
78953                 }
78954                 else if (seenOptionalParameter && !parameter.initializer) {
78955                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
78956                 }
78957             }
78958         }
78959         function getNonSimpleParameters(parameters) {
78960             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
78961         }
78962         function checkGrammarForUseStrictSimpleParameterList(node) {
78963             if (languageVersion >= 3 /* ES2016 */) {
78964                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
78965                 if (useStrictDirective_1) {
78966                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
78967                     if (ts.length(nonSimpleParameters)) {
78968                         ts.forEach(nonSimpleParameters, function (parameter) {
78969                             ts.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));
78970                         });
78971                         var diagnostics_2 = 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)); });
78972                         ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_2));
78973                         return true;
78974                     }
78975                 }
78976             }
78977             return false;
78978         }
78979         function checkGrammarFunctionLikeDeclaration(node) {
78980             // Prevent cascading error by short-circuit
78981             var file = ts.getSourceFileOfNode(node);
78982             return checkGrammarDecoratorsAndModifiers(node) ||
78983                 checkGrammarTypeParameterList(node.typeParameters, file) ||
78984                 checkGrammarParameterList(node.parameters) ||
78985                 checkGrammarArrowFunction(node, file) ||
78986                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
78987         }
78988         function checkGrammarClassLikeDeclaration(node) {
78989             var file = ts.getSourceFileOfNode(node);
78990             return checkGrammarClassDeclarationHeritageClauses(node) ||
78991                 checkGrammarTypeParameterList(node.typeParameters, file);
78992         }
78993         function checkGrammarArrowFunction(node, file) {
78994             if (!ts.isArrowFunction(node)) {
78995                 return false;
78996             }
78997             var equalsGreaterThanToken = node.equalsGreaterThanToken;
78998             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
78999             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
79000             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
79001         }
79002         function checkGrammarIndexSignatureParameters(node) {
79003             var parameter = node.parameters[0];
79004             if (node.parameters.length !== 1) {
79005                 if (parameter) {
79006                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
79007                 }
79008                 else {
79009                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
79010                 }
79011             }
79012             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
79013             if (parameter.dotDotDotToken) {
79014                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
79015             }
79016             if (ts.hasEffectiveModifiers(parameter)) {
79017                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
79018             }
79019             if (parameter.questionToken) {
79020                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
79021             }
79022             if (parameter.initializer) {
79023                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
79024             }
79025             if (!parameter.type) {
79026                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
79027             }
79028             if (parameter.type.kind !== 147 /* StringKeyword */ && parameter.type.kind !== 144 /* NumberKeyword */) {
79029                 var type = getTypeFromTypeNode(parameter.type);
79030                 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
79031                     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(node.type ? getTypeFromTypeNode(node.type) : anyType));
79032                 }
79033                 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
79034                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
79035                 }
79036                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
79037             }
79038             if (!node.type) {
79039                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
79040             }
79041             return false;
79042         }
79043         function checkGrammarIndexSignature(node) {
79044             // Prevent cascading error by short-circuit
79045             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
79046         }
79047         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
79048             if (typeArguments && typeArguments.length === 0) {
79049                 var sourceFile = ts.getSourceFileOfNode(node);
79050                 var start = typeArguments.pos - "<".length;
79051                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
79052                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
79053             }
79054             return false;
79055         }
79056         function checkGrammarTypeArguments(node, typeArguments) {
79057             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
79058                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
79059         }
79060         function checkGrammarTaggedTemplateChain(node) {
79061             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
79062                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
79063             }
79064             return false;
79065         }
79066         function checkGrammarForOmittedArgument(args) {
79067             if (args) {
79068                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
79069                     var arg = args_4[_i];
79070                     if (arg.kind === 222 /* OmittedExpression */) {
79071                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
79072                     }
79073                 }
79074             }
79075             return false;
79076         }
79077         function checkGrammarArguments(args) {
79078             return checkGrammarForOmittedArgument(args);
79079         }
79080         function checkGrammarHeritageClause(node) {
79081             var types = node.types;
79082             if (checkGrammarForDisallowedTrailingComma(types)) {
79083                 return true;
79084             }
79085             if (types && types.length === 0) {
79086                 var listType = ts.tokenToString(node.token);
79087                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
79088             }
79089             return ts.some(types, checkGrammarExpressionWithTypeArguments);
79090         }
79091         function checkGrammarExpressionWithTypeArguments(node) {
79092             return checkGrammarTypeArguments(node, node.typeArguments);
79093         }
79094         function checkGrammarClassDeclarationHeritageClauses(node) {
79095             var seenExtendsClause = false;
79096             var seenImplementsClause = false;
79097             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
79098                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
79099                     var heritageClause = _a[_i];
79100                     if (heritageClause.token === 93 /* ExtendsKeyword */) {
79101                         if (seenExtendsClause) {
79102                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
79103                         }
79104                         if (seenImplementsClause) {
79105                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
79106                         }
79107                         if (heritageClause.types.length > 1) {
79108                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
79109                         }
79110                         seenExtendsClause = true;
79111                     }
79112                     else {
79113                         ts.Debug.assert(heritageClause.token === 116 /* ImplementsKeyword */);
79114                         if (seenImplementsClause) {
79115                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
79116                         }
79117                         seenImplementsClause = true;
79118                     }
79119                     // Grammar checking heritageClause inside class declaration
79120                     checkGrammarHeritageClause(heritageClause);
79121                 }
79122             }
79123         }
79124         function checkGrammarInterfaceDeclaration(node) {
79125             var seenExtendsClause = false;
79126             if (node.heritageClauses) {
79127                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
79128                     var heritageClause = _a[_i];
79129                     if (heritageClause.token === 93 /* ExtendsKeyword */) {
79130                         if (seenExtendsClause) {
79131                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
79132                         }
79133                         seenExtendsClause = true;
79134                     }
79135                     else {
79136                         ts.Debug.assert(heritageClause.token === 116 /* ImplementsKeyword */);
79137                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
79138                     }
79139                     // Grammar checking heritageClause inside class declaration
79140                     checkGrammarHeritageClause(heritageClause);
79141                 }
79142             }
79143             return false;
79144         }
79145         function checkGrammarComputedPropertyName(node) {
79146             // If node is not a computedPropertyName, just skip the grammar checking
79147             if (node.kind !== 158 /* ComputedPropertyName */) {
79148                 return false;
79149             }
79150             var computedPropertyName = node;
79151             if (computedPropertyName.expression.kind === 216 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
79152                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
79153             }
79154             return false;
79155         }
79156         function checkGrammarForGenerator(node) {
79157             if (node.asteriskToken) {
79158                 ts.Debug.assert(node.kind === 251 /* FunctionDeclaration */ ||
79159                     node.kind === 208 /* FunctionExpression */ ||
79160                     node.kind === 165 /* MethodDeclaration */);
79161                 if (node.flags & 8388608 /* Ambient */) {
79162                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
79163                 }
79164                 if (!node.body) {
79165                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
79166                 }
79167             }
79168         }
79169         function checkGrammarForInvalidQuestionMark(questionToken, message) {
79170             return !!questionToken && grammarErrorOnNode(questionToken, message);
79171         }
79172         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
79173             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
79174         }
79175         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
79176             var seen = new ts.Map();
79177             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
79178                 var prop = _a[_i];
79179                 if (prop.kind === 290 /* SpreadAssignment */) {
79180                     if (inDestructuring) {
79181                         // a rest property cannot be destructured any further
79182                         var expression = ts.skipParentheses(prop.expression);
79183                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
79184                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
79185                         }
79186                     }
79187                     continue;
79188                 }
79189                 var name = prop.name;
79190                 if (name.kind === 158 /* ComputedPropertyName */) {
79191                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
79192                     checkGrammarComputedPropertyName(name);
79193                 }
79194                 if (prop.kind === 289 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
79195                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
79196                     // outside of destructuring it is a syntax error
79197                     return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern);
79198                 }
79199                 if (name.kind === 79 /* PrivateIdentifier */) {
79200                     return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
79201                 }
79202                 // Modifiers are never allowed on properties except for 'async' on a method declaration
79203                 if (prop.modifiers) {
79204                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
79205                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
79206                         var mod = _c[_b];
79207                         if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 165 /* MethodDeclaration */) {
79208                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
79209                         }
79210                     }
79211                 }
79212                 // ECMA-262 11.1.5 Object Initializer
79213                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
79214                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
79215                 // IsDataDescriptor(propId.descriptor) is true.
79216                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
79217                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
79218                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
79219                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
79220                 var currentKind = void 0;
79221                 switch (prop.kind) {
79222                     case 289 /* ShorthandPropertyAssignment */:
79223                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
79224                     // falls through
79225                     case 288 /* PropertyAssignment */:
79226                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
79227                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
79228                         if (name.kind === 8 /* NumericLiteral */) {
79229                             checkGrammarNumericLiteral(name);
79230                         }
79231                         currentKind = 4 /* PropertyAssignment */;
79232                         break;
79233                     case 165 /* MethodDeclaration */:
79234                         currentKind = 8 /* Method */;
79235                         break;
79236                     case 167 /* GetAccessor */:
79237                         currentKind = 1 /* GetAccessor */;
79238                         break;
79239                     case 168 /* SetAccessor */:
79240                         currentKind = 2 /* SetAccessor */;
79241                         break;
79242                     default:
79243                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
79244                 }
79245                 if (!inDestructuring) {
79246                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
79247                     if (effectiveName === undefined) {
79248                         continue;
79249                     }
79250                     var existingKind = seen.get(effectiveName);
79251                     if (!existingKind) {
79252                         seen.set(effectiveName, currentKind);
79253                     }
79254                     else {
79255                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
79256                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
79257                         }
79258                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
79259                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
79260                                 seen.set(effectiveName, currentKind | existingKind);
79261                             }
79262                             else {
79263                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
79264                             }
79265                         }
79266                         else {
79267                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
79268                         }
79269                     }
79270                 }
79271             }
79272         }
79273         function checkGrammarJsxElement(node) {
79274             checkGrammarTypeArguments(node, node.typeArguments);
79275             var seen = new ts.Map();
79276             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
79277                 var attr = _a[_i];
79278                 if (attr.kind === 282 /* JsxSpreadAttribute */) {
79279                     continue;
79280                 }
79281                 var name = attr.name, initializer = attr.initializer;
79282                 if (!seen.get(name.escapedText)) {
79283                     seen.set(name.escapedText, true);
79284                 }
79285                 else {
79286                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
79287                 }
79288                 if (initializer && initializer.kind === 283 /* JsxExpression */ && !initializer.expression) {
79289                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
79290                 }
79291             }
79292         }
79293         function checkGrammarJsxExpression(node) {
79294             if (node.expression && ts.isCommaSequence(node.expression)) {
79295                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
79296             }
79297         }
79298         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
79299             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
79300                 return true;
79301             }
79302             if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
79303                 if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
79304                     // use of 'for-await-of' in non-async function
79305                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
79306                     if (!hasParseDiagnostics(sourceFile)) {
79307                         var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
79308                         var func = ts.getContainingFunction(forInOrOfStatement);
79309                         if (func && func.kind !== 166 /* Constructor */) {
79310                             ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
79311                             var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
79312                             ts.addRelatedInfo(diagnostic, relatedInfo);
79313                         }
79314                         diagnostics.add(diagnostic);
79315                         return true;
79316                     }
79317                     return false;
79318                 }
79319             }
79320             if (forInOrOfStatement.initializer.kind === 250 /* VariableDeclarationList */) {
79321                 var variableList = forInOrOfStatement.initializer;
79322                 if (!checkGrammarVariableDeclarationList(variableList)) {
79323                     var declarations = variableList.declarations;
79324                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
79325                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
79326                     // For example:
79327                     //      var let = 10;
79328                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
79329                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
79330                     // We will then want to skip on grammar checking on variableList declaration
79331                     if (!declarations.length) {
79332                         return false;
79333                     }
79334                     if (declarations.length > 1) {
79335                         var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */
79336                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
79337                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
79338                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
79339                     }
79340                     var firstDeclaration = declarations[0];
79341                     if (firstDeclaration.initializer) {
79342                         var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */
79343                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
79344                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
79345                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
79346                     }
79347                     if (firstDeclaration.type) {
79348                         var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */
79349                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
79350                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
79351                         return grammarErrorOnNode(firstDeclaration, diagnostic);
79352                     }
79353                 }
79354             }
79355             return false;
79356         }
79357         function checkGrammarAccessor(accessor) {
79358             if (!(accessor.flags & 8388608 /* Ambient */)) {
79359                 if (languageVersion < 1 /* ES5 */) {
79360                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
79361                 }
79362                 if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
79363                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
79364                 }
79365             }
79366             if (accessor.body && ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
79367                 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
79368             }
79369             if (accessor.typeParameters) {
79370                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
79371             }
79372             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
79373                 return grammarErrorOnNode(accessor.name, accessor.kind === 167 /* GetAccessor */ ?
79374                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
79375                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
79376             }
79377             if (accessor.kind === 168 /* SetAccessor */) {
79378                 if (accessor.type) {
79379                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
79380                 }
79381                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
79382                 if (parameter.dotDotDotToken) {
79383                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
79384                 }
79385                 if (parameter.questionToken) {
79386                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
79387                 }
79388                 if (parameter.initializer) {
79389                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
79390                 }
79391             }
79392             return false;
79393         }
79394         /** Does the accessor have the right number of parameters?
79395          * A get accessor has no parameters or a single `this` parameter.
79396          * A set accessor has one parameter or a `this` parameter and one more parameter.
79397          */
79398         function doesAccessorHaveCorrectParameterCount(accessor) {
79399             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 0 : 1);
79400         }
79401         function getAccessorThisParameter(accessor) {
79402             if (accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 1 : 2)) {
79403                 return ts.getThisParameter(accessor);
79404             }
79405         }
79406         function checkGrammarTypeOperatorNode(node) {
79407             if (node.operator === 151 /* UniqueKeyword */) {
79408                 if (node.type.kind !== 148 /* SymbolKeyword */) {
79409                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(148 /* SymbolKeyword */));
79410                 }
79411                 var parent = ts.walkUpParenthesizedTypes(node.parent);
79412                 if (ts.isInJSFile(parent) && ts.isJSDocTypeExpression(parent)) {
79413                     parent = parent.parent;
79414                     if (ts.isJSDocTypeTag(parent)) {
79415                         // walk up past JSDoc comment node
79416                         parent = parent.parent.parent;
79417                     }
79418                 }
79419                 switch (parent.kind) {
79420                     case 249 /* VariableDeclaration */:
79421                         var decl = parent;
79422                         if (decl.name.kind !== 78 /* Identifier */) {
79423                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
79424                         }
79425                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
79426                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
79427                         }
79428                         if (!(decl.parent.flags & 2 /* Const */)) {
79429                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
79430                         }
79431                         break;
79432                     case 163 /* PropertyDeclaration */:
79433                         if (!ts.hasSyntacticModifier(parent, 32 /* Static */) ||
79434                             !ts.hasEffectiveModifier(parent, 64 /* Readonly */)) {
79435                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
79436                         }
79437                         break;
79438                     case 162 /* PropertySignature */:
79439                         if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) {
79440                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
79441                         }
79442                         break;
79443                     default:
79444                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
79445                 }
79446             }
79447             else if (node.operator === 142 /* ReadonlyKeyword */) {
79448                 if (node.type.kind !== 178 /* ArrayType */ && node.type.kind !== 179 /* TupleType */) {
79449                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(148 /* SymbolKeyword */));
79450                 }
79451             }
79452         }
79453         function checkGrammarForInvalidDynamicName(node, message) {
79454             if (isNonBindableDynamicName(node)) {
79455                 return grammarErrorOnNode(node, message);
79456             }
79457         }
79458         function checkGrammarMethod(node) {
79459             if (checkGrammarFunctionLikeDeclaration(node)) {
79460                 return true;
79461             }
79462             if (node.kind === 165 /* MethodDeclaration */) {
79463                 if (node.parent.kind === 200 /* ObjectLiteralExpression */) {
79464                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
79465                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129 /* AsyncKeyword */)) {
79466                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
79467                     }
79468                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
79469                         return true;
79470                     }
79471                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
79472                         return true;
79473                     }
79474                     else if (node.body === undefined) {
79475                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
79476                     }
79477                 }
79478                 if (checkGrammarForGenerator(node)) {
79479                     return true;
79480                 }
79481             }
79482             if (ts.isClassLike(node.parent)) {
79483                 // Technically, computed properties in ambient contexts is disallowed
79484                 // for property declarations and accessors too, not just methods.
79485                 // However, property declarations disallow computed names in general,
79486                 // and accessors are not allowed in ambient contexts in general,
79487                 // so this error only really matters for methods.
79488                 if (node.flags & 8388608 /* Ambient */) {
79489                     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);
79490                 }
79491                 else if (node.kind === 165 /* MethodDeclaration */ && !node.body) {
79492                     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);
79493                 }
79494             }
79495             else if (node.parent.kind === 253 /* InterfaceDeclaration */) {
79496                 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);
79497             }
79498             else if (node.parent.kind === 177 /* TypeLiteral */) {
79499                 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);
79500             }
79501         }
79502         function checkGrammarBreakOrContinueStatement(node) {
79503             var current = node;
79504             while (current) {
79505                 if (ts.isFunctionLike(current)) {
79506                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
79507                 }
79508                 switch (current.kind) {
79509                     case 245 /* LabeledStatement */:
79510                         if (node.label && current.label.escapedText === node.label.escapedText) {
79511                             // found matching label - verify that label usage is correct
79512                             // continue can only target labels that are on iteration statements
79513                             var isMisplacedContinueLabel = node.kind === 240 /* ContinueStatement */
79514                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
79515                             if (isMisplacedContinueLabel) {
79516                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
79517                             }
79518                             return false;
79519                         }
79520                         break;
79521                     case 244 /* SwitchStatement */:
79522                         if (node.kind === 241 /* BreakStatement */ && !node.label) {
79523                             // unlabeled break within switch statement - ok
79524                             return false;
79525                         }
79526                         break;
79527                     default:
79528                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
79529                             // unlabeled break or continue within iteration statement - ok
79530                             return false;
79531                         }
79532                         break;
79533                 }
79534                 current = current.parent;
79535             }
79536             if (node.label) {
79537                 var message = node.kind === 241 /* BreakStatement */
79538                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
79539                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
79540                 return grammarErrorOnNode(node, message);
79541             }
79542             else {
79543                 var message = node.kind === 241 /* BreakStatement */
79544                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
79545                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
79546                 return grammarErrorOnNode(node, message);
79547             }
79548         }
79549         function checkGrammarBindingElement(node) {
79550             if (node.dotDotDotToken) {
79551                 var elements = node.parent.elements;
79552                 if (node !== ts.last(elements)) {
79553                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
79554                 }
79555                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
79556                 if (node.propertyName) {
79557                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
79558                 }
79559             }
79560             if (node.dotDotDotToken && node.initializer) {
79561                 // Error on equals token which immediately precedes the initializer
79562                 return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
79563             }
79564         }
79565         function isStringOrNumberLiteralExpression(expr) {
79566             return ts.isStringOrNumericLiteralLike(expr) ||
79567                 expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
79568                     expr.operand.kind === 8 /* NumericLiteral */;
79569         }
79570         function isBigIntLiteralExpression(expr) {
79571             return expr.kind === 9 /* BigIntLiteral */ ||
79572                 expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
79573                     expr.operand.kind === 9 /* BigIntLiteral */;
79574         }
79575         function isSimpleLiteralEnumReference(expr) {
79576             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
79577                 ts.isEntityNameExpression(expr.expression)) {
79578                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
79579             }
79580         }
79581         function checkAmbientInitializer(node) {
79582             var initializer = node.initializer;
79583             if (initializer) {
79584                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
79585                     isSimpleLiteralEnumReference(initializer) ||
79586                     initializer.kind === 109 /* TrueKeyword */ || initializer.kind === 94 /* FalseKeyword */ ||
79587                     isBigIntLiteralExpression(initializer));
79588                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
79589                 if (isConstOrReadonly && !node.type) {
79590                     if (isInvalidInitializer) {
79591                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
79592                     }
79593                 }
79594                 else {
79595                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
79596                 }
79597                 if (!isConstOrReadonly || isInvalidInitializer) {
79598                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
79599                 }
79600             }
79601         }
79602         function checkGrammarVariableDeclaration(node) {
79603             if (node.parent.parent.kind !== 238 /* ForInStatement */ && node.parent.parent.kind !== 239 /* ForOfStatement */) {
79604                 if (node.flags & 8388608 /* Ambient */) {
79605                     checkAmbientInitializer(node);
79606                 }
79607                 else if (!node.initializer) {
79608                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
79609                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
79610                     }
79611                     if (ts.isVarConst(node)) {
79612                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
79613                     }
79614                 }
79615             }
79616             if (node.exclamationToken && (node.parent.parent.kind !== 232 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
79617                 var message = node.initializer
79618                     ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions
79619                     : ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations;
79620                 return grammarErrorOnNode(node.exclamationToken, message);
79621             }
79622             var moduleKind = ts.getEmitModuleKind(compilerOptions);
79623             if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System &&
79624                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasSyntacticModifier(node.parent.parent, 1 /* Export */)) {
79625                 checkESModuleMarker(node.name);
79626             }
79627             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
79628             // 1. LexicalDeclaration : LetOrConst BindingList ;
79629             // It is a Syntax Error if the BoundNames of BindingList contains "let".
79630             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
79631             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
79632             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
79633             // and its Identifier is eval or arguments
79634             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
79635         }
79636         function checkESModuleMarker(name) {
79637             if (name.kind === 78 /* Identifier */) {
79638                 if (ts.idText(name) === "__esModule") {
79639                     return grammarErrorOnNodeSkippedOn("noEmit", name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
79640                 }
79641             }
79642             else {
79643                 var elements = name.elements;
79644                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
79645                     var element = elements_1[_i];
79646                     if (!ts.isOmittedExpression(element)) {
79647                         return checkESModuleMarker(element.name);
79648                     }
79649                 }
79650             }
79651             return false;
79652         }
79653         function checkGrammarNameInLetOrConstDeclarations(name) {
79654             if (name.kind === 78 /* Identifier */) {
79655                 if (name.originalKeywordKind === 118 /* LetKeyword */) {
79656                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
79657                 }
79658             }
79659             else {
79660                 var elements = name.elements;
79661                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
79662                     var element = elements_2[_i];
79663                     if (!ts.isOmittedExpression(element)) {
79664                         checkGrammarNameInLetOrConstDeclarations(element.name);
79665                     }
79666                 }
79667             }
79668             return false;
79669         }
79670         function checkGrammarVariableDeclarationList(declarationList) {
79671             var declarations = declarationList.declarations;
79672             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
79673                 return true;
79674             }
79675             if (!declarationList.declarations.length) {
79676                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
79677             }
79678             return false;
79679         }
79680         function allowLetAndConstDeclarations(parent) {
79681             switch (parent.kind) {
79682                 case 234 /* IfStatement */:
79683                 case 235 /* DoStatement */:
79684                 case 236 /* WhileStatement */:
79685                 case 243 /* WithStatement */:
79686                 case 237 /* ForStatement */:
79687                 case 238 /* ForInStatement */:
79688                 case 239 /* ForOfStatement */:
79689                     return false;
79690                 case 245 /* LabeledStatement */:
79691                     return allowLetAndConstDeclarations(parent.parent);
79692             }
79693             return true;
79694         }
79695         function checkGrammarForDisallowedLetOrConstStatement(node) {
79696             if (!allowLetAndConstDeclarations(node.parent)) {
79697                 if (ts.isLet(node.declarationList)) {
79698                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
79699                 }
79700                 else if (ts.isVarConst(node.declarationList)) {
79701                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
79702                 }
79703             }
79704         }
79705         function checkGrammarMetaProperty(node) {
79706             var escapedText = node.name.escapedText;
79707             switch (node.keywordToken) {
79708                 case 102 /* NewKeyword */:
79709                     if (escapedText !== "target") {
79710                         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");
79711                     }
79712                     break;
79713                 case 99 /* ImportKeyword */:
79714                     if (escapedText !== "meta") {
79715                         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");
79716                     }
79717                     break;
79718             }
79719         }
79720         function hasParseDiagnostics(sourceFile) {
79721             return sourceFile.parseDiagnostics.length > 0;
79722         }
79723         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
79724             var sourceFile = ts.getSourceFileOfNode(node);
79725             if (!hasParseDiagnostics(sourceFile)) {
79726                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
79727                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
79728                 return true;
79729             }
79730             return false;
79731         }
79732         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
79733             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
79734             if (!hasParseDiagnostics(sourceFile)) {
79735                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
79736                 return true;
79737             }
79738             return false;
79739         }
79740         function grammarErrorOnNodeSkippedOn(key, node, message, arg0, arg1, arg2) {
79741             var sourceFile = ts.getSourceFileOfNode(node);
79742             if (!hasParseDiagnostics(sourceFile)) {
79743                 errorSkippedOn(key, node, message, arg0, arg1, arg2);
79744                 return true;
79745             }
79746             return false;
79747         }
79748         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
79749             var sourceFile = ts.getSourceFileOfNode(node);
79750             if (!hasParseDiagnostics(sourceFile)) {
79751                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
79752                 return true;
79753             }
79754             return false;
79755         }
79756         function checkGrammarConstructorTypeParameters(node) {
79757             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
79758             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
79759             if (range) {
79760                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
79761                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
79762             }
79763         }
79764         function checkGrammarConstructorTypeAnnotation(node) {
79765             var type = ts.getEffectiveReturnTypeNode(node);
79766             if (type) {
79767                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
79768             }
79769         }
79770         function checkGrammarProperty(node) {
79771             if (ts.isClassLike(node.parent)) {
79772                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
79773                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
79774                 }
79775                 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)) {
79776                     return true;
79777                 }
79778                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
79779                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
79780                 }
79781             }
79782             else if (node.parent.kind === 253 /* InterfaceDeclaration */) {
79783                 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)) {
79784                     return true;
79785                 }
79786                 if (node.initializer) {
79787                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
79788                 }
79789             }
79790             else if (node.parent.kind === 177 /* TypeLiteral */) {
79791                 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)) {
79792                     return true;
79793                 }
79794                 if (node.initializer) {
79795                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
79796                 }
79797             }
79798             if (node.flags & 8388608 /* Ambient */) {
79799                 checkAmbientInitializer(node);
79800             }
79801             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
79802                 node.flags & 8388608 /* Ambient */ || ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
79803                 var message = node.initializer
79804                     ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions
79805                     : !node.type
79806                         ? ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations
79807                         : ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
79808                 return grammarErrorOnNode(node.exclamationToken, message);
79809             }
79810         }
79811         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
79812             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
79813             // interfaces and imports categories:
79814             //
79815             //  DeclarationElement:
79816             //     ExportAssignment
79817             //     export_opt   InterfaceDeclaration
79818             //     export_opt   TypeAliasDeclaration
79819             //     export_opt   ImportDeclaration
79820             //     export_opt   ExternalImportDeclaration
79821             //     export_opt   AmbientDeclaration
79822             //
79823             // TODO: The spec needs to be amended to reflect this grammar.
79824             if (node.kind === 253 /* InterfaceDeclaration */ ||
79825                 node.kind === 254 /* TypeAliasDeclaration */ ||
79826                 node.kind === 261 /* ImportDeclaration */ ||
79827                 node.kind === 260 /* ImportEqualsDeclaration */ ||
79828                 node.kind === 267 /* ExportDeclaration */ ||
79829                 node.kind === 266 /* ExportAssignment */ ||
79830                 node.kind === 259 /* NamespaceExportDeclaration */ ||
79831                 ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
79832                 return false;
79833             }
79834             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
79835         }
79836         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
79837             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
79838                 var decl = _a[_i];
79839                 if (ts.isDeclaration(decl) || decl.kind === 232 /* VariableStatement */) {
79840                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
79841                         return true;
79842                     }
79843                 }
79844             }
79845             return false;
79846         }
79847         function checkGrammarSourceFile(node) {
79848             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
79849         }
79850         function checkGrammarStatementInAmbientContext(node) {
79851             if (node.flags & 8388608 /* Ambient */) {
79852                 // Find containing block which is either Block, ModuleBlock, SourceFile
79853                 var links = getNodeLinks(node);
79854                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
79855                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
79856                 }
79857                 // We are either parented by another statement, or some sort of block.
79858                 // If we're in a block, we only want to really report an error once
79859                 // to prevent noisiness.  So use a bit on the block to indicate if
79860                 // this has already been reported, and don't report if it has.
79861                 //
79862                 if (node.parent.kind === 230 /* Block */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
79863                     var links_2 = getNodeLinks(node.parent);
79864                     // Check if the containing block ever report this error
79865                     if (!links_2.hasReportedStatementInAmbientContext) {
79866                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
79867                     }
79868                 }
79869                 else {
79870                     // We must be parented by a statement.  If so, there's no need
79871                     // to report the error as our parent will have already done it.
79872                     // Debug.assert(isStatement(node.parent));
79873                 }
79874             }
79875             return false;
79876         }
79877         function checkGrammarNumericLiteral(node) {
79878             // Grammar checking
79879             if (node.numericLiteralFlags & 32 /* Octal */) {
79880                 var diagnosticMessage = void 0;
79881                 if (languageVersion >= 1 /* ES5 */) {
79882                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
79883                 }
79884                 else if (ts.isChildOfNodeWithKind(node, 191 /* LiteralType */)) {
79885                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
79886                 }
79887                 else if (ts.isChildOfNodeWithKind(node, 291 /* EnumMember */)) {
79888                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
79889                 }
79890                 if (diagnosticMessage) {
79891                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
79892                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
79893                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
79894                 }
79895             }
79896             // Realism (size) checking
79897             checkNumericLiteralValueSize(node);
79898             return false;
79899         }
79900         function checkNumericLiteralValueSize(node) {
79901             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
79902             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
79903             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
79904             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
79905                 return;
79906             }
79907             // We can't rely on the runtime to accurately store and compare extremely large numeric values
79908             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
79909             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
79910             // it's likely addition operations on it will fail too
79911             var apparentValue = +ts.getTextOfNode(node);
79912             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
79913                 return;
79914             }
79915             addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers));
79916         }
79917         function checkGrammarBigIntLiteral(node) {
79918             var literalType = ts.isLiteralTypeNode(node.parent) ||
79919                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
79920             if (!literalType) {
79921                 if (languageVersion < 7 /* ES2020 */) {
79922                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
79923                         return true;
79924                     }
79925                 }
79926             }
79927             return false;
79928         }
79929         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
79930             var sourceFile = ts.getSourceFileOfNode(node);
79931             if (!hasParseDiagnostics(sourceFile)) {
79932                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
79933                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
79934                 return true;
79935             }
79936             return false;
79937         }
79938         function getAmbientModules() {
79939             if (!ambientModulesCache) {
79940                 ambientModulesCache = [];
79941                 globals.forEach(function (global, sym) {
79942                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
79943                     if (ambientModuleSymbolRegex.test(sym)) {
79944                         ambientModulesCache.push(global);
79945                     }
79946                 });
79947             }
79948             return ambientModulesCache;
79949         }
79950         function checkGrammarImportClause(node) {
79951             if (node.isTypeOnly && node.name && node.namedBindings) {
79952                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
79953             }
79954             return false;
79955         }
79956         function checkGrammarImportCallExpression(node) {
79957             if (moduleKind === ts.ModuleKind.ES2015) {
79958                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
79959             }
79960             if (node.typeArguments) {
79961                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
79962             }
79963             var nodeArguments = node.arguments;
79964             if (nodeArguments.length !== 1) {
79965                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
79966             }
79967             checkGrammarForDisallowedTrailingComma(nodeArguments);
79968             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
79969             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
79970             if (ts.isSpreadElement(nodeArguments[0])) {
79971                 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
79972             }
79973             return false;
79974         }
79975         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
79976             var sourceObjectFlags = ts.getObjectFlags(source);
79977             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
79978                 return ts.find(unionTarget.types, function (target) {
79979                     if (target.flags & 524288 /* Object */) {
79980                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
79981                         if (overlapObjFlags & 4 /* Reference */) {
79982                             return source.target === target.target;
79983                         }
79984                         if (overlapObjFlags & 16 /* Anonymous */) {
79985                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
79986                         }
79987                     }
79988                     return false;
79989                 });
79990             }
79991         }
79992         function findBestTypeForObjectLiteral(source, unionTarget) {
79993             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
79994                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
79995             }
79996         }
79997         function findBestTypeForInvokable(source, unionTarget) {
79998             var signatureKind = 0 /* Call */;
79999             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
80000                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
80001             if (hasSignatures) {
80002                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
80003             }
80004         }
80005         function findMostOverlappyType(source, unionTarget) {
80006             var bestMatch;
80007             var matchingCount = 0;
80008             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
80009                 var target = _a[_i];
80010                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
80011                 if (overlap.flags & 4194304 /* Index */) {
80012                     // perfect overlap of keys
80013                     bestMatch = target;
80014                     matchingCount = Infinity;
80015                 }
80016                 else if (overlap.flags & 1048576 /* Union */) {
80017                     // We only want to account for literal types otherwise.
80018                     // If we have a union of index types, it seems likely that we
80019                     // needed to elaborate between two generic mapped types anyway.
80020                     var len = ts.length(ts.filter(overlap.types, isUnitType));
80021                     if (len >= matchingCount) {
80022                         bestMatch = target;
80023                         matchingCount = len;
80024                     }
80025                 }
80026                 else if (isUnitType(overlap) && 1 >= matchingCount) {
80027                     bestMatch = target;
80028                     matchingCount = 1;
80029                 }
80030             }
80031             return bestMatch;
80032         }
80033         function filterPrimitivesIfContainsNonPrimitive(type) {
80034             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
80035                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
80036                 if (!(result.flags & 131072 /* Never */)) {
80037                     return result;
80038                 }
80039             }
80040             return type;
80041         }
80042         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
80043         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
80044             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
80045                 var sourceProperties = getPropertiesOfType(source);
80046                 if (sourceProperties) {
80047                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
80048                     if (sourcePropertiesFiltered) {
80049                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
80050                     }
80051                 }
80052             }
80053             return undefined;
80054         }
80055     }
80056     ts.createTypeChecker = createTypeChecker;
80057     function isNotAccessor(declaration) {
80058         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
80059         return !ts.isAccessor(declaration);
80060     }
80061     function isNotOverload(declaration) {
80062         return (declaration.kind !== 251 /* FunctionDeclaration */ && declaration.kind !== 165 /* MethodDeclaration */) ||
80063             !!declaration.body;
80064     }
80065     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
80066     function isDeclarationNameOrImportPropertyName(name) {
80067         switch (name.parent.kind) {
80068             case 265 /* ImportSpecifier */:
80069             case 270 /* ExportSpecifier */:
80070                 return ts.isIdentifier(name);
80071             default:
80072                 return ts.isDeclarationName(name);
80073         }
80074     }
80075     function isSomeImportDeclaration(decl) {
80076         switch (decl.kind) {
80077             case 262 /* ImportClause */: // For default import
80078             case 260 /* ImportEqualsDeclaration */:
80079             case 263 /* NamespaceImport */:
80080             case 265 /* ImportSpecifier */: // For rename import `x as y`
80081                 return true;
80082             case 78 /* Identifier */:
80083                 // For regular import, `decl` is an Identifier under the ImportSpecifier.
80084                 return decl.parent.kind === 265 /* ImportSpecifier */;
80085             default:
80086                 return false;
80087         }
80088     }
80089     var JsxNames;
80090     (function (JsxNames) {
80091         JsxNames.JSX = "JSX";
80092         JsxNames.IntrinsicElements = "IntrinsicElements";
80093         JsxNames.ElementClass = "ElementClass";
80094         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
80095         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
80096         JsxNames.Element = "Element";
80097         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
80098         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
80099         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
80100     })(JsxNames || (JsxNames = {}));
80101     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
80102         switch (typeKind) {
80103             case 0 /* Yield */: return "yieldType";
80104             case 1 /* Return */: return "returnType";
80105             case 2 /* Next */: return "nextType";
80106         }
80107     }
80108     function signatureHasRestParameter(s) {
80109         return !!(s.flags & 1 /* HasRestParameter */);
80110     }
80111     ts.signatureHasRestParameter = signatureHasRestParameter;
80112     function signatureHasLiteralTypes(s) {
80113         return !!(s.flags & 2 /* HasLiteralTypes */);
80114     }
80115     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
80116 })(ts || (ts = {}));
80117 var ts;
80118 (function (ts) {
80119     var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
80120     function visitNode(node, visitor, test, lift) {
80121         if (node === undefined || visitor === undefined) {
80122             return node;
80123         }
80124         var visited = visitor(node);
80125         if (visited === node) {
80126             return node;
80127         }
80128         var visitedNode;
80129         if (visited === undefined) {
80130             return undefined;
80131         }
80132         else if (ts.isArray(visited)) {
80133             visitedNode = (lift || extractSingleNode)(visited);
80134         }
80135         else {
80136             visitedNode = visited;
80137         }
80138         ts.Debug.assertNode(visitedNode, test);
80139         return visitedNode;
80140     }
80141     ts.visitNode = visitNode;
80142     /**
80143      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
80144      *
80145      * @param nodes The NodeArray to visit.
80146      * @param visitor The callback used to visit a Node.
80147      * @param test A node test to execute for each node.
80148      * @param start An optional value indicating the starting offset at which to start visiting.
80149      * @param count An optional value indicating the maximum number of nodes to visit.
80150      */
80151     function visitNodes(nodes, visitor, test, start, count) {
80152         if (nodes === undefined || visitor === undefined) {
80153             return nodes;
80154         }
80155         var updated;
80156         // Ensure start and count have valid values
80157         var length = nodes.length;
80158         if (start === undefined || start < 0) {
80159             start = 0;
80160         }
80161         if (count === undefined || count > length - start) {
80162             count = length - start;
80163         }
80164         var hasTrailingComma;
80165         var pos = -1;
80166         var end = -1;
80167         if (start > 0 || count < length) {
80168             // If we are not visiting all of the original nodes, we must always create a new array.
80169             // Since this is a fragment of a node array, we do not copy over the previous location
80170             // and will only copy over `hasTrailingComma` if we are including the last element.
80171             updated = [];
80172             hasTrailingComma = nodes.hasTrailingComma && start + count === length;
80173         }
80174         // Visit each original node.
80175         for (var i = 0; i < count; i++) {
80176             var node = nodes[i + start];
80177             var visited = node !== undefined ? visitor(node) : undefined;
80178             if (updated !== undefined || visited === undefined || visited !== node) {
80179                 if (updated === undefined) {
80180                     // Ensure we have a copy of `nodes`, up to the current index.
80181                     updated = nodes.slice(0, i);
80182                     hasTrailingComma = nodes.hasTrailingComma;
80183                     pos = nodes.pos;
80184                     end = nodes.end;
80185                 }
80186                 if (visited) {
80187                     if (ts.isArray(visited)) {
80188                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
80189                             var visitedNode = visited_1[_i];
80190                             void ts.Debug.assertNode(visitedNode, test);
80191                             updated.push(visitedNode);
80192                         }
80193                     }
80194                     else {
80195                         void ts.Debug.assertNode(visited, test);
80196                         updated.push(visited);
80197                     }
80198                 }
80199             }
80200         }
80201         if (updated) {
80202             // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory.
80203             var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma);
80204             ts.setTextRangePosEnd(updatedArray, pos, end);
80205             return updatedArray;
80206         }
80207         return nodes;
80208     }
80209     ts.visitNodes = visitNodes;
80210     /**
80211      * Starts a new lexical environment and visits a statement list, ending the lexical environment
80212      * and merging hoisted declarations upon completion.
80213      */
80214     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict, nodesVisitor) {
80215         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
80216         context.startLexicalEnvironment();
80217         statements = nodesVisitor(statements, visitor, ts.isStatement, start);
80218         if (ensureUseStrict)
80219             statements = context.factory.ensureUseStrict(statements);
80220         return ts.factory.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
80221     }
80222     ts.visitLexicalEnvironment = visitLexicalEnvironment;
80223     function visitParameterList(nodes, visitor, context, nodesVisitor) {
80224         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
80225         var updated;
80226         context.startLexicalEnvironment();
80227         if (nodes) {
80228             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
80229             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
80230             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
80231             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
80232             // that we might transform that introduces a temporary variable would fail as the temporary variable
80233             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
80234             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
80235             // when the emit target is greater than ES2015.
80236             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
80237                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
80238                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
80239             }
80240             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
80241         }
80242         context.suspendLexicalEnvironment();
80243         return updated;
80244     }
80245     ts.visitParameterList = visitParameterList;
80246     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
80247         var result;
80248         for (var i = 0; i < parameters.length; i++) {
80249             var parameter = parameters[i];
80250             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
80251             if (result || updated !== parameter) {
80252                 if (!result)
80253                     result = parameters.slice(0, i);
80254                 result[i] = updated;
80255             }
80256         }
80257         if (result) {
80258             return ts.setTextRange(context.factory.createNodeArray(result, parameters.hasTrailingComma), parameters);
80259         }
80260         return parameters;
80261     }
80262     function addDefaultValueAssignmentIfNeeded(parameter, context) {
80263         // A rest parameter cannot have a binding pattern or an initializer,
80264         // so let's just ignore it.
80265         return parameter.dotDotDotToken ? parameter :
80266             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
80267                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
80268                     parameter;
80269     }
80270     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
80271         var factory = context.factory;
80272         context.addInitializationStatement(factory.createVariableStatement(
80273         /*modifiers*/ undefined, factory.createVariableDeclarationList([
80274             factory.createVariableDeclaration(parameter.name, 
80275             /*exclamationToken*/ undefined, parameter.type, parameter.initializer ?
80276                 factory.createConditionalExpression(factory.createStrictEquality(factory.getGeneratedNameForNode(parameter), factory.createVoidZero()), 
80277                 /*questionToken*/ undefined, parameter.initializer, 
80278                 /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) :
80279                 factory.getGeneratedNameForNode(parameter)),
80280         ])));
80281         return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
80282         /*initializer*/ undefined);
80283     }
80284     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
80285         var factory = context.factory;
80286         context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
80287             factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(ts.setEmitFlags(factory.cloneNode(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
80288         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
80289         return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
80290         /*initializer*/ undefined);
80291     }
80292     function visitFunctionBody(node, visitor, context, nodeVisitor) {
80293         if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
80294         context.resumeLexicalEnvironment();
80295         var updated = nodeVisitor(node, visitor, ts.isConciseBody);
80296         var declarations = context.endLexicalEnvironment();
80297         if (ts.some(declarations)) {
80298             if (!updated) {
80299                 return context.factory.createBlock(declarations);
80300             }
80301             var block = context.factory.converters.convertToFunctionBlock(updated);
80302             var statements = ts.factory.mergeLexicalEnvironment(block.statements, declarations);
80303             return context.factory.updateBlock(block, statements);
80304         }
80305         return updated;
80306     }
80307     ts.visitFunctionBody = visitFunctionBody;
80308     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) {
80309         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
80310         if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
80311         if (node === undefined) {
80312             return undefined;
80313         }
80314         var kind = node.kind;
80315         // No need to visit nodes with no children.
80316         if ((kind > 0 /* FirstToken */ && kind <= 156 /* LastToken */) || kind === 187 /* ThisType */) {
80317             return node;
80318         }
80319         var factory = context.factory;
80320         switch (kind) {
80321             // Names
80322             case 78 /* Identifier */:
80323                 return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
80324             case 157 /* QualifiedName */:
80325                 return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier));
80326             case 158 /* ComputedPropertyName */:
80327                 return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80328             // Signature elements
80329             case 159 /* TypeParameter */:
80330                 return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode));
80331             case 160 /* Parameter */:
80332                 return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
80333             case 161 /* Decorator */:
80334                 return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80335             // Type elements
80336             case 162 /* PropertySignature */:
80337                 return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode));
80338             case 163 /* PropertyDeclaration */:
80339                 return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), 
80340                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
80341                 nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
80342             case 164 /* MethodSignature */:
80343                 return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80344             case 165 /* MethodDeclaration */:
80345                 return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80346             case 166 /* Constructor */:
80347                 return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80348             case 167 /* GetAccessor */:
80349                 return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80350             case 168 /* SetAccessor */:
80351                 return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80352             case 169 /* CallSignature */:
80353                 return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80354             case 170 /* ConstructSignature */:
80355                 return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80356             case 171 /* IndexSignature */:
80357                 return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80358             // Types
80359             case 172 /* TypePredicate */:
80360                 return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode));
80361             case 173 /* TypeReference */:
80362                 return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
80363             case 174 /* FunctionType */:
80364                 return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80365             case 175 /* ConstructorType */:
80366                 return factory.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80367             case 176 /* TypeQuery */:
80368                 return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName));
80369             case 177 /* TypeLiteral */:
80370                 return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
80371             case 178 /* ArrayType */:
80372                 return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode));
80373             case 179 /* TupleType */:
80374                 return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode));
80375             case 180 /* OptionalType */:
80376                 return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
80377             case 181 /* RestType */:
80378                 return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
80379             case 182 /* UnionType */:
80380                 return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
80381             case 183 /* IntersectionType */:
80382                 return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
80383             case 184 /* ConditionalType */:
80384                 return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode));
80385             case 185 /* InferType */:
80386                 return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
80387             case 195 /* ImportType */:
80388                 return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
80389             case 192 /* NamedTupleMember */:
80390                 return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode));
80391             case 186 /* ParenthesizedType */:
80392                 return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
80393             case 188 /* TypeOperator */:
80394                 return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
80395             case 189 /* IndexedAccessType */:
80396                 return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode));
80397             case 190 /* MappedType */:
80398                 return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode));
80399             case 191 /* LiteralType */:
80400                 return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression));
80401             case 193 /* TemplateLiteralType */:
80402                 return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan));
80403             case 194 /* TemplateLiteralTypeSpan */:
80404                 return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
80405             // Binding patterns
80406             case 196 /* ObjectBindingPattern */:
80407                 return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
80408             case 197 /* ArrayBindingPattern */:
80409                 return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
80410             case 198 /* BindingElement */:
80411                 return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression));
80412             // Expression
80413             case 199 /* ArrayLiteralExpression */:
80414                 return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
80415             case 200 /* ObjectLiteralExpression */:
80416                 return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
80417             case 201 /* PropertyAccessExpression */:
80418                 if (node.flags & 32 /* OptionalChain */) {
80419                     return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier));
80420                 }
80421                 return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
80422             case 202 /* ElementAccessExpression */:
80423                 if (node.flags & 32 /* OptionalChain */) {
80424                     return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
80425                 }
80426                 return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
80427             case 203 /* CallExpression */:
80428                 if (node.flags & 32 /* OptionalChain */) {
80429                     return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
80430                 }
80431                 return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
80432             case 204 /* NewExpression */:
80433                 return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
80434             case 205 /* TaggedTemplateExpression */:
80435                 return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral));
80436             case 206 /* TypeAssertionExpression */:
80437                 return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression));
80438             case 207 /* ParenthesizedExpression */:
80439                 return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80440             case 208 /* FunctionExpression */:
80441                 return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80442             case 209 /* ArrowFunction */:
80443                 return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80444             case 210 /* DeleteExpression */:
80445                 return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80446             case 211 /* TypeOfExpression */:
80447                 return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80448             case 212 /* VoidExpression */:
80449                 return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80450             case 213 /* AwaitExpression */:
80451                 return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80452             case 214 /* PrefixUnaryExpression */:
80453                 return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
80454             case 215 /* PostfixUnaryExpression */:
80455                 return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
80456             case 216 /* BinaryExpression */:
80457                 return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression));
80458             case 217 /* ConditionalExpression */:
80459                 return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression));
80460             case 218 /* TemplateExpression */:
80461                 return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
80462             case 219 /* YieldExpression */:
80463                 return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression));
80464             case 220 /* SpreadElement */:
80465                 return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80466             case 221 /* ClassExpression */:
80467                 return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
80468             case 223 /* ExpressionWithTypeArguments */:
80469                 return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
80470             case 224 /* AsExpression */:
80471                 return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode));
80472             case 225 /* NonNullExpression */:
80473                 if (node.flags & 32 /* OptionalChain */) {
80474                     return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80475                 }
80476                 return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80477             case 226 /* MetaProperty */:
80478                 return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
80479             // Misc
80480             case 228 /* TemplateSpan */:
80481                 return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
80482             // Element
80483             case 230 /* Block */:
80484                 return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
80485             case 232 /* VariableStatement */:
80486                 return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList));
80487             case 233 /* ExpressionStatement */:
80488                 return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80489             case 234 /* IfStatement */:
80490                 return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock));
80491             case 235 /* DoStatement */:
80492                 return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression));
80493             case 236 /* WhileStatement */:
80494                 return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80495             case 237 /* ForStatement */:
80496                 return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80497             case 238 /* ForInStatement */:
80498                 return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80499             case 239 /* ForOfStatement */:
80500                 return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isToken), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80501             case 240 /* ContinueStatement */:
80502                 return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
80503             case 241 /* BreakStatement */:
80504                 return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
80505             case 242 /* ReturnStatement */:
80506                 return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80507             case 243 /* WithStatement */:
80508                 return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80509             case 244 /* SwitchStatement */:
80510                 return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock));
80511             case 245 /* LabeledStatement */:
80512                 return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80513             case 246 /* ThrowStatement */:
80514                 return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80515             case 247 /* TryStatement */:
80516                 return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock));
80517             case 249 /* VariableDeclaration */:
80518                 return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
80519             case 250 /* VariableDeclarationList */:
80520                 return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
80521             case 251 /* FunctionDeclaration */:
80522                 return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80523             case 252 /* ClassDeclaration */:
80524                 return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
80525             case 253 /* InterfaceDeclaration */:
80526                 return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement));
80527             case 254 /* TypeAliasDeclaration */:
80528                 return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80529             case 255 /* EnumDeclaration */:
80530                 return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember));
80531             case 256 /* ModuleDeclaration */:
80532                 return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.body, visitor, ts.isModuleBody));
80533             case 257 /* ModuleBlock */:
80534                 return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
80535             case 258 /* CaseBlock */:
80536                 return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
80537             case 259 /* NamespaceExportDeclaration */:
80538                 return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
80539             case 260 /* ImportEqualsDeclaration */:
80540                 return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference));
80541             case 261 /* ImportDeclaration */:
80542                 return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression));
80543             case 262 /* ImportClause */:
80544                 return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings));
80545             case 263 /* NamespaceImport */:
80546                 return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
80547             case 269 /* NamespaceExport */:
80548                 return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
80549             case 264 /* NamedImports */:
80550                 return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
80551             case 265 /* ImportSpecifier */:
80552                 return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
80553             case 266 /* ExportAssignment */:
80554                 return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression));
80555             case 267 /* ExportDeclaration */:
80556                 return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression));
80557             case 268 /* NamedExports */:
80558                 return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
80559             case 270 /* ExportSpecifier */:
80560                 return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
80561             // Module references
80562             case 272 /* ExternalModuleReference */:
80563                 return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80564             // JSX
80565             case 273 /* JsxElement */:
80566                 return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement));
80567             case 274 /* JsxSelfClosingElement */:
80568                 return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
80569             case 275 /* JsxOpeningElement */:
80570                 return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
80571             case 276 /* JsxClosingElement */:
80572                 return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression));
80573             case 277 /* JsxFragment */:
80574                 return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment));
80575             case 280 /* JsxAttribute */:
80576                 return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
80577             case 281 /* JsxAttributes */:
80578                 return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
80579             case 282 /* JsxSpreadAttribute */:
80580                 return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80581             case 283 /* JsxExpression */:
80582                 return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80583             // Clauses
80584             case 284 /* CaseClause */:
80585                 return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
80586             case 285 /* DefaultClause */:
80587                 return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
80588             case 286 /* HeritageClause */:
80589                 return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
80590             case 287 /* CatchClause */:
80591                 return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock));
80592             // Property assignments
80593             case 288 /* PropertyAssignment */:
80594                 return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
80595             case 289 /* ShorthandPropertyAssignment */:
80596                 return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression));
80597             case 290 /* SpreadAssignment */:
80598                 return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80599             // Enum
80600             case 291 /* EnumMember */:
80601                 return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
80602             // Top-level nodes
80603             case 297 /* SourceFile */:
80604                 return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context));
80605             // Transformation nodes
80606             case 336 /* PartiallyEmittedExpression */:
80607                 return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80608             case 337 /* CommaListExpression */:
80609                 return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
80610             default:
80611                 // No need to visit nodes with no children.
80612                 return node;
80613         }
80614     }
80615     ts.visitEachChild = visitEachChild;
80616     /**
80617      * Extracts the single node from a NodeArray.
80618      *
80619      * @param nodes The NodeArray.
80620      */
80621     function extractSingleNode(nodes) {
80622         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
80623         return ts.singleOrUndefined(nodes);
80624     }
80625 })(ts || (ts = {}));
80626 /* @internal */
80627 var ts;
80628 (function (ts) {
80629     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
80630         var _a = generatorOptions.extendedDiagnostics
80631             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
80632             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
80633         // Current source map file and its index in the sources list
80634         var rawSources = [];
80635         var sources = [];
80636         var sourceToSourceIndexMap = new ts.Map();
80637         var sourcesContent;
80638         var names = [];
80639         var nameToNameIndexMap;
80640         var mappings = "";
80641         // Last recorded and encoded mappings
80642         var lastGeneratedLine = 0;
80643         var lastGeneratedCharacter = 0;
80644         var lastSourceIndex = 0;
80645         var lastSourceLine = 0;
80646         var lastSourceCharacter = 0;
80647         var lastNameIndex = 0;
80648         var hasLast = false;
80649         var pendingGeneratedLine = 0;
80650         var pendingGeneratedCharacter = 0;
80651         var pendingSourceIndex = 0;
80652         var pendingSourceLine = 0;
80653         var pendingSourceCharacter = 0;
80654         var pendingNameIndex = 0;
80655         var hasPending = false;
80656         var hasPendingSource = false;
80657         var hasPendingName = false;
80658         return {
80659             getSources: function () { return rawSources; },
80660             addSource: addSource,
80661             setSourceContent: setSourceContent,
80662             addName: addName,
80663             addMapping: addMapping,
80664             appendSourceMap: appendSourceMap,
80665             toJSON: toJSON,
80666             toString: function () { return JSON.stringify(toJSON()); }
80667         };
80668         function addSource(fileName) {
80669             enter();
80670             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
80671             /*isAbsolutePathAnUrl*/ true);
80672             var sourceIndex = sourceToSourceIndexMap.get(source);
80673             if (sourceIndex === undefined) {
80674                 sourceIndex = sources.length;
80675                 sources.push(source);
80676                 rawSources.push(fileName);
80677                 sourceToSourceIndexMap.set(source, sourceIndex);
80678             }
80679             exit();
80680             return sourceIndex;
80681         }
80682         /* eslint-disable boolean-trivia, no-null/no-null */
80683         function setSourceContent(sourceIndex, content) {
80684             enter();
80685             if (content !== null) {
80686                 if (!sourcesContent)
80687                     sourcesContent = [];
80688                 while (sourcesContent.length < sourceIndex) {
80689                     sourcesContent.push(null);
80690                 }
80691                 sourcesContent[sourceIndex] = content;
80692             }
80693             exit();
80694         }
80695         /* eslint-enable boolean-trivia, no-null/no-null */
80696         function addName(name) {
80697             enter();
80698             if (!nameToNameIndexMap)
80699                 nameToNameIndexMap = new ts.Map();
80700             var nameIndex = nameToNameIndexMap.get(name);
80701             if (nameIndex === undefined) {
80702                 nameIndex = names.length;
80703                 names.push(name);
80704                 nameToNameIndexMap.set(name, nameIndex);
80705             }
80706             exit();
80707             return nameIndex;
80708         }
80709         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
80710             return !hasPending
80711                 || pendingGeneratedLine !== generatedLine
80712                 || pendingGeneratedCharacter !== generatedCharacter;
80713         }
80714         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
80715             return sourceIndex !== undefined
80716                 && sourceLine !== undefined
80717                 && sourceCharacter !== undefined
80718                 && pendingSourceIndex === sourceIndex
80719                 && (pendingSourceLine > sourceLine
80720                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
80721         }
80722         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
80723             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
80724             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
80725             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
80726             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
80727             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
80728             enter();
80729             // If this location wasn't recorded or the location in source is going backwards, record the mapping
80730             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
80731                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
80732                 commitPendingMapping();
80733                 pendingGeneratedLine = generatedLine;
80734                 pendingGeneratedCharacter = generatedCharacter;
80735                 hasPendingSource = false;
80736                 hasPendingName = false;
80737                 hasPending = true;
80738             }
80739             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
80740                 pendingSourceIndex = sourceIndex;
80741                 pendingSourceLine = sourceLine;
80742                 pendingSourceCharacter = sourceCharacter;
80743                 hasPendingSource = true;
80744                 if (nameIndex !== undefined) {
80745                     pendingNameIndex = nameIndex;
80746                     hasPendingName = true;
80747                 }
80748             }
80749             exit();
80750         }
80751         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
80752             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
80753             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
80754             enter();
80755             // First, decode the old component sourcemap
80756             var sourceIndexToNewSourceIndexMap = [];
80757             var nameIndexToNewNameIndexMap;
80758             var mappingIterator = decodeMappings(map.mappings);
80759             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
80760                 var raw = iterResult.value;
80761                 if (end && (raw.generatedLine > end.line ||
80762                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
80763                     break;
80764                 }
80765                 if (start && (raw.generatedLine < start.line ||
80766                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
80767                     continue;
80768                 }
80769                 // Then reencode all the updated mappings into the overall map
80770                 var newSourceIndex = void 0;
80771                 var newSourceLine = void 0;
80772                 var newSourceCharacter = void 0;
80773                 var newNameIndex = void 0;
80774                 if (raw.sourceIndex !== undefined) {
80775                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
80776                     if (newSourceIndex === undefined) {
80777                         // Apply offsets to each position and fixup source entries
80778                         var rawPath = map.sources[raw.sourceIndex];
80779                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
80780                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
80781                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
80782                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
80783                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
80784                         }
80785                     }
80786                     newSourceLine = raw.sourceLine;
80787                     newSourceCharacter = raw.sourceCharacter;
80788                     if (map.names && raw.nameIndex !== undefined) {
80789                         if (!nameIndexToNewNameIndexMap)
80790                             nameIndexToNewNameIndexMap = [];
80791                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
80792                         if (newNameIndex === undefined) {
80793                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
80794                         }
80795                     }
80796                 }
80797                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
80798                 var newGeneratedLine = rawGeneratedLine + generatedLine;
80799                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
80800                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
80801                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
80802             }
80803             exit();
80804         }
80805         function shouldCommitMapping() {
80806             return !hasLast
80807                 || lastGeneratedLine !== pendingGeneratedLine
80808                 || lastGeneratedCharacter !== pendingGeneratedCharacter
80809                 || lastSourceIndex !== pendingSourceIndex
80810                 || lastSourceLine !== pendingSourceLine
80811                 || lastSourceCharacter !== pendingSourceCharacter
80812                 || lastNameIndex !== pendingNameIndex;
80813         }
80814         function commitPendingMapping() {
80815             if (!hasPending || !shouldCommitMapping()) {
80816                 return;
80817             }
80818             enter();
80819             // Line/Comma delimiters
80820             if (lastGeneratedLine < pendingGeneratedLine) {
80821                 // Emit line delimiters
80822                 do {
80823                     mappings += ";";
80824                     lastGeneratedLine++;
80825                     lastGeneratedCharacter = 0;
80826                 } while (lastGeneratedLine < pendingGeneratedLine);
80827             }
80828             else {
80829                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
80830                 // Emit comma to separate the entry
80831                 if (hasLast) {
80832                     mappings += ",";
80833                 }
80834             }
80835             // 1. Relative generated character
80836             mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
80837             lastGeneratedCharacter = pendingGeneratedCharacter;
80838             if (hasPendingSource) {
80839                 // 2. Relative sourceIndex
80840                 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
80841                 lastSourceIndex = pendingSourceIndex;
80842                 // 3. Relative source line
80843                 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
80844                 lastSourceLine = pendingSourceLine;
80845                 // 4. Relative source character
80846                 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
80847                 lastSourceCharacter = pendingSourceCharacter;
80848                 if (hasPendingName) {
80849                     // 5. Relative nameIndex
80850                     mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
80851                     lastNameIndex = pendingNameIndex;
80852                 }
80853             }
80854             hasLast = true;
80855             exit();
80856         }
80857         function toJSON() {
80858             commitPendingMapping();
80859             return {
80860                 version: 3,
80861                 file: file,
80862                 sourceRoot: sourceRoot,
80863                 sources: sources,
80864                 names: names,
80865                 mappings: mappings,
80866                 sourcesContent: sourcesContent,
80867             };
80868         }
80869     }
80870     ts.createSourceMapGenerator = createSourceMapGenerator;
80871     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
80872     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
80873     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
80874     function getLineInfo(text, lineStarts) {
80875         return {
80876             getLineCount: function () { return lineStarts.length; },
80877             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
80878         };
80879     }
80880     ts.getLineInfo = getLineInfo;
80881     /**
80882      * Tries to find the sourceMappingURL comment at the end of a file.
80883      */
80884     function tryGetSourceMappingURL(lineInfo) {
80885         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
80886             var line = lineInfo.getLineText(index);
80887             var comment = sourceMapCommentRegExp.exec(line);
80888             if (comment) {
80889                 return comment[1];
80890             }
80891             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
80892             else if (!line.match(whitespaceOrMapCommentRegExp)) {
80893                 break;
80894             }
80895         }
80896     }
80897     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
80898     /* eslint-disable no-null/no-null */
80899     function isStringOrNull(x) {
80900         return typeof x === "string" || x === null;
80901     }
80902     function isRawSourceMap(x) {
80903         return x !== null
80904             && typeof x === "object"
80905             && x.version === 3
80906             && typeof x.file === "string"
80907             && typeof x.mappings === "string"
80908             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
80909             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
80910             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
80911             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
80912     }
80913     ts.isRawSourceMap = isRawSourceMap;
80914     /* eslint-enable no-null/no-null */
80915     function tryParseRawSourceMap(text) {
80916         try {
80917             var parsed = JSON.parse(text);
80918             if (isRawSourceMap(parsed)) {
80919                 return parsed;
80920             }
80921         }
80922         catch (_a) {
80923             // empty
80924         }
80925         return undefined;
80926     }
80927     ts.tryParseRawSourceMap = tryParseRawSourceMap;
80928     function decodeMappings(mappings) {
80929         var done = false;
80930         var pos = 0;
80931         var generatedLine = 0;
80932         var generatedCharacter = 0;
80933         var sourceIndex = 0;
80934         var sourceLine = 0;
80935         var sourceCharacter = 0;
80936         var nameIndex = 0;
80937         var error;
80938         return {
80939             get pos() { return pos; },
80940             get error() { return error; },
80941             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
80942             next: function () {
80943                 while (!done && pos < mappings.length) {
80944                     var ch = mappings.charCodeAt(pos);
80945                     if (ch === 59 /* semicolon */) {
80946                         // new line
80947                         generatedLine++;
80948                         generatedCharacter = 0;
80949                         pos++;
80950                         continue;
80951                     }
80952                     if (ch === 44 /* comma */) {
80953                         // Next entry is on same line - no action needed
80954                         pos++;
80955                         continue;
80956                     }
80957                     var hasSource = false;
80958                     var hasName = false;
80959                     generatedCharacter += base64VLQFormatDecode();
80960                     if (hasReportedError())
80961                         return stopIterating();
80962                     if (generatedCharacter < 0)
80963                         return setErrorAndStopIterating("Invalid generatedCharacter found");
80964                     if (!isSourceMappingSegmentEnd()) {
80965                         hasSource = true;
80966                         sourceIndex += base64VLQFormatDecode();
80967                         if (hasReportedError())
80968                             return stopIterating();
80969                         if (sourceIndex < 0)
80970                             return setErrorAndStopIterating("Invalid sourceIndex found");
80971                         if (isSourceMappingSegmentEnd())
80972                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
80973                         sourceLine += base64VLQFormatDecode();
80974                         if (hasReportedError())
80975                             return stopIterating();
80976                         if (sourceLine < 0)
80977                             return setErrorAndStopIterating("Invalid sourceLine found");
80978                         if (isSourceMappingSegmentEnd())
80979                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
80980                         sourceCharacter += base64VLQFormatDecode();
80981                         if (hasReportedError())
80982                             return stopIterating();
80983                         if (sourceCharacter < 0)
80984                             return setErrorAndStopIterating("Invalid sourceCharacter found");
80985                         if (!isSourceMappingSegmentEnd()) {
80986                             hasName = true;
80987                             nameIndex += base64VLQFormatDecode();
80988                             if (hasReportedError())
80989                                 return stopIterating();
80990                             if (nameIndex < 0)
80991                                 return setErrorAndStopIterating("Invalid nameIndex found");
80992                             if (!isSourceMappingSegmentEnd())
80993                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
80994                         }
80995                     }
80996                     return { value: captureMapping(hasSource, hasName), done: done };
80997                 }
80998                 return stopIterating();
80999             }
81000         };
81001         function captureMapping(hasSource, hasName) {
81002             return {
81003                 generatedLine: generatedLine,
81004                 generatedCharacter: generatedCharacter,
81005                 sourceIndex: hasSource ? sourceIndex : undefined,
81006                 sourceLine: hasSource ? sourceLine : undefined,
81007                 sourceCharacter: hasSource ? sourceCharacter : undefined,
81008                 nameIndex: hasName ? nameIndex : undefined
81009             };
81010         }
81011         function stopIterating() {
81012             done = true;
81013             return { value: undefined, done: true };
81014         }
81015         function setError(message) {
81016             if (error === undefined) {
81017                 error = message;
81018             }
81019         }
81020         function setErrorAndStopIterating(message) {
81021             setError(message);
81022             return stopIterating();
81023         }
81024         function hasReportedError() {
81025             return error !== undefined;
81026         }
81027         function isSourceMappingSegmentEnd() {
81028             return (pos === mappings.length ||
81029                 mappings.charCodeAt(pos) === 44 /* comma */ ||
81030                 mappings.charCodeAt(pos) === 59 /* semicolon */);
81031         }
81032         function base64VLQFormatDecode() {
81033             var moreDigits = true;
81034             var shiftCount = 0;
81035             var value = 0;
81036             for (; moreDigits; pos++) {
81037                 if (pos >= mappings.length)
81038                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
81039                 // 6 digit number
81040                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
81041                 if (currentByte === -1)
81042                     return setError("Invalid character in VLQ"), -1;
81043                 // If msb is set, we still have more bits to continue
81044                 moreDigits = (currentByte & 32) !== 0;
81045                 // least significant 5 bits are the next msbs in the final value.
81046                 value = value | ((currentByte & 31) << shiftCount);
81047                 shiftCount += 5;
81048             }
81049             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
81050             if ((value & 1) === 0) {
81051                 // + number
81052                 value = value >> 1;
81053             }
81054             else {
81055                 // - number
81056                 value = value >> 1;
81057                 value = -value;
81058             }
81059             return value;
81060         }
81061     }
81062     ts.decodeMappings = decodeMappings;
81063     function sameMapping(left, right) {
81064         return left === right
81065             || left.generatedLine === right.generatedLine
81066                 && left.generatedCharacter === right.generatedCharacter
81067                 && left.sourceIndex === right.sourceIndex
81068                 && left.sourceLine === right.sourceLine
81069                 && left.sourceCharacter === right.sourceCharacter
81070                 && left.nameIndex === right.nameIndex;
81071     }
81072     ts.sameMapping = sameMapping;
81073     function isSourceMapping(mapping) {
81074         return mapping.sourceIndex !== undefined
81075             && mapping.sourceLine !== undefined
81076             && mapping.sourceCharacter !== undefined;
81077     }
81078     ts.isSourceMapping = isSourceMapping;
81079     function base64FormatEncode(value) {
81080         return value >= 0 && value < 26 ? 65 /* A */ + value :
81081             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
81082                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
81083                     value === 62 ? 43 /* plus */ :
81084                         value === 63 ? 47 /* slash */ :
81085                             ts.Debug.fail(value + ": not a base64 value");
81086     }
81087     function base64FormatDecode(ch) {
81088         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
81089             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
81090                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
81091                     ch === 43 /* plus */ ? 62 :
81092                         ch === 47 /* slash */ ? 63 :
81093                             -1;
81094     }
81095     function base64VLQFormatEncode(inValue) {
81096         // Add a new least significant bit that has the sign of the value.
81097         // if negative number the least significant bit that gets added to the number has value 1
81098         // else least significant bit value that gets added is 0
81099         // eg. -1 changes to binary : 01 [1] => 3
81100         //     +1 changes to binary : 01 [0] => 2
81101         if (inValue < 0) {
81102             inValue = ((-inValue) << 1) + 1;
81103         }
81104         else {
81105             inValue = inValue << 1;
81106         }
81107         // Encode 5 bits at a time starting from least significant bits
81108         var encodedStr = "";
81109         do {
81110             var currentDigit = inValue & 31; // 11111
81111             inValue = inValue >> 5;
81112             if (inValue > 0) {
81113                 // There are still more digits to decode, set the msb (6th bit)
81114                 currentDigit = currentDigit | 32;
81115             }
81116             encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
81117         } while (inValue > 0);
81118         return encodedStr;
81119     }
81120     function isSourceMappedPosition(value) {
81121         return value.sourceIndex !== undefined
81122             && value.sourcePosition !== undefined;
81123     }
81124     function sameMappedPosition(left, right) {
81125         return left.generatedPosition === right.generatedPosition
81126             && left.sourceIndex === right.sourceIndex
81127             && left.sourcePosition === right.sourcePosition;
81128     }
81129     function compareSourcePositions(left, right) {
81130         // Compares sourcePosition without comparing sourceIndex
81131         // since the mappings are grouped by sourceIndex
81132         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
81133         return ts.compareValues(left.sourcePosition, right.sourcePosition);
81134     }
81135     function compareGeneratedPositions(left, right) {
81136         return ts.compareValues(left.generatedPosition, right.generatedPosition);
81137     }
81138     function getSourcePositionOfMapping(value) {
81139         return value.sourcePosition;
81140     }
81141     function getGeneratedPositionOfMapping(value) {
81142         return value.generatedPosition;
81143     }
81144     function createDocumentPositionMapper(host, map, mapPath) {
81145         var mapDirectory = ts.getDirectoryPath(mapPath);
81146         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
81147         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
81148         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
81149         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
81150         var sourceToSourceIndexMap = new ts.Map(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
81151         var decodedMappings;
81152         var generatedMappings;
81153         var sourceMappings;
81154         return {
81155             getSourcePosition: getSourcePosition,
81156             getGeneratedPosition: getGeneratedPosition
81157         };
81158         function processMapping(mapping) {
81159             var generatedPosition = generatedFile !== undefined
81160                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
81161                 : -1;
81162             var source;
81163             var sourcePosition;
81164             if (isSourceMapping(mapping)) {
81165                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
81166                 source = map.sources[mapping.sourceIndex];
81167                 sourcePosition = sourceFile !== undefined
81168                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
81169                     : -1;
81170             }
81171             return {
81172                 generatedPosition: generatedPosition,
81173                 source: source,
81174                 sourceIndex: mapping.sourceIndex,
81175                 sourcePosition: sourcePosition,
81176                 nameIndex: mapping.nameIndex
81177             };
81178         }
81179         function getDecodedMappings() {
81180             if (decodedMappings === undefined) {
81181                 var decoder = decodeMappings(map.mappings);
81182                 var mappings = ts.arrayFrom(decoder, processMapping);
81183                 if (decoder.error !== undefined) {
81184                     if (host.log) {
81185                         host.log("Encountered error while decoding sourcemap: " + decoder.error);
81186                     }
81187                     decodedMappings = ts.emptyArray;
81188                 }
81189                 else {
81190                     decodedMappings = mappings;
81191                 }
81192             }
81193             return decodedMappings;
81194         }
81195         function getSourceMappings(sourceIndex) {
81196             if (sourceMappings === undefined) {
81197                 var lists = [];
81198                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
81199                     var mapping = _a[_i];
81200                     if (!isSourceMappedPosition(mapping))
81201                         continue;
81202                     var list = lists[mapping.sourceIndex];
81203                     if (!list)
81204                         lists[mapping.sourceIndex] = list = [];
81205                     list.push(mapping);
81206                 }
81207                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
81208             }
81209             return sourceMappings[sourceIndex];
81210         }
81211         function getGeneratedMappings() {
81212             if (generatedMappings === undefined) {
81213                 var list = [];
81214                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
81215                     var mapping = _a[_i];
81216                     list.push(mapping);
81217                 }
81218                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
81219             }
81220             return generatedMappings;
81221         }
81222         function getGeneratedPosition(loc) {
81223             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
81224             if (sourceIndex === undefined)
81225                 return loc;
81226             var sourceMappings = getSourceMappings(sourceIndex);
81227             if (!ts.some(sourceMappings))
81228                 return loc;
81229             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
81230             if (targetIndex < 0) {
81231                 // if no exact match, closest is 2's complement of result
81232                 targetIndex = ~targetIndex;
81233             }
81234             var mapping = sourceMappings[targetIndex];
81235             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
81236                 return loc;
81237             }
81238             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
81239         }
81240         function getSourcePosition(loc) {
81241             var generatedMappings = getGeneratedMappings();
81242             if (!ts.some(generatedMappings))
81243                 return loc;
81244             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
81245             if (targetIndex < 0) {
81246                 // if no exact match, closest is 2's complement of result
81247                 targetIndex = ~targetIndex;
81248             }
81249             var mapping = generatedMappings[targetIndex];
81250             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
81251                 return loc;
81252             }
81253             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
81254         }
81255     }
81256     ts.createDocumentPositionMapper = createDocumentPositionMapper;
81257     ts.identitySourceMapConsumer = {
81258         getSourcePosition: ts.identity,
81259         getGeneratedPosition: ts.identity
81260     };
81261 })(ts || (ts = {}));
81262 /* @internal */
81263 var ts;
81264 (function (ts) {
81265     function getOriginalNodeId(node) {
81266         node = ts.getOriginalNode(node);
81267         return node ? ts.getNodeId(node) : 0;
81268     }
81269     ts.getOriginalNodeId = getOriginalNodeId;
81270     function containsDefaultReference(node) {
81271         if (!node)
81272             return false;
81273         if (!ts.isNamedImports(node))
81274             return false;
81275         return ts.some(node.elements, isNamedDefaultReference);
81276     }
81277     function isNamedDefaultReference(e) {
81278         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
81279     }
81280     function chainBundle(context, transformSourceFile) {
81281         return transformSourceFileOrBundle;
81282         function transformSourceFileOrBundle(node) {
81283             return node.kind === 297 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
81284         }
81285         function transformBundle(node) {
81286             return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
81287         }
81288     }
81289     ts.chainBundle = chainBundle;
81290     function getExportNeedsImportStarHelper(node) {
81291         return !!ts.getNamespaceDeclarationNode(node);
81292     }
81293     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
81294     function getImportNeedsImportStarHelper(node) {
81295         if (!!ts.getNamespaceDeclarationNode(node)) {
81296             return true;
81297         }
81298         var bindings = node.importClause && node.importClause.namedBindings;
81299         if (!bindings) {
81300             return false;
81301         }
81302         if (!ts.isNamedImports(bindings))
81303             return false;
81304         var defaultRefCount = 0;
81305         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
81306             var binding = _a[_i];
81307             if (isNamedDefaultReference(binding)) {
81308                 defaultRefCount++;
81309             }
81310         }
81311         // 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
81312         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
81313     }
81314     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
81315     function getImportNeedsImportDefaultHelper(node) {
81316         // 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)
81317         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
81318     }
81319     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
81320     function collectExternalModuleInfo(context, sourceFile, resolver, compilerOptions) {
81321         var externalImports = [];
81322         var exportSpecifiers = ts.createMultiMap();
81323         var exportedBindings = [];
81324         var uniqueExports = new ts.Map();
81325         var exportedNames;
81326         var hasExportDefault = false;
81327         var exportEquals;
81328         var hasExportStarsToExportValues = false;
81329         var hasImportStar = false;
81330         var hasImportDefault = false;
81331         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
81332             var node = _a[_i];
81333             switch (node.kind) {
81334                 case 261 /* ImportDeclaration */:
81335                     // import "mod"
81336                     // import x from "mod"
81337                     // import * as x from "mod"
81338                     // import { x, y } from "mod"
81339                     externalImports.push(node);
81340                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
81341                         hasImportStar = true;
81342                     }
81343                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
81344                         hasImportDefault = true;
81345                     }
81346                     break;
81347                 case 260 /* ImportEqualsDeclaration */:
81348                     if (node.moduleReference.kind === 272 /* ExternalModuleReference */) {
81349                         // import x = require("mod")
81350                         externalImports.push(node);
81351                     }
81352                     break;
81353                 case 267 /* ExportDeclaration */:
81354                     if (node.moduleSpecifier) {
81355                         if (!node.exportClause) {
81356                             // export * from "mod"
81357                             externalImports.push(node);
81358                             hasExportStarsToExportValues = true;
81359                         }
81360                         else {
81361                             // export * as ns from "mod"
81362                             // export { x, y } from "mod"
81363                             externalImports.push(node);
81364                             if (ts.isNamedExports(node.exportClause)) {
81365                                 addExportedNamesForExportDeclaration(node);
81366                             }
81367                             else {
81368                                 var name = node.exportClause.name;
81369                                 if (!uniqueExports.get(ts.idText(name))) {
81370                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
81371                                     uniqueExports.set(ts.idText(name), true);
81372                                     exportedNames = ts.append(exportedNames, name);
81373                                 }
81374                                 // we use the same helpers for `export * as ns` as we do for `import * as ns`
81375                                 hasImportStar = true;
81376                             }
81377                         }
81378                     }
81379                     else {
81380                         // export { x, y }
81381                         addExportedNamesForExportDeclaration(node);
81382                     }
81383                     break;
81384                 case 266 /* ExportAssignment */:
81385                     if (node.isExportEquals && !exportEquals) {
81386                         // export = x
81387                         exportEquals = node;
81388                     }
81389                     break;
81390                 case 232 /* VariableStatement */:
81391                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
81392                         for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) {
81393                             var decl = _c[_b];
81394                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
81395                         }
81396                     }
81397                     break;
81398                 case 251 /* FunctionDeclaration */:
81399                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
81400                         if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
81401                             // export default function() { }
81402                             if (!hasExportDefault) {
81403                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
81404                                 hasExportDefault = true;
81405                             }
81406                         }
81407                         else {
81408                             // export function x() { }
81409                             var name = node.name;
81410                             if (!uniqueExports.get(ts.idText(name))) {
81411                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
81412                                 uniqueExports.set(ts.idText(name), true);
81413                                 exportedNames = ts.append(exportedNames, name);
81414                             }
81415                         }
81416                     }
81417                     break;
81418                 case 252 /* ClassDeclaration */:
81419                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
81420                         if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
81421                             // export default class { }
81422                             if (!hasExportDefault) {
81423                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
81424                                 hasExportDefault = true;
81425                             }
81426                         }
81427                         else {
81428                             // export class x { }
81429                             var name = node.name;
81430                             if (name && !uniqueExports.get(ts.idText(name))) {
81431                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
81432                                 uniqueExports.set(ts.idText(name), true);
81433                                 exportedNames = ts.append(exportedNames, name);
81434                             }
81435                         }
81436                     }
81437                     break;
81438             }
81439         }
81440         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(context.factory, context.getEmitHelperFactory(), sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
81441         if (externalHelpersImportDeclaration) {
81442             externalImports.unshift(externalHelpersImportDeclaration);
81443         }
81444         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
81445         function addExportedNamesForExportDeclaration(node) {
81446             for (var _i = 0, _a = ts.cast(node.exportClause, ts.isNamedExports).elements; _i < _a.length; _i++) {
81447                 var specifier = _a[_i];
81448                 if (!uniqueExports.get(ts.idText(specifier.name))) {
81449                     var name = specifier.propertyName || specifier.name;
81450                     if (!node.moduleSpecifier) {
81451                         exportSpecifiers.add(ts.idText(name), specifier);
81452                     }
81453                     var decl = resolver.getReferencedImportDeclaration(name)
81454                         || resolver.getReferencedValueDeclaration(name);
81455                     if (decl) {
81456                         multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
81457                     }
81458                     uniqueExports.set(ts.idText(specifier.name), true);
81459                     exportedNames = ts.append(exportedNames, specifier.name);
81460                 }
81461             }
81462         }
81463     }
81464     ts.collectExternalModuleInfo = collectExternalModuleInfo;
81465     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
81466         if (ts.isBindingPattern(decl.name)) {
81467             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
81468                 var element = _a[_i];
81469                 if (!ts.isOmittedExpression(element)) {
81470                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
81471                 }
81472             }
81473         }
81474         else if (!ts.isGeneratedIdentifier(decl.name)) {
81475             var text = ts.idText(decl.name);
81476             if (!uniqueExports.get(text)) {
81477                 uniqueExports.set(text, true);
81478                 exportedNames = ts.append(exportedNames, decl.name);
81479             }
81480         }
81481         return exportedNames;
81482     }
81483     /** Use a sparse array as a multi-map. */
81484     function multiMapSparseArrayAdd(map, key, value) {
81485         var values = map[key];
81486         if (values) {
81487             values.push(value);
81488         }
81489         else {
81490             map[key] = values = [value];
81491         }
81492         return values;
81493     }
81494     /**
81495      * Used in the module transformer to check if an expression is reasonably without sideeffect,
81496      *  and thus better to copy into multiple places rather than to cache in a temporary variable
81497      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
81498      */
81499     function isSimpleCopiableExpression(expression) {
81500         return ts.isStringLiteralLike(expression) ||
81501             expression.kind === 8 /* NumericLiteral */ ||
81502             ts.isKeyword(expression.kind) ||
81503             ts.isIdentifier(expression);
81504     }
81505     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
81506     /**
81507      * A simple inlinable expression is an expression which can be copied into multiple locations
81508      * without risk of repeating any sideeffects and whose value could not possibly change between
81509      * any such locations
81510      */
81511     function isSimpleInlineableExpression(expression) {
81512         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
81513             ts.isWellKnownSymbolSyntactically(expression);
81514     }
81515     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
81516     function isCompoundAssignment(kind) {
81517         return kind >= 63 /* FirstCompoundAssignment */
81518             && kind <= 77 /* LastCompoundAssignment */;
81519     }
81520     ts.isCompoundAssignment = isCompoundAssignment;
81521     function getNonAssignmentOperatorForCompoundAssignment(kind) {
81522         switch (kind) {
81523             case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
81524             case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
81525             case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
81526             case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
81527             case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
81528             case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
81529             case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
81530             case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
81531             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
81532             case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
81533             case 73 /* BarEqualsToken */: return 51 /* BarToken */;
81534             case 77 /* CaretEqualsToken */: return 52 /* CaretToken */;
81535             case 74 /* BarBarEqualsToken */: return 56 /* BarBarToken */;
81536             case 75 /* AmpersandAmpersandEqualsToken */: return 55 /* AmpersandAmpersandToken */;
81537             case 76 /* QuestionQuestionEqualsToken */: return 60 /* QuestionQuestionToken */;
81538         }
81539     }
81540     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
81541     /**
81542      * Adds super call and preceding prologue directives into the list of statements.
81543      *
81544      * @param ctor The constructor node.
81545      * @param result The list of statements.
81546      * @param visitor The visitor to apply to each node added to the result array.
81547      * @returns index of the statement that follows super call
81548      */
81549     function addPrologueDirectivesAndInitialSuperCall(factory, ctor, result, visitor) {
81550         if (ctor.body) {
81551             var statements = ctor.body.statements;
81552             // add prologue directives to the list (if any)
81553             var index = factory.copyPrologue(statements, result, /*ensureUseStrict*/ false, visitor);
81554             if (index === statements.length) {
81555                 // list contains nothing but prologue directives (or empty) - exit
81556                 return index;
81557             }
81558             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
81559             if (superIndex > -1) {
81560                 for (var i = index; i <= superIndex; i++) {
81561                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
81562                 }
81563                 return superIndex + 1;
81564             }
81565             return index;
81566         }
81567         return 0;
81568     }
81569     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
81570     function getProperties(node, requireInitializer, isStatic) {
81571         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
81572     }
81573     ts.getProperties = getProperties;
81574     /**
81575      * Is a class element either a static or an instance property declaration with an initializer?
81576      *
81577      * @param member The class element node.
81578      * @param isStatic A value indicating whether the member should be a static or instance member.
81579      */
81580     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
81581         return ts.isPropertyDeclaration(member)
81582             && (!!member.initializer || !requireInitializer)
81583             && ts.hasStaticModifier(member) === isStatic;
81584     }
81585     /**
81586      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
81587      *
81588      * @param member The class element node.
81589      * @param isStatic A value indicating whether the member should be a static or instance member.
81590      */
81591     function isInitializedProperty(member) {
81592         return member.kind === 163 /* PropertyDeclaration */
81593             && member.initializer !== undefined;
81594     }
81595     ts.isInitializedProperty = isInitializedProperty;
81596 })(ts || (ts = {}));
81597 /*@internal*/
81598 var ts;
81599 (function (ts) {
81600     var FlattenLevel;
81601     (function (FlattenLevel) {
81602         FlattenLevel[FlattenLevel["All"] = 0] = "All";
81603         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
81604     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
81605     /**
81606      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
81607      *
81608      * @param node The node to flatten.
81609      * @param visitor An optional visitor used to visit initializers.
81610      * @param context The transformation context.
81611      * @param level Indicates the extent to which flattening should occur.
81612      * @param needsValue An optional value indicating whether the value from the right-hand-side of
81613      * the destructuring assignment is needed as part of a larger expression.
81614      * @param createAssignmentCallback An optional callback used to create the assignment expression.
81615      */
81616     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
81617         var location = node;
81618         var value;
81619         if (ts.isDestructuringAssignment(node)) {
81620             value = node.right;
81621             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
81622                 if (ts.isDestructuringAssignment(value)) {
81623                     location = node = value;
81624                     value = node.right;
81625                 }
81626                 else {
81627                     return ts.visitNode(value, visitor, ts.isExpression);
81628                 }
81629             }
81630         }
81631         var expressions;
81632         var flattenContext = {
81633             context: context,
81634             level: level,
81635             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
81636             hoistTempVariables: true,
81637             emitExpression: emitExpression,
81638             emitBindingOrAssignment: emitBindingOrAssignment,
81639             createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayAssignmentPattern(context.factory, elements); },
81640             createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectAssignmentPattern(context.factory, elements); },
81641             createArrayBindingOrAssignmentElement: makeAssignmentElement,
81642             visitor: visitor
81643         };
81644         if (value) {
81645             value = ts.visitNode(value, visitor, ts.isExpression);
81646             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
81647                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
81648                 // If the right-hand value of the assignment is also an assignment target then
81649                 // we need to cache the right-hand value.
81650                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
81651             }
81652             else if (needsValue) {
81653                 // If the right-hand value of the destructuring assignment needs to be preserved (as
81654                 // is the case when the destructuring assignment is part of a larger expression),
81655                 // then we need to cache the right-hand value.
81656                 //
81657                 // The source map location for the assignment should point to the entire binary
81658                 // expression.
81659                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
81660             }
81661             else if (ts.nodeIsSynthesized(node)) {
81662                 // Generally, the source map location for a destructuring assignment is the root
81663                 // expression.
81664                 //
81665                 // However, if the root expression is synthesized (as in the case
81666                 // of the initializer when transforming a ForOfStatement), then the source map
81667                 // location should point to the right-hand value of the expression.
81668                 location = value;
81669             }
81670         }
81671         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
81672         if (value && needsValue) {
81673             if (!ts.some(expressions)) {
81674                 return value;
81675             }
81676             expressions.push(value);
81677         }
81678         return context.factory.inlineExpressions(expressions) || context.factory.createOmittedExpression();
81679         function emitExpression(expression) {
81680             expressions = ts.append(expressions, expression);
81681         }
81682         function emitBindingOrAssignment(target, value, location, original) {
81683             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
81684             var expression = createAssignmentCallback
81685                 ? createAssignmentCallback(target, value, location)
81686                 : ts.setTextRange(context.factory.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
81687             expression.original = original;
81688             emitExpression(expression);
81689         }
81690     }
81691     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
81692     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
81693         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
81694         if (ts.isBindingOrAssignmentPattern(target)) {
81695             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
81696         }
81697         else if (ts.isIdentifier(target)) {
81698             return target.escapedText === escapedName;
81699         }
81700         return false;
81701     }
81702     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
81703         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
81704         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
81705             var element = elements_3[_i];
81706             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
81707                 return true;
81708             }
81709         }
81710         return false;
81711     }
81712     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
81713         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
81714         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
81715             return true;
81716         }
81717         var target = ts.getTargetOfBindingOrAssignmentElement(element);
81718         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
81719     }
81720     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
81721         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
81722     }
81723     /**
81724      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
81725      *
81726      * @param node The node to flatten.
81727      * @param visitor An optional visitor used to visit initializers.
81728      * @param context The transformation context.
81729      * @param boundValue The value bound to the declaration.
81730      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
81731      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
81732      * @param level Indicates the extent to which flattening should occur.
81733      */
81734     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
81735         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
81736         var pendingExpressions;
81737         var pendingDeclarations = [];
81738         var declarations = [];
81739         var flattenContext = {
81740             context: context,
81741             level: level,
81742             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
81743             hoistTempVariables: hoistTempVariables,
81744             emitExpression: emitExpression,
81745             emitBindingOrAssignment: emitBindingOrAssignment,
81746             createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayBindingPattern(context.factory, elements); },
81747             createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectBindingPattern(context.factory, elements); },
81748             createArrayBindingOrAssignmentElement: function (name) { return makeBindingElement(context.factory, name); },
81749             visitor: visitor
81750         };
81751         if (ts.isVariableDeclaration(node)) {
81752             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
81753             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
81754                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
81755                 // If the right-hand value of the assignment is also an assignment target then
81756                 // we need to cache the right-hand value.
81757                 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
81758                 node = context.factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer);
81759             }
81760         }
81761         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
81762         if (pendingExpressions) {
81763             var temp = context.factory.createTempVariable(/*recordTempVariable*/ undefined);
81764             if (hoistTempVariables) {
81765                 var value = context.factory.inlineExpressions(pendingExpressions);
81766                 pendingExpressions = undefined;
81767                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
81768             }
81769             else {
81770                 context.hoistVariableDeclaration(temp);
81771                 var pendingDeclaration = ts.last(pendingDeclarations);
81772                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, context.factory.createAssignment(temp, pendingDeclaration.value));
81773                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
81774                 pendingDeclaration.value = temp;
81775             }
81776         }
81777         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
81778             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
81779             var variable = context.factory.createVariableDeclaration(name, 
81780             /*exclamationToken*/ undefined, 
81781             /*type*/ undefined, pendingExpressions_1 ? context.factory.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
81782             variable.original = original;
81783             ts.setTextRange(variable, location);
81784             declarations.push(variable);
81785         }
81786         return declarations;
81787         function emitExpression(value) {
81788             pendingExpressions = ts.append(pendingExpressions, value);
81789         }
81790         function emitBindingOrAssignment(target, value, location, original) {
81791             ts.Debug.assertNode(target, ts.isBindingName);
81792             if (pendingExpressions) {
81793                 value = context.factory.inlineExpressions(ts.append(pendingExpressions, value));
81794                 pendingExpressions = undefined;
81795             }
81796             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
81797         }
81798     }
81799     ts.flattenDestructuringBinding = flattenDestructuringBinding;
81800     /**
81801      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
81802      *
81803      * @param flattenContext Options used to control flattening.
81804      * @param element The element to flatten.
81805      * @param value The current RHS value to assign to the element.
81806      * @param location The location to use for source maps and comments.
81807      * @param skipInitializer An optional value indicating whether to include the initializer
81808      * for the element.
81809      */
81810     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
81811         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
81812         if (!skipInitializer) {
81813             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
81814             if (initializer) {
81815                 // Combine value and initializer
81816                 if (value) {
81817                     value = createDefaultValueCheck(flattenContext, value, initializer, location);
81818                     // If 'value' is not a simple expression, it could contain side-effecting code that should evaluate before an object or array binding pattern.
81819                     if (!ts.isSimpleInlineableExpression(initializer) && ts.isBindingOrAssignmentPattern(bindingTarget)) {
81820                         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
81821                     }
81822                 }
81823                 else {
81824                     value = initializer;
81825                 }
81826             }
81827             else if (!value) {
81828                 // Use 'void 0' in absence of value and initializer
81829                 value = flattenContext.context.factory.createVoidZero();
81830             }
81831         }
81832         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
81833             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
81834         }
81835         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
81836             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
81837         }
81838         else {
81839             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
81840         }
81841     }
81842     /**
81843      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
81844      *
81845      * @param flattenContext Options used to control flattening.
81846      * @param parent The parent element of the pattern.
81847      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
81848      * @param value The current RHS value to assign to the element.
81849      * @param location The location to use for source maps and comments.
81850      */
81851     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
81852         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
81853         var numElements = elements.length;
81854         if (numElements !== 1) {
81855             // For anything other than a single-element destructuring we need to generate a temporary
81856             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
81857             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
81858             // so in that case, we'll intentionally create that temporary.
81859             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
81860             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
81861         }
81862         var bindingElements;
81863         var computedTempVariables;
81864         for (var i = 0; i < numElements; i++) {
81865             var element = elements[i];
81866             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
81867                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
81868                 if (flattenContext.level >= 1 /* ObjectRest */
81869                     && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
81870                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
81871                     && !ts.isComputedPropertyName(propertyName)) {
81872                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
81873                 }
81874                 else {
81875                     if (bindingElements) {
81876                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
81877                         bindingElements = undefined;
81878                     }
81879                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
81880                     if (ts.isComputedPropertyName(propertyName)) {
81881                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
81882                     }
81883                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
81884                 }
81885             }
81886             else if (i === numElements - 1) {
81887                 if (bindingElements) {
81888                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
81889                     bindingElements = undefined;
81890                 }
81891                 var rhsValue = flattenContext.context.getEmitHelperFactory().createRestHelper(value, elements, computedTempVariables, pattern);
81892                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
81893             }
81894         }
81895         if (bindingElements) {
81896             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
81897         }
81898     }
81899     /**
81900      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
81901      *
81902      * @param flattenContext Options used to control flattening.
81903      * @param parent The parent element of the pattern.
81904      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
81905      * @param value The current RHS value to assign to the element.
81906      * @param location The location to use for source maps and comments.
81907      */
81908     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
81909         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
81910         var numElements = elements.length;
81911         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
81912             // Read the elements of the iterable into an array
81913             value = ensureIdentifier(flattenContext, ts.setTextRange(flattenContext.context.getEmitHelperFactory().createReadHelper(value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
81914                 ? undefined
81915                 : numElements), location), 
81916             /*reuseIdentifierExpressions*/ false, location);
81917         }
81918         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
81919             || ts.every(elements, ts.isOmittedExpression)) {
81920             // For anything other than a single-element destructuring we need to generate a temporary
81921             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
81922             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
81923             // so in that case, we'll intentionally create that temporary.
81924             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
81925             // then we will create temporary variable.
81926             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
81927             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
81928         }
81929         var bindingElements;
81930         var restContainingElements;
81931         for (var i = 0; i < numElements; i++) {
81932             var element = elements[i];
81933             if (flattenContext.level >= 1 /* ObjectRest */) {
81934                 // If an array pattern contains an ObjectRest, we must cache the result so that we
81935                 // can perform the ObjectRest destructuring in a different declaration
81936                 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) {
81937                     flattenContext.hasTransformedPriorElement = true;
81938                     var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
81939                     if (flattenContext.hoistTempVariables) {
81940                         flattenContext.context.hoistVariableDeclaration(temp);
81941                     }
81942                     restContainingElements = ts.append(restContainingElements, [temp, element]);
81943                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
81944                 }
81945                 else {
81946                     bindingElements = ts.append(bindingElements, element);
81947                 }
81948             }
81949             else if (ts.isOmittedExpression(element)) {
81950                 continue;
81951             }
81952             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
81953                 var rhsValue = flattenContext.context.factory.createElementAccessExpression(value, i);
81954                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
81955             }
81956             else if (i === numElements - 1) {
81957                 var rhsValue = flattenContext.context.factory.createArraySliceCall(value, i);
81958                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
81959             }
81960         }
81961         if (bindingElements) {
81962             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
81963         }
81964         if (restContainingElements) {
81965             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
81966                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
81967                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
81968             }
81969         }
81970     }
81971     function isSimpleBindingOrAssignmentElement(element) {
81972         var target = ts.getTargetOfBindingOrAssignmentElement(element);
81973         if (!target || ts.isOmittedExpression(target))
81974             return true;
81975         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
81976         if (propertyName && !ts.isPropertyNameLiteral(propertyName))
81977             return false;
81978         var initializer = ts.getInitializerOfBindingOrAssignmentElement(element);
81979         if (initializer && !ts.isSimpleInlineableExpression(initializer))
81980             return false;
81981         if (ts.isBindingOrAssignmentPattern(target))
81982             return ts.every(ts.getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement);
81983         return ts.isIdentifier(target);
81984     }
81985     /**
81986      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
81987      *
81988      * @param flattenContext Options used to control flattening.
81989      * @param value The RHS value to test.
81990      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
81991      * @param location The location to use for source maps and comments.
81992      */
81993     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
81994         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
81995         return flattenContext.context.factory.createConditionalExpression(flattenContext.context.factory.createTypeCheck(value, "undefined"), /*questionToken*/ undefined, defaultValue, /*colonToken*/ undefined, value);
81996     }
81997     /**
81998      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
81999      * right-hand side of a transformed destructuring assignment.
82000      *
82001      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
82002      *
82003      * @param flattenContext Options used to control flattening.
82004      * @param value The RHS value that is the source of the property.
82005      * @param propertyName The destructuring property name.
82006      */
82007     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
82008         if (ts.isComputedPropertyName(propertyName)) {
82009             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
82010             return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
82011         }
82012         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
82013             var argumentExpression = ts.factory.cloneNode(propertyName);
82014             return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
82015         }
82016         else {
82017             var name = flattenContext.context.factory.createIdentifier(ts.idText(propertyName));
82018             return flattenContext.context.factory.createPropertyAccessExpression(value, name);
82019         }
82020     }
82021     /**
82022      * Ensures that there exists a declared identifier whose value holds the given expression.
82023      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
82024      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
82025      *
82026      * @param flattenContext Options used to control flattening.
82027      * @param value the expression whose value needs to be bound.
82028      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
82029      * false if it is necessary to always emit an identifier.
82030      * @param location The location to use for source maps and comments.
82031      */
82032     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
82033         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
82034             return value;
82035         }
82036         else {
82037             var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
82038             if (flattenContext.hoistTempVariables) {
82039                 flattenContext.context.hoistVariableDeclaration(temp);
82040                 flattenContext.emitExpression(ts.setTextRange(flattenContext.context.factory.createAssignment(temp, value), location));
82041             }
82042             else {
82043                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
82044             }
82045             return temp;
82046         }
82047     }
82048     function makeArrayBindingPattern(factory, elements) {
82049         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
82050         return factory.createArrayBindingPattern(elements);
82051     }
82052     function makeArrayAssignmentPattern(factory, elements) {
82053         return factory.createArrayLiteralExpression(ts.map(elements, factory.converters.convertToArrayAssignmentElement));
82054     }
82055     function makeObjectBindingPattern(factory, elements) {
82056         ts.Debug.assertEachNode(elements, ts.isBindingElement);
82057         return factory.createObjectBindingPattern(elements);
82058     }
82059     function makeObjectAssignmentPattern(factory, elements) {
82060         return factory.createObjectLiteralExpression(ts.map(elements, factory.converters.convertToObjectAssignmentElement));
82061     }
82062     function makeBindingElement(factory, name) {
82063         return factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
82064     }
82065     function makeAssignmentElement(name) {
82066         return name;
82067     }
82068 })(ts || (ts = {}));
82069 /*@internal*/
82070 var ts;
82071 (function (ts) {
82072     var ProcessLevel;
82073     (function (ProcessLevel) {
82074         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
82075         ProcessLevel[ProcessLevel["All"] = 1] = "All";
82076     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
82077     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
82078         // Visit the tag expression
82079         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
82080         // Build up the template arguments and the raw and cooked strings for the template.
82081         // We start out with 'undefined' for the first argument and revisit later
82082         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
82083         var templateArguments = [undefined];
82084         var cookedStrings = [];
82085         var rawStrings = [];
82086         var template = node.template;
82087         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template)) {
82088             return ts.visitEachChild(node, visitor, context);
82089         }
82090         if (ts.isNoSubstitutionTemplateLiteral(template)) {
82091             cookedStrings.push(createTemplateCooked(template));
82092             rawStrings.push(getRawLiteral(template, currentSourceFile));
82093         }
82094         else {
82095             cookedStrings.push(createTemplateCooked(template.head));
82096             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
82097             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
82098                 var templateSpan = _a[_i];
82099                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
82100                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
82101                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
82102             }
82103         }
82104         var helperCall = context.getEmitHelperFactory().createTemplateObjectHelper(ts.factory.createArrayLiteralExpression(cookedStrings), ts.factory.createArrayLiteralExpression(rawStrings));
82105         // Create a variable to cache the template object if we're in a module.
82106         // Do not do this in the global scope, as any variable we currently generate could conflict with
82107         // variables from outside of the current compilation. In the future, we can revisit this behavior.
82108         if (ts.isExternalModule(currentSourceFile)) {
82109             var tempVar = ts.factory.createUniqueName("templateObject");
82110             recordTaggedTemplateString(tempVar);
82111             templateArguments[0] = ts.factory.createLogicalOr(tempVar, ts.factory.createAssignment(tempVar, helperCall));
82112         }
82113         else {
82114             templateArguments[0] = helperCall;
82115         }
82116         return ts.factory.createCallExpression(tag, /*typeArguments*/ undefined, templateArguments);
82117     }
82118     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
82119     function createTemplateCooked(template) {
82120         return template.templateFlags ? ts.factory.createVoidZero() : ts.factory.createStringLiteral(template.text);
82121     }
82122     /**
82123      * Creates an ES5 compatible literal from an ES6 template literal.
82124      *
82125      * @param node The ES6 template literal.
82126      */
82127     function getRawLiteral(node, currentSourceFile) {
82128         // Find original source text, since we need to emit the raw strings of the tagged template.
82129         // The raw strings contain the (escaped) strings of what the user wrote.
82130         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
82131         var text = node.rawText;
82132         if (text === undefined) {
82133             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
82134             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
82135             // thus we need to remove those characters.
82136             // First template piece starts with "`", others with "}"
82137             // Last template piece ends with "`", others with "${"
82138             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
82139             text = text.substring(1, text.length - (isLast ? 1 : 2));
82140         }
82141         // Newline normalization:
82142         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
82143         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
82144         text = text.replace(/\r\n?/g, "\n");
82145         return ts.setTextRange(ts.factory.createStringLiteral(text), node);
82146     }
82147 })(ts || (ts = {}));
82148 /*@internal*/
82149 var ts;
82150 (function (ts) {
82151     /**
82152      * Indicates whether to emit type metadata in the new format.
82153      */
82154     var USE_NEW_TYPE_METADATA_FORMAT = false;
82155     var TypeScriptSubstitutionFlags;
82156     (function (TypeScriptSubstitutionFlags) {
82157         /** Enables substitutions for decorated classes. */
82158         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
82159         /** Enables substitutions for namespace exports. */
82160         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
82161         /* Enables substitutions for unqualified enum members */
82162         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
82163     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
82164     var ClassFacts;
82165     (function (ClassFacts) {
82166         ClassFacts[ClassFacts["None"] = 0] = "None";
82167         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
82168         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
82169         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
82170         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
82171         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
82172         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
82173         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
82174         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
82175         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
82176         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
82177         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
82178         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
82179     })(ClassFacts || (ClassFacts = {}));
82180     function transformTypeScript(context) {
82181         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
82182         var resolver = context.getEmitResolver();
82183         var compilerOptions = context.getCompilerOptions();
82184         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
82185         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
82186         var moduleKind = ts.getEmitModuleKind(compilerOptions);
82187         // Save the previous transformation hooks.
82188         var previousOnEmitNode = context.onEmitNode;
82189         var previousOnSubstituteNode = context.onSubstituteNode;
82190         // Set new transformation hooks.
82191         context.onEmitNode = onEmitNode;
82192         context.onSubstituteNode = onSubstituteNode;
82193         // Enable substitution for property/element access to emit const enum values.
82194         context.enableSubstitution(201 /* PropertyAccessExpression */);
82195         context.enableSubstitution(202 /* ElementAccessExpression */);
82196         // These variables contain state that changes as we descend into the tree.
82197         var currentSourceFile;
82198         var currentNamespace;
82199         var currentNamespaceContainerName;
82200         var currentLexicalScope;
82201         var currentNameScope;
82202         var currentScopeFirstDeclarationsOfName;
82203         var currentClassHasParameterProperties;
82204         /**
82205          * Keeps track of whether expression substitution has been enabled for specific edge cases.
82206          * They are persisted between each SourceFile transformation and should not be reset.
82207          */
82208         var enabledSubstitutions;
82209         /**
82210          * A map that keeps track of aliases created for classes with decorators to avoid issues
82211          * with the double-binding behavior of classes.
82212          */
82213         var classAliases;
82214         /**
82215          * Keeps track of whether we are within any containing namespaces when performing
82216          * just-in-time substitution while printing an expression identifier.
82217          */
82218         var applicableSubstitutions;
82219         return transformSourceFileOrBundle;
82220         function transformSourceFileOrBundle(node) {
82221             if (node.kind === 298 /* Bundle */) {
82222                 return transformBundle(node);
82223             }
82224             return transformSourceFile(node);
82225         }
82226         function transformBundle(node) {
82227             return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
82228                 if (prepend.kind === 300 /* InputFiles */) {
82229                     return ts.createUnparsedSourceFile(prepend, "js");
82230                 }
82231                 return prepend;
82232             }));
82233         }
82234         /**
82235          * Transform TypeScript-specific syntax in a SourceFile.
82236          *
82237          * @param node A SourceFile node.
82238          */
82239         function transformSourceFile(node) {
82240             if (node.isDeclarationFile) {
82241                 return node;
82242             }
82243             currentSourceFile = node;
82244             var visited = saveStateAndInvoke(node, visitSourceFile);
82245             ts.addEmitHelpers(visited, context.readEmitHelpers());
82246             currentSourceFile = undefined;
82247             return visited;
82248         }
82249         /**
82250          * Visits a node, saving and restoring state variables on the stack.
82251          *
82252          * @param node The node to visit.
82253          */
82254         function saveStateAndInvoke(node, f) {
82255             // Save state
82256             var savedCurrentScope = currentLexicalScope;
82257             var savedCurrentNameScope = currentNameScope;
82258             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
82259             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
82260             // Handle state changes before visiting a node.
82261             onBeforeVisitNode(node);
82262             var visited = f(node);
82263             // Restore state
82264             if (currentLexicalScope !== savedCurrentScope) {
82265                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
82266             }
82267             currentLexicalScope = savedCurrentScope;
82268             currentNameScope = savedCurrentNameScope;
82269             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
82270             return visited;
82271         }
82272         /**
82273          * Performs actions that should always occur immediately before visiting a node.
82274          *
82275          * @param node The node to visit.
82276          */
82277         function onBeforeVisitNode(node) {
82278             switch (node.kind) {
82279                 case 297 /* SourceFile */:
82280                 case 258 /* CaseBlock */:
82281                 case 257 /* ModuleBlock */:
82282                 case 230 /* Block */:
82283                     currentLexicalScope = node;
82284                     currentNameScope = undefined;
82285                     currentScopeFirstDeclarationsOfName = undefined;
82286                     break;
82287                 case 252 /* ClassDeclaration */:
82288                 case 251 /* FunctionDeclaration */:
82289                     if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
82290                         break;
82291                     }
82292                     // Record these declarations provided that they have a name.
82293                     if (node.name) {
82294                         recordEmittedDeclarationInScope(node);
82295                     }
82296                     else {
82297                         // These nodes should always have names unless they are default-exports;
82298                         // however, class declaration parsing allows for undefined names, so syntactically invalid
82299                         // programs may also have an undefined name.
82300                         ts.Debug.assert(node.kind === 252 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */));
82301                     }
82302                     if (ts.isClassDeclaration(node)) {
82303                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
82304                         currentNameScope = node;
82305                     }
82306                     break;
82307             }
82308         }
82309         /**
82310          * General-purpose node visitor.
82311          *
82312          * @param node The node to visit.
82313          */
82314         function visitor(node) {
82315             return saveStateAndInvoke(node, visitorWorker);
82316         }
82317         /**
82318          * Visits and possibly transforms any node.
82319          *
82320          * @param node The node to visit.
82321          */
82322         function visitorWorker(node) {
82323             if (node.transformFlags & 1 /* ContainsTypeScript */) {
82324                 return visitTypeScript(node);
82325             }
82326             return node;
82327         }
82328         /**
82329          * Specialized visitor that visits the immediate children of a SourceFile.
82330          *
82331          * @param node The node to visit.
82332          */
82333         function sourceElementVisitor(node) {
82334             return saveStateAndInvoke(node, sourceElementVisitorWorker);
82335         }
82336         /**
82337          * Specialized visitor that visits the immediate children of a SourceFile.
82338          *
82339          * @param node The node to visit.
82340          */
82341         function sourceElementVisitorWorker(node) {
82342             switch (node.kind) {
82343                 case 261 /* ImportDeclaration */:
82344                 case 260 /* ImportEqualsDeclaration */:
82345                 case 266 /* ExportAssignment */:
82346                 case 267 /* ExportDeclaration */:
82347                     return visitElidableStatement(node);
82348                 default:
82349                     return visitorWorker(node);
82350             }
82351         }
82352         function visitElidableStatement(node) {
82353             var parsed = ts.getParseTreeNode(node);
82354             if (parsed !== node) {
82355                 // If the node has been transformed by a `before` transformer, perform no ellision on it
82356                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
82357                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
82358                 // and will trigger debug failures when debug verbosity is turned up
82359                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
82360                     // This node contains TypeScript, so we should visit its children.
82361                     return ts.visitEachChild(node, visitor, context);
82362                 }
82363                 // Otherwise, we can just return the node
82364                 return node;
82365             }
82366             switch (node.kind) {
82367                 case 261 /* ImportDeclaration */:
82368                     return visitImportDeclaration(node);
82369                 case 260 /* ImportEqualsDeclaration */:
82370                     return visitImportEqualsDeclaration(node);
82371                 case 266 /* ExportAssignment */:
82372                     return visitExportAssignment(node);
82373                 case 267 /* ExportDeclaration */:
82374                     return visitExportDeclaration(node);
82375                 default:
82376                     ts.Debug.fail("Unhandled ellided statement");
82377             }
82378         }
82379         /**
82380          * Specialized visitor that visits the immediate children of a namespace.
82381          *
82382          * @param node The node to visit.
82383          */
82384         function namespaceElementVisitor(node) {
82385             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
82386         }
82387         /**
82388          * Specialized visitor that visits the immediate children of a namespace.
82389          *
82390          * @param node The node to visit.
82391          */
82392         function namespaceElementVisitorWorker(node) {
82393             if (node.kind === 267 /* ExportDeclaration */ ||
82394                 node.kind === 261 /* ImportDeclaration */ ||
82395                 node.kind === 262 /* ImportClause */ ||
82396                 (node.kind === 260 /* ImportEqualsDeclaration */ &&
82397                     node.moduleReference.kind === 272 /* ExternalModuleReference */)) {
82398                 // do not emit ES6 imports and exports since they are illegal inside a namespace
82399                 return undefined;
82400             }
82401             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasSyntacticModifier(node, 1 /* Export */)) {
82402                 return visitTypeScript(node);
82403             }
82404             return node;
82405         }
82406         /**
82407          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
82408          *
82409          * @param node The node to visit.
82410          */
82411         function classElementVisitor(node) {
82412             return saveStateAndInvoke(node, classElementVisitorWorker);
82413         }
82414         /**
82415          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
82416          *
82417          * @param node The node to visit.
82418          */
82419         function classElementVisitorWorker(node) {
82420             switch (node.kind) {
82421                 case 166 /* Constructor */:
82422                     return visitConstructor(node);
82423                 case 163 /* PropertyDeclaration */:
82424                     // Property declarations are not TypeScript syntax, but they must be visited
82425                     // for the decorator transformation.
82426                     return visitPropertyDeclaration(node);
82427                 case 171 /* IndexSignature */:
82428                 case 167 /* GetAccessor */:
82429                 case 168 /* SetAccessor */:
82430                 case 165 /* MethodDeclaration */:
82431                     // Fallback to the default visit behavior.
82432                     return visitorWorker(node);
82433                 case 229 /* SemicolonClassElement */:
82434                     return node;
82435                 default:
82436                     return ts.Debug.failBadSyntaxKind(node);
82437             }
82438         }
82439         function modifierVisitor(node) {
82440             if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
82441                 return undefined;
82442             }
82443             else if (currentNamespace && node.kind === 92 /* ExportKeyword */) {
82444                 return undefined;
82445             }
82446             return node;
82447         }
82448         /**
82449          * Branching visitor, visits a TypeScript syntax node.
82450          *
82451          * @param node The node to visit.
82452          */
82453         function visitTypeScript(node) {
82454             if (ts.isStatement(node) && ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
82455                 // TypeScript ambient declarations are elided, but some comments may be preserved.
82456                 // See the implementation of `getLeadingComments` in comments.ts for more details.
82457                 return factory.createNotEmittedStatement(node);
82458             }
82459             switch (node.kind) {
82460                 case 92 /* ExportKeyword */:
82461                 case 87 /* DefaultKeyword */:
82462                     // ES6 export and default modifiers are elided when inside a namespace.
82463                     return currentNamespace ? undefined : node;
82464                 case 122 /* PublicKeyword */:
82465                 case 120 /* PrivateKeyword */:
82466                 case 121 /* ProtectedKeyword */:
82467                 case 125 /* AbstractKeyword */:
82468                 case 84 /* ConstKeyword */:
82469                 case 133 /* DeclareKeyword */:
82470                 case 142 /* ReadonlyKeyword */:
82471                 // TypeScript accessibility and readonly modifiers are elided
82472                 // falls through
82473                 case 178 /* ArrayType */:
82474                 case 179 /* TupleType */:
82475                 case 180 /* OptionalType */:
82476                 case 181 /* RestType */:
82477                 case 177 /* TypeLiteral */:
82478                 case 172 /* TypePredicate */:
82479                 case 159 /* TypeParameter */:
82480                 case 128 /* AnyKeyword */:
82481                 case 152 /* UnknownKeyword */:
82482                 case 131 /* BooleanKeyword */:
82483                 case 147 /* StringKeyword */:
82484                 case 144 /* NumberKeyword */:
82485                 case 141 /* NeverKeyword */:
82486                 case 113 /* VoidKeyword */:
82487                 case 148 /* SymbolKeyword */:
82488                 case 175 /* ConstructorType */:
82489                 case 174 /* FunctionType */:
82490                 case 176 /* TypeQuery */:
82491                 case 173 /* TypeReference */:
82492                 case 182 /* UnionType */:
82493                 case 183 /* IntersectionType */:
82494                 case 184 /* ConditionalType */:
82495                 case 186 /* ParenthesizedType */:
82496                 case 187 /* ThisType */:
82497                 case 188 /* TypeOperator */:
82498                 case 189 /* IndexedAccessType */:
82499                 case 190 /* MappedType */:
82500                 case 191 /* LiteralType */:
82501                 // TypeScript type nodes are elided.
82502                 // falls through
82503                 case 171 /* IndexSignature */:
82504                 // TypeScript index signatures are elided.
82505                 // falls through
82506                 case 161 /* Decorator */:
82507                 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
82508                 // falls through
82509                 case 254 /* TypeAliasDeclaration */:
82510                     // TypeScript type-only declarations are elided.
82511                     return undefined;
82512                 case 163 /* PropertyDeclaration */:
82513                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
82514                     return visitPropertyDeclaration(node);
82515                 case 259 /* NamespaceExportDeclaration */:
82516                     // TypeScript namespace export declarations are elided.
82517                     return undefined;
82518                 case 166 /* Constructor */:
82519                     return visitConstructor(node);
82520                 case 253 /* InterfaceDeclaration */:
82521                     // TypeScript interfaces are elided, but some comments may be preserved.
82522                     // See the implementation of `getLeadingComments` in comments.ts for more details.
82523                     return factory.createNotEmittedStatement(node);
82524                 case 252 /* ClassDeclaration */:
82525                     // This may be a class declaration with TypeScript syntax extensions.
82526                     //
82527                     // TypeScript class syntax extensions include:
82528                     // - decorators
82529                     // - optional `implements` heritage clause
82530                     // - parameter property assignments in the constructor
82531                     // - index signatures
82532                     // - method overload signatures
82533                     return visitClassDeclaration(node);
82534                 case 221 /* ClassExpression */:
82535                     // This may be a class expression with TypeScript syntax extensions.
82536                     //
82537                     // TypeScript class syntax extensions include:
82538                     // - decorators
82539                     // - optional `implements` heritage clause
82540                     // - parameter property assignments in the constructor
82541                     // - index signatures
82542                     // - method overload signatures
82543                     return visitClassExpression(node);
82544                 case 286 /* HeritageClause */:
82545                     // This may be a heritage clause with TypeScript syntax extensions.
82546                     //
82547                     // TypeScript heritage clause extensions include:
82548                     // - `implements` clause
82549                     return visitHeritageClause(node);
82550                 case 223 /* ExpressionWithTypeArguments */:
82551                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
82552                     return visitExpressionWithTypeArguments(node);
82553                 case 165 /* MethodDeclaration */:
82554                     // TypeScript method declarations may have decorators, modifiers
82555                     // or type annotations.
82556                     return visitMethodDeclaration(node);
82557                 case 167 /* GetAccessor */:
82558                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
82559                     return visitGetAccessor(node);
82560                 case 168 /* SetAccessor */:
82561                     // Set Accessors can have TypeScript modifiers and type annotations.
82562                     return visitSetAccessor(node);
82563                 case 251 /* FunctionDeclaration */:
82564                     // Typescript function declarations can have modifiers, decorators, and type annotations.
82565                     return visitFunctionDeclaration(node);
82566                 case 208 /* FunctionExpression */:
82567                     // TypeScript function expressions can have modifiers and type annotations.
82568                     return visitFunctionExpression(node);
82569                 case 209 /* ArrowFunction */:
82570                     // TypeScript arrow functions can have modifiers and type annotations.
82571                     return visitArrowFunction(node);
82572                 case 160 /* Parameter */:
82573                     // This may be a parameter declaration with TypeScript syntax extensions.
82574                     //
82575                     // TypeScript parameter declaration syntax extensions include:
82576                     // - decorators
82577                     // - accessibility modifiers
82578                     // - the question mark (?) token for optional parameters
82579                     // - type annotations
82580                     // - this parameters
82581                     return visitParameter(node);
82582                 case 207 /* ParenthesizedExpression */:
82583                     // ParenthesizedExpressions are TypeScript if their expression is a
82584                     // TypeAssertion or AsExpression
82585                     return visitParenthesizedExpression(node);
82586                 case 206 /* TypeAssertionExpression */:
82587                 case 224 /* AsExpression */:
82588                     // TypeScript type assertions are removed, but their subtrees are preserved.
82589                     return visitAssertionExpression(node);
82590                 case 203 /* CallExpression */:
82591                     return visitCallExpression(node);
82592                 case 204 /* NewExpression */:
82593                     return visitNewExpression(node);
82594                 case 205 /* TaggedTemplateExpression */:
82595                     return visitTaggedTemplateExpression(node);
82596                 case 225 /* NonNullExpression */:
82597                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
82598                     return visitNonNullExpression(node);
82599                 case 255 /* EnumDeclaration */:
82600                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
82601                     return visitEnumDeclaration(node);
82602                 case 232 /* VariableStatement */:
82603                     // TypeScript namespace exports for variable statements must be transformed.
82604                     return visitVariableStatement(node);
82605                 case 249 /* VariableDeclaration */:
82606                     return visitVariableDeclaration(node);
82607                 case 256 /* ModuleDeclaration */:
82608                     // TypeScript namespace declarations must be transformed.
82609                     return visitModuleDeclaration(node);
82610                 case 260 /* ImportEqualsDeclaration */:
82611                     // TypeScript namespace or external module import.
82612                     return visitImportEqualsDeclaration(node);
82613                 case 274 /* JsxSelfClosingElement */:
82614                     return visitJsxSelfClosingElement(node);
82615                 case 275 /* JsxOpeningElement */:
82616                     return visitJsxJsxOpeningElement(node);
82617                 default:
82618                     // node contains some other TypeScript syntax
82619                     return ts.visitEachChild(node, visitor, context);
82620             }
82621         }
82622         function visitSourceFile(node) {
82623             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
82624                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
82625                 !ts.isJsonSourceFile(node);
82626             return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
82627         }
82628         /**
82629          * Tests whether we should emit a __decorate call for a class declaration.
82630          */
82631         function shouldEmitDecorateCallForClass(node) {
82632             if (node.decorators && node.decorators.length > 0) {
82633                 return true;
82634             }
82635             var constructor = ts.getFirstConstructorWithBody(node);
82636             if (constructor) {
82637                 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
82638             }
82639             return false;
82640         }
82641         /**
82642          * Tests whether we should emit a __decorate call for a parameter declaration.
82643          */
82644         function shouldEmitDecorateCallForParameter(parameter) {
82645             return parameter.decorators !== undefined && parameter.decorators.length > 0;
82646         }
82647         function getClassFacts(node, staticProperties) {
82648             var facts = 0 /* None */;
82649             if (ts.some(staticProperties))
82650                 facts |= 1 /* HasStaticInitializedProperties */;
82651             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
82652             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */)
82653                 facts |= 64 /* IsDerivedClass */;
82654             if (shouldEmitDecorateCallForClass(node))
82655                 facts |= 2 /* HasConstructorDecorators */;
82656             if (ts.childIsDecorated(node))
82657                 facts |= 4 /* HasMemberDecorators */;
82658             if (isExportOfNamespace(node))
82659                 facts |= 8 /* IsExportOfNamespace */;
82660             else if (isDefaultExternalModuleExport(node))
82661                 facts |= 32 /* IsDefaultExternalExport */;
82662             else if (isNamedExternalModuleExport(node))
82663                 facts |= 16 /* IsNamedExternalExport */;
82664             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
82665                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
82666             return facts;
82667         }
82668         function hasTypeScriptClassSyntax(node) {
82669             return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
82670         }
82671         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
82672             return ts.some(node.decorators)
82673                 || ts.some(node.typeParameters)
82674                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
82675                 || ts.some(node.members, hasTypeScriptClassSyntax);
82676         }
82677         function visitClassDeclaration(node) {
82678             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* Export */))) {
82679                 return ts.visitEachChild(node, visitor, context);
82680             }
82681             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
82682             var facts = getClassFacts(node, staticProperties);
82683             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
82684                 context.startLexicalEnvironment();
82685             }
82686             var name = node.name || (facts & 5 /* NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined);
82687             var classStatement = facts & 2 /* HasConstructorDecorators */
82688                 ? createClassDeclarationHeadWithDecorators(node, name)
82689                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
82690             var statements = [classStatement];
82691             // Write any decorators of the node.
82692             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
82693             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
82694             addConstructorDecorationStatement(statements, node);
82695             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
82696                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
82697                 // 'es2015' transformer can properly nest static initializers and decorators. The result
82698                 // looks something like:
82699                 //
82700                 //  var C = function () {
82701                 //      class C {
82702                 //      }
82703                 //      C.static_prop = 1;
82704                 //      return C;
82705                 //  }();
82706                 //
82707                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
82708                 var localName = factory.getInternalName(node);
82709                 // The following partially-emitted expression exists purely to align our sourcemap
82710                 // emit with the original emitter.
82711                 var outer = factory.createPartiallyEmittedExpression(localName);
82712                 ts.setTextRangeEnd(outer, closingBraceLocation.end);
82713                 ts.setEmitFlags(outer, 1536 /* NoComments */);
82714                 var statement = factory.createReturnStatement(outer);
82715                 ts.setTextRangePos(statement, closingBraceLocation.pos);
82716                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
82717                 statements.push(statement);
82718                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
82719                 var iife = factory.createImmediatelyInvokedArrowFunction(statements);
82720                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
82721                 var varStatement = factory.createVariableStatement(
82722                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
82723                     factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
82724                     /*exclamationToken*/ undefined, 
82725                     /*type*/ undefined, iife)
82726                 ]));
82727                 ts.setOriginalNode(varStatement, node);
82728                 ts.setCommentRange(varStatement, node);
82729                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
82730                 ts.startOnNewLine(varStatement);
82731                 statements = [varStatement];
82732             }
82733             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
82734             // Otherwise, if the class was exported at the top level and was decorated, emit an export
82735             // declaration or export default for the class.
82736             if (facts & 8 /* IsExportOfNamespace */) {
82737                 addExportMemberAssignment(statements, node);
82738             }
82739             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
82740                 if (facts & 32 /* IsDefaultExternalExport */) {
82741                     statements.push(factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
82742                 }
82743                 else if (facts & 16 /* IsNamedExternalExport */) {
82744                     statements.push(factory.createExternalModuleExport(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
82745                 }
82746             }
82747             if (statements.length > 1) {
82748                 // Add a DeclarationMarker as a marker for the end of the declaration
82749                 statements.push(factory.createEndOfDeclarationMarker(node));
82750                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
82751             }
82752             return ts.singleOrMany(statements);
82753         }
82754         /**
82755          * Transforms a non-decorated class declaration and appends the resulting statements.
82756          *
82757          * @param node A ClassDeclaration node.
82758          * @param name The name of the class.
82759          * @param facts Precomputed facts about the class.
82760          */
82761         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
82762             //  ${modifiers} class ${name} ${heritageClauses} {
82763             //      ${members}
82764             //  }
82765             // we do not emit modifiers on the declaration if we are emitting an IIFE
82766             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
82767                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
82768                 : undefined;
82769             var classDeclaration = factory.createClassDeclaration(
82770             /*decorators*/ undefined, modifiers, name, 
82771             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
82772             // To better align with the old emitter, we should not emit a trailing source map
82773             // entry if the class has static properties.
82774             var emitFlags = ts.getEmitFlags(node);
82775             if (facts & 1 /* HasStaticInitializedProperties */) {
82776                 emitFlags |= 32 /* NoTrailingSourceMap */;
82777             }
82778             ts.setTextRange(classDeclaration, node);
82779             ts.setOriginalNode(classDeclaration, node);
82780             ts.setEmitFlags(classDeclaration, emitFlags);
82781             return classDeclaration;
82782         }
82783         /**
82784          * Transforms a decorated class declaration and appends the resulting statements. If
82785          * the class requires an alias to avoid issues with double-binding, the alias is returned.
82786          */
82787         function createClassDeclarationHeadWithDecorators(node, name) {
82788             // When we emit an ES6 class that has a class decorator, we must tailor the
82789             // emit to certain specific cases.
82790             //
82791             // In the simplest case, we emit the class declaration as a let declaration, and
82792             // evaluate decorators after the close of the class body:
82793             //
82794             //  [Example 1]
82795             //  ---------------------------------------------------------------------
82796             //  TypeScript                      | Javascript
82797             //  ---------------------------------------------------------------------
82798             //  @dec                            | let C = class C {
82799             //  class C {                       | }
82800             //  }                               | C = __decorate([dec], C);
82801             //  ---------------------------------------------------------------------
82802             //  @dec                            | let C = class C {
82803             //  export class C {                | }
82804             //  }                               | C = __decorate([dec], C);
82805             //                                  | export { C };
82806             //  ---------------------------------------------------------------------
82807             //
82808             // If a class declaration contains a reference to itself *inside* of the class body,
82809             // this introduces two bindings to the class: One outside of the class body, and one
82810             // inside of the class body. If we apply decorators as in [Example 1] above, there
82811             // is the possibility that the decorator `dec` will return a new value for the
82812             // constructor, which would result in the binding inside of the class no longer
82813             // pointing to the same reference as the binding outside of the class.
82814             //
82815             // As a result, we must instead rewrite all references to the class *inside* of the
82816             // class body to instead point to a local temporary alias for the class:
82817             //
82818             //  [Example 2]
82819             //  ---------------------------------------------------------------------
82820             //  TypeScript                      | Javascript
82821             //  ---------------------------------------------------------------------
82822             //  @dec                            | let C = C_1 = class C {
82823             //  class C {                       |   static x() { return C_1.y; }
82824             //    static x() { return C.y; }    | }
82825             //    static y = 1;                 | C.y = 1;
82826             //  }                               | C = C_1 = __decorate([dec], C);
82827             //                                  | var C_1;
82828             //  ---------------------------------------------------------------------
82829             //  @dec                            | let C = class C {
82830             //  export class C {                |   static x() { return C_1.y; }
82831             //    static x() { return C.y; }    | }
82832             //    static y = 1;                 | C.y = 1;
82833             //  }                               | C = C_1 = __decorate([dec], C);
82834             //                                  | export { C };
82835             //                                  | var C_1;
82836             //  ---------------------------------------------------------------------
82837             //
82838             // If a class declaration is the default export of a module, we instead emit
82839             // the export after the decorated declaration:
82840             //
82841             //  [Example 3]
82842             //  ---------------------------------------------------------------------
82843             //  TypeScript                      | Javascript
82844             //  ---------------------------------------------------------------------
82845             //  @dec                            | let default_1 = class {
82846             //  export default class {          | }
82847             //  }                               | default_1 = __decorate([dec], default_1);
82848             //                                  | export default default_1;
82849             //  ---------------------------------------------------------------------
82850             //  @dec                            | let C = class C {
82851             //  export default class C {        | }
82852             //  }                               | C = __decorate([dec], C);
82853             //                                  | export default C;
82854             //  ---------------------------------------------------------------------
82855             //
82856             // If the class declaration is the default export and a reference to itself
82857             // inside of the class body, we must emit both an alias for the class *and*
82858             // move the export after the declaration:
82859             //
82860             //  [Example 4]
82861             //  ---------------------------------------------------------------------
82862             //  TypeScript                      | Javascript
82863             //  ---------------------------------------------------------------------
82864             //  @dec                            | let C = class C {
82865             //  export default class C {        |   static x() { return C_1.y; }
82866             //    static x() { return C.y; }    | }
82867             //    static y = 1;                 | C.y = 1;
82868             //  }                               | C = C_1 = __decorate([dec], C);
82869             //                                  | export default C;
82870             //                                  | var C_1;
82871             //  ---------------------------------------------------------------------
82872             //
82873             var location = ts.moveRangePastDecorators(node);
82874             var classAlias = getClassAliasIfNeeded(node);
82875             var declName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
82876             //  ... = class ${name} ${heritageClauses} {
82877             //      ${members}
82878             //  }
82879             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
82880             var members = transformClassMembers(node);
82881             var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
82882             ts.setOriginalNode(classExpression, node);
82883             ts.setTextRange(classExpression, location);
82884             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
82885             //                                         or decoratedClassAlias if the class contain self-reference.
82886             var statement = factory.createVariableStatement(
82887             /*modifiers*/ undefined, factory.createVariableDeclarationList([
82888                 factory.createVariableDeclaration(declName, 
82889                 /*exclamationToken*/ undefined, 
82890                 /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression)
82891             ], 1 /* Let */));
82892             ts.setOriginalNode(statement, node);
82893             ts.setTextRange(statement, location);
82894             ts.setCommentRange(statement, node);
82895             return statement;
82896         }
82897         function visitClassExpression(node) {
82898             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
82899                 return ts.visitEachChild(node, visitor, context);
82900             }
82901             var classExpression = factory.createClassExpression(
82902             /*decorators*/ undefined, 
82903             /*modifiers*/ undefined, node.name, 
82904             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
82905             ts.setOriginalNode(classExpression, node);
82906             ts.setTextRange(classExpression, node);
82907             return classExpression;
82908         }
82909         /**
82910          * Transforms the members of a class.
82911          *
82912          * @param node The current class.
82913          */
82914         function transformClassMembers(node) {
82915             var members = [];
82916             var constructor = ts.getFirstConstructorWithBody(node);
82917             var parametersWithPropertyAssignments = constructor &&
82918                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
82919             if (parametersWithPropertyAssignments) {
82920                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
82921                     var parameter = parametersWithPropertyAssignments_1[_i];
82922                     if (ts.isIdentifier(parameter.name)) {
82923                         members.push(ts.setOriginalNode(factory.createPropertyDeclaration(
82924                         /*decorators*/ undefined, 
82925                         /*modifiers*/ undefined, parameter.name, 
82926                         /*questionOrExclamationToken*/ undefined, 
82927                         /*type*/ undefined, 
82928                         /*initializer*/ undefined), parameter));
82929                     }
82930                 }
82931             }
82932             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
82933             return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
82934         }
82935         /**
82936          * Gets either the static or instance members of a class that are decorated, or have
82937          * parameters that are decorated.
82938          *
82939          * @param node The class containing the member.
82940          * @param isStatic A value indicating whether to retrieve static or instance members of
82941          *                 the class.
82942          */
82943         function getDecoratedClassElements(node, isStatic) {
82944             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
82945         }
82946         /**
82947          * Determines whether a class member is a static member of a class that is decorated, or
82948          * has parameters that are decorated.
82949          *
82950          * @param member The class member.
82951          */
82952         function isStaticDecoratedClassElement(member, parent) {
82953             return isDecoratedClassElement(member, /*isStatic*/ true, parent);
82954         }
82955         /**
82956          * Determines whether a class member is an instance member of a class that is decorated,
82957          * or has parameters that are decorated.
82958          *
82959          * @param member The class member.
82960          */
82961         function isInstanceDecoratedClassElement(member, parent) {
82962             return isDecoratedClassElement(member, /*isStatic*/ false, parent);
82963         }
82964         /**
82965          * Determines whether a class member is either a static or an instance member of a class
82966          * that is decorated, or has parameters that are decorated.
82967          *
82968          * @param member The class member.
82969          */
82970         function isDecoratedClassElement(member, isStatic, parent) {
82971             return ts.nodeOrChildIsDecorated(member, parent)
82972                 && isStatic === ts.hasSyntacticModifier(member, 32 /* Static */);
82973         }
82974         /**
82975          * Gets an array of arrays of decorators for the parameters of a function-like node.
82976          * The offset into the result array should correspond to the offset of the parameter.
82977          *
82978          * @param node The function-like node.
82979          */
82980         function getDecoratorsOfParameters(node) {
82981             var decorators;
82982             if (node) {
82983                 var parameters = node.parameters;
82984                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
82985                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
82986                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
82987                 for (var i = 0; i < numParameters; i++) {
82988                     var parameter = parameters[i + firstParameterOffset];
82989                     if (decorators || parameter.decorators) {
82990                         if (!decorators) {
82991                             decorators = new Array(numParameters);
82992                         }
82993                         decorators[i] = parameter.decorators;
82994                     }
82995                 }
82996             }
82997             return decorators;
82998         }
82999         /**
83000          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
83001          * parameters of the constructor of the class.
83002          *
83003          * @param node The class node.
83004          */
83005         function getAllDecoratorsOfConstructor(node) {
83006             var decorators = node.decorators;
83007             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
83008             if (!decorators && !parameters) {
83009                 return undefined;
83010             }
83011             return {
83012                 decorators: decorators,
83013                 parameters: parameters
83014             };
83015         }
83016         /**
83017          * Gets an AllDecorators object containing the decorators for the member and its parameters.
83018          *
83019          * @param node The class node that contains the member.
83020          * @param member The class member.
83021          */
83022         function getAllDecoratorsOfClassElement(node, member) {
83023             switch (member.kind) {
83024                 case 167 /* GetAccessor */:
83025                 case 168 /* SetAccessor */:
83026                     return getAllDecoratorsOfAccessors(node, member);
83027                 case 165 /* MethodDeclaration */:
83028                     return getAllDecoratorsOfMethod(member);
83029                 case 163 /* PropertyDeclaration */:
83030                     return getAllDecoratorsOfProperty(member);
83031                 default:
83032                     return undefined;
83033             }
83034         }
83035         /**
83036          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
83037          *
83038          * @param node The class node that contains the accessor.
83039          * @param accessor The class accessor member.
83040          */
83041         function getAllDecoratorsOfAccessors(node, accessor) {
83042             if (!accessor.body) {
83043                 return undefined;
83044             }
83045             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
83046             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
83047             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
83048                 return undefined;
83049             }
83050             var decorators = firstAccessorWithDecorators.decorators;
83051             var parameters = getDecoratorsOfParameters(setAccessor);
83052             if (!decorators && !parameters) {
83053                 return undefined;
83054             }
83055             return { decorators: decorators, parameters: parameters };
83056         }
83057         /**
83058          * Gets an AllDecorators object containing the decorators for the method and its parameters.
83059          *
83060          * @param method The class method member.
83061          */
83062         function getAllDecoratorsOfMethod(method) {
83063             if (!method.body) {
83064                 return undefined;
83065             }
83066             var decorators = method.decorators;
83067             var parameters = getDecoratorsOfParameters(method);
83068             if (!decorators && !parameters) {
83069                 return undefined;
83070             }
83071             return { decorators: decorators, parameters: parameters };
83072         }
83073         /**
83074          * Gets an AllDecorators object containing the decorators for the property.
83075          *
83076          * @param property The class property member.
83077          */
83078         function getAllDecoratorsOfProperty(property) {
83079             var decorators = property.decorators;
83080             if (!decorators) {
83081                 return undefined;
83082             }
83083             return { decorators: decorators };
83084         }
83085         /**
83086          * Transforms all of the decorators for a declaration into an array of expressions.
83087          *
83088          * @param node The declaration node.
83089          * @param allDecorators An object containing all of the decorators for the declaration.
83090          */
83091         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
83092             if (!allDecorators) {
83093                 return undefined;
83094             }
83095             var decoratorExpressions = [];
83096             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
83097             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
83098             addTypeMetadata(node, container, decoratorExpressions);
83099             return decoratorExpressions;
83100         }
83101         /**
83102          * Generates statements used to apply decorators to either the static or instance members
83103          * of a class.
83104          *
83105          * @param node The class node.
83106          * @param isStatic A value indicating whether to generate statements for static or
83107          *                 instance members.
83108          */
83109         function addClassElementDecorationStatements(statements, node, isStatic) {
83110             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
83111         }
83112         /**
83113          * Generates expressions used to apply decorators to either the static or instance members
83114          * of a class.
83115          *
83116          * @param node The class node.
83117          * @param isStatic A value indicating whether to generate expressions for static or
83118          *                 instance members.
83119          */
83120         function generateClassElementDecorationExpressions(node, isStatic) {
83121             var members = getDecoratedClassElements(node, isStatic);
83122             var expressions;
83123             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
83124                 var member = members_6[_i];
83125                 var expression = generateClassElementDecorationExpression(node, member);
83126                 if (expression) {
83127                     if (!expressions) {
83128                         expressions = [expression];
83129                     }
83130                     else {
83131                         expressions.push(expression);
83132                     }
83133                 }
83134             }
83135             return expressions;
83136         }
83137         /**
83138          * Generates an expression used to evaluate class element decorators at runtime.
83139          *
83140          * @param node The class node that contains the member.
83141          * @param member The class member.
83142          */
83143         function generateClassElementDecorationExpression(node, member) {
83144             var allDecorators = getAllDecoratorsOfClassElement(node, member);
83145             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
83146             if (!decoratorExpressions) {
83147                 return undefined;
83148             }
83149             // Emit the call to __decorate. Given the following:
83150             //
83151             //   class C {
83152             //     @dec method(@dec2 x) {}
83153             //     @dec get accessor() {}
83154             //     @dec prop;
83155             //   }
83156             //
83157             // The emit for a method is:
83158             //
83159             //   __decorate([
83160             //       dec,
83161             //       __param(0, dec2),
83162             //       __metadata("design:type", Function),
83163             //       __metadata("design:paramtypes", [Object]),
83164             //       __metadata("design:returntype", void 0)
83165             //   ], C.prototype, "method", null);
83166             //
83167             // The emit for an accessor is:
83168             //
83169             //   __decorate([
83170             //       dec
83171             //   ], C.prototype, "accessor", null);
83172             //
83173             // The emit for a property is:
83174             //
83175             //   __decorate([
83176             //       dec
83177             //   ], C.prototype, "prop");
83178             //
83179             var prefix = getClassMemberPrefix(node, member);
83180             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
83181             var descriptor = languageVersion > 0 /* ES3 */
83182                 ? member.kind === 163 /* PropertyDeclaration */
83183                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
83184                     // should not invoke `Object.getOwnPropertyDescriptor`.
83185                     ? factory.createVoidZero()
83186                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
83187                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
83188                     : factory.createNull()
83189                 : undefined;
83190             var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor);
83191             ts.setTextRange(helper, ts.moveRangePastDecorators(member));
83192             ts.setEmitFlags(helper, 1536 /* NoComments */);
83193             return helper;
83194         }
83195         /**
83196          * Generates a __decorate helper call for a class constructor.
83197          *
83198          * @param node The class node.
83199          */
83200         function addConstructorDecorationStatement(statements, node) {
83201             var expression = generateConstructorDecorationExpression(node);
83202             if (expression) {
83203                 statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node));
83204             }
83205         }
83206         /**
83207          * Generates a __decorate helper call for a class constructor.
83208          *
83209          * @param node The class node.
83210          */
83211         function generateConstructorDecorationExpression(node) {
83212             var allDecorators = getAllDecoratorsOfConstructor(node);
83213             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
83214             if (!decoratorExpressions) {
83215                 return undefined;
83216             }
83217             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
83218             var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
83219             var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName);
83220             var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate);
83221             ts.setEmitFlags(expression, 1536 /* NoComments */);
83222             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
83223             return expression;
83224         }
83225         /**
83226          * Transforms a decorator into an expression.
83227          *
83228          * @param decorator The decorator node.
83229          */
83230         function transformDecorator(decorator) {
83231             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
83232         }
83233         /**
83234          * Transforms the decorators of a parameter.
83235          *
83236          * @param decorators The decorators for the parameter at the provided offset.
83237          * @param parameterOffset The offset of the parameter.
83238          */
83239         function transformDecoratorsOfParameter(decorators, parameterOffset) {
83240             var expressions;
83241             if (decorators) {
83242                 expressions = [];
83243                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
83244                     var decorator = decorators_1[_i];
83245                     var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset);
83246                     ts.setTextRange(helper, decorator.expression);
83247                     ts.setEmitFlags(helper, 1536 /* NoComments */);
83248                     expressions.push(helper);
83249                 }
83250             }
83251             return expressions;
83252         }
83253         /**
83254          * Adds optional type metadata for a declaration.
83255          *
83256          * @param node The declaration node.
83257          * @param decoratorExpressions The destination array to which to add new decorator expressions.
83258          */
83259         function addTypeMetadata(node, container, decoratorExpressions) {
83260             if (USE_NEW_TYPE_METADATA_FORMAT) {
83261                 addNewTypeMetadata(node, container, decoratorExpressions);
83262             }
83263             else {
83264                 addOldTypeMetadata(node, container, decoratorExpressions);
83265             }
83266         }
83267         function addOldTypeMetadata(node, container, decoratorExpressions) {
83268             if (compilerOptions.emitDecoratorMetadata) {
83269                 if (shouldAddTypeMetadata(node)) {
83270                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node)));
83271                 }
83272                 if (shouldAddParamTypesMetadata(node)) {
83273                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container)));
83274                 }
83275                 if (shouldAddReturnTypeMetadata(node)) {
83276                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node)));
83277                 }
83278             }
83279         }
83280         function addNewTypeMetadata(node, container, decoratorExpressions) {
83281             if (compilerOptions.emitDecoratorMetadata) {
83282                 var properties = void 0;
83283                 if (shouldAddTypeMetadata(node)) {
83284                     (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
83285                 }
83286                 if (shouldAddParamTypesMetadata(node)) {
83287                     (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
83288                 }
83289                 if (shouldAddReturnTypeMetadata(node)) {
83290                     (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
83291                 }
83292                 if (properties) {
83293                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)));
83294                 }
83295             }
83296         }
83297         /**
83298          * Determines whether to emit the "design:type" metadata based on the node's kind.
83299          * The caller should have already tested whether the node has decorators and whether the
83300          * emitDecoratorMetadata compiler option is set.
83301          *
83302          * @param node The node to test.
83303          */
83304         function shouldAddTypeMetadata(node) {
83305             var kind = node.kind;
83306             return kind === 165 /* MethodDeclaration */
83307                 || kind === 167 /* GetAccessor */
83308                 || kind === 168 /* SetAccessor */
83309                 || kind === 163 /* PropertyDeclaration */;
83310         }
83311         /**
83312          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
83313          * The caller should have already tested whether the node has decorators and whether the
83314          * emitDecoratorMetadata compiler option is set.
83315          *
83316          * @param node The node to test.
83317          */
83318         function shouldAddReturnTypeMetadata(node) {
83319             return node.kind === 165 /* MethodDeclaration */;
83320         }
83321         /**
83322          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
83323          * The caller should have already tested whether the node has decorators and whether the
83324          * emitDecoratorMetadata compiler option is set.
83325          *
83326          * @param node The node to test.
83327          */
83328         function shouldAddParamTypesMetadata(node) {
83329             switch (node.kind) {
83330                 case 252 /* ClassDeclaration */:
83331                 case 221 /* ClassExpression */:
83332                     return ts.getFirstConstructorWithBody(node) !== undefined;
83333                 case 165 /* MethodDeclaration */:
83334                 case 167 /* GetAccessor */:
83335                 case 168 /* SetAccessor */:
83336                     return true;
83337             }
83338             return false;
83339         }
83340         function getAccessorTypeNode(node) {
83341             var accessors = resolver.getAllAccessorDeclarations(node);
83342             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
83343                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
83344         }
83345         /**
83346          * Serializes the type of a node for use with decorator type metadata.
83347          *
83348          * @param node The node that should have its type serialized.
83349          */
83350         function serializeTypeOfNode(node) {
83351             switch (node.kind) {
83352                 case 163 /* PropertyDeclaration */:
83353                 case 160 /* Parameter */:
83354                     return serializeTypeNode(node.type);
83355                 case 168 /* SetAccessor */:
83356                 case 167 /* GetAccessor */:
83357                     return serializeTypeNode(getAccessorTypeNode(node));
83358                 case 252 /* ClassDeclaration */:
83359                 case 221 /* ClassExpression */:
83360                 case 165 /* MethodDeclaration */:
83361                     return factory.createIdentifier("Function");
83362                 default:
83363                     return factory.createVoidZero();
83364             }
83365         }
83366         /**
83367          * Serializes the types of the parameters of a node for use with decorator type metadata.
83368          *
83369          * @param node The node that should have its parameter types serialized.
83370          */
83371         function serializeParameterTypesOfNode(node, container) {
83372             var valueDeclaration = ts.isClassLike(node)
83373                 ? ts.getFirstConstructorWithBody(node)
83374                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
83375                     ? node
83376                     : undefined;
83377             var expressions = [];
83378             if (valueDeclaration) {
83379                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
83380                 var numParameters = parameters.length;
83381                 for (var i = 0; i < numParameters; i++) {
83382                     var parameter = parameters[i];
83383                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
83384                         continue;
83385                     }
83386                     if (parameter.dotDotDotToken) {
83387                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
83388                     }
83389                     else {
83390                         expressions.push(serializeTypeOfNode(parameter));
83391                     }
83392                 }
83393             }
83394             return factory.createArrayLiteralExpression(expressions);
83395         }
83396         function getParametersOfDecoratedDeclaration(node, container) {
83397             if (container && node.kind === 167 /* GetAccessor */) {
83398                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
83399                 if (setAccessor) {
83400                     return setAccessor.parameters;
83401                 }
83402             }
83403             return node.parameters;
83404         }
83405         /**
83406          * Serializes the return type of a node for use with decorator type metadata.
83407          *
83408          * @param node The node that should have its return type serialized.
83409          */
83410         function serializeReturnTypeOfNode(node) {
83411             if (ts.isFunctionLike(node) && node.type) {
83412                 return serializeTypeNode(node.type);
83413             }
83414             else if (ts.isAsyncFunction(node)) {
83415                 return factory.createIdentifier("Promise");
83416             }
83417             return factory.createVoidZero();
83418         }
83419         /**
83420          * Serializes a type node for use with decorator type metadata.
83421          *
83422          * Types are serialized in the following fashion:
83423          * - Void types point to "undefined" (e.g. "void 0")
83424          * - Function and Constructor types point to the global "Function" constructor.
83425          * - Interface types with a call or construct signature types point to the global
83426          *   "Function" constructor.
83427          * - Array and Tuple types point to the global "Array" constructor.
83428          * - Type predicates and booleans point to the global "Boolean" constructor.
83429          * - String literal types and strings point to the global "String" constructor.
83430          * - Enum and number types point to the global "Number" constructor.
83431          * - Symbol types point to the global "Symbol" constructor.
83432          * - Type references to classes (or class-like variables) point to the constructor for the class.
83433          * - Anything else points to the global "Object" constructor.
83434          *
83435          * @param node The type node to serialize.
83436          */
83437         function serializeTypeNode(node) {
83438             if (node === undefined) {
83439                 return factory.createIdentifier("Object");
83440             }
83441             switch (node.kind) {
83442                 case 113 /* VoidKeyword */:
83443                 case 150 /* UndefinedKeyword */:
83444                 case 141 /* NeverKeyword */:
83445                     return factory.createVoidZero();
83446                 case 186 /* ParenthesizedType */:
83447                     return serializeTypeNode(node.type);
83448                 case 174 /* FunctionType */:
83449                 case 175 /* ConstructorType */:
83450                     return factory.createIdentifier("Function");
83451                 case 178 /* ArrayType */:
83452                 case 179 /* TupleType */:
83453                     return factory.createIdentifier("Array");
83454                 case 172 /* TypePredicate */:
83455                 case 131 /* BooleanKeyword */:
83456                     return factory.createIdentifier("Boolean");
83457                 case 147 /* StringKeyword */:
83458                     return factory.createIdentifier("String");
83459                 case 145 /* ObjectKeyword */:
83460                     return factory.createIdentifier("Object");
83461                 case 191 /* LiteralType */:
83462                     switch (node.literal.kind) {
83463                         case 10 /* StringLiteral */:
83464                         case 14 /* NoSubstitutionTemplateLiteral */:
83465                             return factory.createIdentifier("String");
83466                         case 214 /* PrefixUnaryExpression */:
83467                         case 8 /* NumericLiteral */:
83468                             return factory.createIdentifier("Number");
83469                         case 9 /* BigIntLiteral */:
83470                             return getGlobalBigIntNameWithFallback();
83471                         case 109 /* TrueKeyword */:
83472                         case 94 /* FalseKeyword */:
83473                             return factory.createIdentifier("Boolean");
83474                         case 103 /* NullKeyword */:
83475                             return factory.createVoidZero();
83476                         default:
83477                             return ts.Debug.failBadSyntaxKind(node.literal);
83478                     }
83479                 case 144 /* NumberKeyword */:
83480                     return factory.createIdentifier("Number");
83481                 case 155 /* BigIntKeyword */:
83482                     return getGlobalBigIntNameWithFallback();
83483                 case 148 /* SymbolKeyword */:
83484                     return languageVersion < 2 /* ES2015 */
83485                         ? getGlobalSymbolNameWithFallback()
83486                         : factory.createIdentifier("Symbol");
83487                 case 173 /* TypeReference */:
83488                     return serializeTypeReferenceNode(node);
83489                 case 183 /* IntersectionType */:
83490                 case 182 /* UnionType */:
83491                     return serializeTypeList(node.types);
83492                 case 184 /* ConditionalType */:
83493                     return serializeTypeList([node.trueType, node.falseType]);
83494                 case 188 /* TypeOperator */:
83495                     if (node.operator === 142 /* ReadonlyKeyword */) {
83496                         return serializeTypeNode(node.type);
83497                     }
83498                     break;
83499                 case 176 /* TypeQuery */:
83500                 case 189 /* IndexedAccessType */:
83501                 case 190 /* MappedType */:
83502                 case 177 /* TypeLiteral */:
83503                 case 128 /* AnyKeyword */:
83504                 case 152 /* UnknownKeyword */:
83505                 case 187 /* ThisType */:
83506                 case 195 /* ImportType */:
83507                     break;
83508                 // handle JSDoc types from an invalid parse
83509                 case 303 /* JSDocAllType */:
83510                 case 304 /* JSDocUnknownType */:
83511                 case 308 /* JSDocFunctionType */:
83512                 case 309 /* JSDocVariadicType */:
83513                 case 310 /* JSDocNamepathType */:
83514                     break;
83515                 case 305 /* JSDocNullableType */:
83516                 case 306 /* JSDocNonNullableType */:
83517                 case 307 /* JSDocOptionalType */:
83518                     return serializeTypeNode(node.type);
83519                 default:
83520                     return ts.Debug.failBadSyntaxKind(node);
83521             }
83522             return factory.createIdentifier("Object");
83523         }
83524         function serializeTypeList(types) {
83525             // Note when updating logic here also update getEntityNameForDecoratorMetadata
83526             // so that aliases can be marked as referenced
83527             var serializedUnion;
83528             for (var _i = 0, types_22 = types; _i < types_22.length; _i++) {
83529                 var typeNode = types_22[_i];
83530                 while (typeNode.kind === 186 /* ParenthesizedType */) {
83531                     typeNode = typeNode.type; // Skip parens if need be
83532                 }
83533                 if (typeNode.kind === 141 /* NeverKeyword */) {
83534                     continue; // Always elide `never` from the union/intersection if possible
83535                 }
83536                 if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) {
83537                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
83538                 }
83539                 var serializedIndividual = serializeTypeNode(typeNode);
83540                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
83541                     // One of the individual is global object, return immediately
83542                     return serializedIndividual;
83543                 }
83544                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
83545                 // anything more complex and we will just default to Object
83546                 else if (serializedUnion) {
83547                     // Different types
83548                     if (!ts.isIdentifier(serializedUnion) ||
83549                         !ts.isIdentifier(serializedIndividual) ||
83550                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
83551                         return factory.createIdentifier("Object");
83552                     }
83553                 }
83554                 else {
83555                     // Initialize the union type
83556                     serializedUnion = serializedIndividual;
83557                 }
83558             }
83559             // If we were able to find common type, use it
83560             return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
83561         }
83562         /**
83563          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
83564          * decorator type metadata.
83565          *
83566          * @param node The type reference node.
83567          */
83568         function serializeTypeReferenceNode(node) {
83569             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
83570             switch (kind) {
83571                 case ts.TypeReferenceSerializationKind.Unknown:
83572                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
83573                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
83574                         return factory.createIdentifier("Object");
83575                     }
83576                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
83577                     var temp = factory.createTempVariable(hoistVariableDeclaration);
83578                     return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), 
83579                     /*questionToken*/ undefined, temp, 
83580                     /*colonToken*/ undefined, factory.createIdentifier("Object"));
83581                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
83582                     return serializeEntityNameAsExpression(node.typeName);
83583                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
83584                     return factory.createVoidZero();
83585                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
83586                     return getGlobalBigIntNameWithFallback();
83587                 case ts.TypeReferenceSerializationKind.BooleanType:
83588                     return factory.createIdentifier("Boolean");
83589                 case ts.TypeReferenceSerializationKind.NumberLikeType:
83590                     return factory.createIdentifier("Number");
83591                 case ts.TypeReferenceSerializationKind.StringLikeType:
83592                     return factory.createIdentifier("String");
83593                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
83594                     return factory.createIdentifier("Array");
83595                 case ts.TypeReferenceSerializationKind.ESSymbolType:
83596                     return languageVersion < 2 /* ES2015 */
83597                         ? getGlobalSymbolNameWithFallback()
83598                         : factory.createIdentifier("Symbol");
83599                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
83600                     return factory.createIdentifier("Function");
83601                 case ts.TypeReferenceSerializationKind.Promise:
83602                     return factory.createIdentifier("Promise");
83603                 case ts.TypeReferenceSerializationKind.ObjectType:
83604                     return factory.createIdentifier("Object");
83605                 default:
83606                     return ts.Debug.assertNever(kind);
83607             }
83608         }
83609         function createCheckedValue(left, right) {
83610             return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right);
83611         }
83612         /**
83613          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
83614          *
83615          * @param node The entity name to serialize.
83616          */
83617         function serializeEntityNameAsExpressionFallback(node) {
83618             if (node.kind === 78 /* Identifier */) {
83619                 // A -> typeof A !== undefined && A
83620                 var copied = serializeEntityNameAsExpression(node);
83621                 return createCheckedValue(copied, copied);
83622             }
83623             if (node.left.kind === 78 /* Identifier */) {
83624                 // A.B -> typeof A !== undefined && A.B
83625                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
83626             }
83627             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
83628             var left = serializeEntityNameAsExpressionFallback(node.left);
83629             var temp = factory.createTempVariable(hoistVariableDeclaration);
83630             return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right));
83631         }
83632         /**
83633          * Serializes an entity name as an expression for decorator type metadata.
83634          *
83635          * @param node The entity name to serialize.
83636          */
83637         function serializeEntityNameAsExpression(node) {
83638             switch (node.kind) {
83639                 case 78 /* Identifier */:
83640                     // Create a clone of the name with a new parent, and treat it as if it were
83641                     // a source tree node for the purposes of the checker.
83642                     var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent);
83643                     name.original = undefined;
83644                     ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node.
83645                     return name;
83646                 case 157 /* QualifiedName */:
83647                     return serializeQualifiedNameAsExpression(node);
83648             }
83649         }
83650         /**
83651          * Serializes an qualified name as an expression for decorator type metadata.
83652          *
83653          * @param node The qualified name to serialize.
83654          * @param useFallback A value indicating whether to use logical operators to test for the
83655          *                    qualified name at runtime.
83656          */
83657         function serializeQualifiedNameAsExpression(node) {
83658             return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right);
83659         }
83660         /**
83661          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
83662          * available.
83663          */
83664         function getGlobalSymbolNameWithFallback() {
83665             return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), 
83666             /*questionToken*/ undefined, factory.createIdentifier("Symbol"), 
83667             /*colonToken*/ undefined, factory.createIdentifier("Object"));
83668         }
83669         /**
83670          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
83671          * available.
83672          */
83673         function getGlobalBigIntNameWithFallback() {
83674             return languageVersion < 99 /* ESNext */
83675                 ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), 
83676                 /*questionToken*/ undefined, factory.createIdentifier("BigInt"), 
83677                 /*colonToken*/ undefined, factory.createIdentifier("Object"))
83678                 : factory.createIdentifier("BigInt");
83679         }
83680         /**
83681          * Gets an expression that represents a property name (for decorated properties or enums).
83682          * For a computed property, a name is generated for the node.
83683          *
83684          * @param member The member whose name should be converted into an expression.
83685          */
83686         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
83687             var name = member.name;
83688             if (ts.isPrivateIdentifier(name)) {
83689                 return factory.createIdentifier("");
83690             }
83691             else if (ts.isComputedPropertyName(name)) {
83692                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
83693                     ? factory.getGeneratedNameForNode(name)
83694                     : name.expression;
83695             }
83696             else if (ts.isIdentifier(name)) {
83697                 return factory.createStringLiteral(ts.idText(name));
83698             }
83699             else {
83700                 return factory.cloneNode(name);
83701             }
83702         }
83703         /**
83704          * Visits the property name of a class element, for use when emitting property
83705          * initializers. For a computed property on a node with decorators, a temporary
83706          * value is stored for later use.
83707          *
83708          * @param member The member whose name should be visited.
83709          */
83710         function visitPropertyNameOfClassElement(member) {
83711             var name = member.name;
83712             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
83713             // The names are used more than once when:
83714             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
83715             //   - the property has a decorator.
83716             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
83717                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
83718                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
83719                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
83720                     var generatedName = factory.getGeneratedNameForNode(name);
83721                     hoistVariableDeclaration(generatedName);
83722                     return factory.updateComputedPropertyName(name, factory.createAssignment(generatedName, expression));
83723                 }
83724             }
83725             return ts.visitNode(name, visitor, ts.isPropertyName);
83726         }
83727         /**
83728          * Transforms a HeritageClause with TypeScript syntax.
83729          *
83730          * This function will only be called when one of the following conditions are met:
83731          * - The node is a non-`extends` heritage clause that should be elided.
83732          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
83733          *
83734          * @param node The HeritageClause to transform.
83735          */
83736         function visitHeritageClause(node) {
83737             if (node.token === 116 /* ImplementsKeyword */) {
83738                 // implements clauses are elided
83739                 return undefined;
83740             }
83741             return ts.visitEachChild(node, visitor, context);
83742         }
83743         /**
83744          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
83745          *
83746          * This function will only be called when one of the following conditions are met:
83747          * - The node contains type arguments that should be elided.
83748          *
83749          * @param node The ExpressionWithTypeArguments to transform.
83750          */
83751         function visitExpressionWithTypeArguments(node) {
83752             return factory.updateExpressionWithTypeArguments(node, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression), 
83753             /*typeArguments*/ undefined);
83754         }
83755         /**
83756          * Determines whether to emit a function-like declaration. We should not emit the
83757          * declaration if it does not have a body.
83758          *
83759          * @param node The declaration node.
83760          */
83761         function shouldEmitFunctionLikeDeclaration(node) {
83762             return !ts.nodeIsMissing(node.body);
83763         }
83764         function visitPropertyDeclaration(node) {
83765             if (node.flags & 8388608 /* Ambient */) {
83766                 return undefined;
83767             }
83768             var updated = factory.updatePropertyDeclaration(node, 
83769             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
83770             /*questionOrExclamationToken*/ undefined, 
83771             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
83772             if (updated !== node) {
83773                 // While we emit the source map for the node after skipping decorators and modifiers,
83774                 // we need to emit the comments for the original range.
83775                 ts.setCommentRange(updated, node);
83776                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
83777             }
83778             return updated;
83779         }
83780         function visitConstructor(node) {
83781             if (!shouldEmitFunctionLikeDeclaration(node)) {
83782                 return undefined;
83783             }
83784             return factory.updateConstructorDeclaration(node, 
83785             /*decorators*/ undefined, 
83786             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
83787         }
83788         function transformConstructorBody(body, constructor) {
83789             var parametersWithPropertyAssignments = constructor &&
83790                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
83791             if (!ts.some(parametersWithPropertyAssignments)) {
83792                 return ts.visitFunctionBody(body, visitor, context);
83793             }
83794             var statements = [];
83795             var indexOfFirstStatement = 0;
83796             resumeLexicalEnvironment();
83797             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
83798             // Add parameters with property assignments. Transforms this:
83799             //
83800             //  constructor (public x, public y) {
83801             //  }
83802             //
83803             // Into this:
83804             //
83805             //  constructor (x, y) {
83806             //      this.x = x;
83807             //      this.y = y;
83808             //  }
83809             //
83810             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
83811             // Add the existing statements, skipping the initial super call.
83812             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
83813             // End the lexical environment.
83814             statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
83815             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true);
83816             ts.setTextRange(block, /*location*/ body);
83817             ts.setOriginalNode(block, body);
83818             return block;
83819         }
83820         /**
83821          * Transforms a parameter into a property assignment statement.
83822          *
83823          * @param node The parameter declaration.
83824          */
83825         function transformParameterWithPropertyAssignment(node) {
83826             var name = node.name;
83827             if (!ts.isIdentifier(name)) {
83828                 return undefined;
83829             }
83830             // TODO(rbuckton): Does this need to be parented?
83831             var propertyName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
83832             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
83833             // TODO(rbuckton): Does this need to be parented?
83834             var localName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
83835             ts.setEmitFlags(localName, 1536 /* NoComments */);
83836             return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(factory.createExpressionStatement(factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1))));
83837         }
83838         function visitMethodDeclaration(node) {
83839             if (!shouldEmitFunctionLikeDeclaration(node)) {
83840                 return undefined;
83841             }
83842             var updated = factory.updateMethodDeclaration(node, 
83843             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
83844             /*questionToken*/ undefined, 
83845             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
83846             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
83847             if (updated !== node) {
83848                 // While we emit the source map for the node after skipping decorators and modifiers,
83849                 // we need to emit the comments for the original range.
83850                 ts.setCommentRange(updated, node);
83851                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
83852             }
83853             return updated;
83854         }
83855         /**
83856          * Determines whether to emit an accessor declaration. We should not emit the
83857          * declaration if it does not have a body and is abstract.
83858          *
83859          * @param node The declaration node.
83860          */
83861         function shouldEmitAccessorDeclaration(node) {
83862             return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* Abstract */));
83863         }
83864         function visitGetAccessor(node) {
83865             if (!shouldEmitAccessorDeclaration(node)) {
83866                 return undefined;
83867             }
83868             var updated = factory.updateGetAccessorDeclaration(node, 
83869             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
83870             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
83871             if (updated !== node) {
83872                 // While we emit the source map for the node after skipping decorators and modifiers,
83873                 // we need to emit the comments for the original range.
83874                 ts.setCommentRange(updated, node);
83875                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
83876             }
83877             return updated;
83878         }
83879         function visitSetAccessor(node) {
83880             if (!shouldEmitAccessorDeclaration(node)) {
83881                 return undefined;
83882             }
83883             var updated = factory.updateSetAccessorDeclaration(node, 
83884             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
83885             if (updated !== node) {
83886                 // While we emit the source map for the node after skipping decorators and modifiers,
83887                 // we need to emit the comments for the original range.
83888                 ts.setCommentRange(updated, node);
83889                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
83890             }
83891             return updated;
83892         }
83893         function visitFunctionDeclaration(node) {
83894             if (!shouldEmitFunctionLikeDeclaration(node)) {
83895                 return factory.createNotEmittedStatement(node);
83896             }
83897             var updated = factory.updateFunctionDeclaration(node, 
83898             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
83899             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
83900             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
83901             if (isExportOfNamespace(node)) {
83902                 var statements = [updated];
83903                 addExportMemberAssignment(statements, node);
83904                 return statements;
83905             }
83906             return updated;
83907         }
83908         function visitFunctionExpression(node) {
83909             if (!shouldEmitFunctionLikeDeclaration(node)) {
83910                 return factory.createOmittedExpression();
83911             }
83912             var updated = factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
83913             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
83914             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
83915             return updated;
83916         }
83917         function visitArrowFunction(node) {
83918             var updated = factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
83919             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
83920             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
83921             return updated;
83922         }
83923         function visitParameter(node) {
83924             if (ts.parameterIsThisKeyword(node)) {
83925                 return undefined;
83926             }
83927             var updated = factory.updateParameterDeclaration(node, 
83928             /*decorators*/ undefined, 
83929             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
83930             /*questionToken*/ undefined, 
83931             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
83932             if (updated !== node) {
83933                 // While we emit the source map for the node after skipping decorators and modifiers,
83934                 // we need to emit the comments for the original range.
83935                 ts.setCommentRange(updated, node);
83936                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
83937                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
83938                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
83939             }
83940             return updated;
83941         }
83942         function visitVariableStatement(node) {
83943             if (isExportOfNamespace(node)) {
83944                 var variables = ts.getInitializedVariables(node.declarationList);
83945                 if (variables.length === 0) {
83946                     // elide statement if there are no initialized variables.
83947                     return undefined;
83948                 }
83949                 return ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
83950             }
83951             else {
83952                 return ts.visitEachChild(node, visitor, context);
83953             }
83954         }
83955         function transformInitializedVariable(node) {
83956             var name = node.name;
83957             if (ts.isBindingPattern(name)) {
83958                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
83959                 /*needsValue*/ false, createNamespaceExportExpression);
83960             }
83961             else {
83962                 return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
83963                 /*location*/ node);
83964             }
83965         }
83966         function visitVariableDeclaration(node) {
83967             return factory.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
83968             /*exclamationToken*/ undefined, 
83969             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
83970         }
83971         function visitParenthesizedExpression(node) {
83972             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
83973             if (ts.isAssertionExpression(innerExpression)) {
83974                 // Make sure we consider all nested cast expressions, e.g.:
83975                 // (<any><number><any>-A).x;
83976                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
83977                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
83978                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
83979                 // the parentheses, however, could cause change in the semantics of the generated
83980                 // code if the casted expression has a lower precedence than the rest of the
83981                 // expression.
83982                 //
83983                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
83984                 // preserve the position information of the original expression.
83985                 //
83986                 // Due to the auto-parenthesization rules used by the visitor and factory functions
83987                 // we can safely elide the parentheses here, as a new synthetic
83988                 // ParenthesizedExpression will be inserted if we remove parentheses too
83989                 // aggressively.
83990                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
83991                 // correctly for return and throw, we must keep the parenthesis
83992                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
83993                     return factory.updateParenthesizedExpression(node, expression);
83994                 }
83995                 return factory.createPartiallyEmittedExpression(expression, node);
83996             }
83997             return ts.visitEachChild(node, visitor, context);
83998         }
83999         function visitAssertionExpression(node) {
84000             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84001             return factory.createPartiallyEmittedExpression(expression, node);
84002         }
84003         function visitNonNullExpression(node) {
84004             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
84005             return factory.createPartiallyEmittedExpression(expression, node);
84006         }
84007         function visitCallExpression(node) {
84008             return factory.updateCallExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
84009             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
84010         }
84011         function visitNewExpression(node) {
84012             return factory.updateNewExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
84013             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
84014         }
84015         function visitTaggedTemplateExpression(node) {
84016             return factory.updateTaggedTemplateExpression(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
84017             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
84018         }
84019         function visitJsxSelfClosingElement(node) {
84020             return factory.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
84021             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
84022         }
84023         function visitJsxJsxOpeningElement(node) {
84024             return factory.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
84025             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
84026         }
84027         /**
84028          * Determines whether to emit an enum declaration.
84029          *
84030          * @param node The enum declaration node.
84031          */
84032         function shouldEmitEnumDeclaration(node) {
84033             return !ts.isEnumConst(node)
84034                 || compilerOptions.preserveConstEnums
84035                 || compilerOptions.isolatedModules;
84036         }
84037         /**
84038          * Visits an enum declaration.
84039          *
84040          * This function will be called any time a TypeScript enum is encountered.
84041          *
84042          * @param node The enum declaration node.
84043          */
84044         function visitEnumDeclaration(node) {
84045             if (!shouldEmitEnumDeclaration(node)) {
84046                 return factory.createNotEmittedStatement(node);
84047             }
84048             var statements = [];
84049             // We request to be advised when the printer is about to print this node. This allows
84050             // us to set up the correct state for later substitutions.
84051             var emitFlags = 2 /* AdviseOnEmitNode */;
84052             // If needed, we should emit a variable declaration for the enum. If we emit
84053             // a leading variable declaration, we should not emit leading comments for the
84054             // enum body.
84055             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
84056             if (varAdded) {
84057                 // We should still emit the comments if we are emitting a system module.
84058                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
84059                     emitFlags |= 512 /* NoLeadingComments */;
84060                 }
84061             }
84062             // `parameterName` is the declaration name used inside of the enum.
84063             var parameterName = getNamespaceParameterName(node);
84064             // `containerName` is the expression used inside of the enum for assignments.
84065             var containerName = getNamespaceContainerName(node);
84066             // `exportName` is the expression used within this node's container for any exported references.
84067             var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
84068                 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
84069                 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
84070             //  x || (x = {})
84071             //  exports.x || (exports.x = {})
84072             var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
84073             if (hasNamespaceQualifiedExportName(node)) {
84074                 // `localName` is the expression used within this node's containing scope for any local references.
84075                 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
84076                 //  x = (exports.x || (exports.x = {}))
84077                 moduleArg = factory.createAssignment(localName, moduleArg);
84078             }
84079             //  (function (x) {
84080             //      x[x["y"] = 0] = "y";
84081             //      ...
84082             //  })(x || (x = {}));
84083             var enumStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
84084             /*modifiers*/ undefined, 
84085             /*asteriskToken*/ undefined, 
84086             /*name*/ undefined, 
84087             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
84088             /*type*/ undefined, transformEnumBody(node, containerName)), 
84089             /*typeArguments*/ undefined, [moduleArg]));
84090             ts.setOriginalNode(enumStatement, node);
84091             if (varAdded) {
84092                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
84093                 ts.setSyntheticLeadingComments(enumStatement, undefined);
84094                 ts.setSyntheticTrailingComments(enumStatement, undefined);
84095             }
84096             ts.setTextRange(enumStatement, node);
84097             ts.addEmitFlags(enumStatement, emitFlags);
84098             statements.push(enumStatement);
84099             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
84100             // the end of the declaration.
84101             statements.push(factory.createEndOfDeclarationMarker(node));
84102             return statements;
84103         }
84104         /**
84105          * Transforms the body of an enum declaration.
84106          *
84107          * @param node The enum declaration node.
84108          */
84109         function transformEnumBody(node, localName) {
84110             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
84111             currentNamespaceContainerName = localName;
84112             var statements = [];
84113             startLexicalEnvironment();
84114             var members = ts.map(node.members, transformEnumMember);
84115             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
84116             ts.addRange(statements, members);
84117             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
84118             return factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members), 
84119             /*multiLine*/ true);
84120         }
84121         /**
84122          * Transforms an enum member into a statement.
84123          *
84124          * @param member The enum member node.
84125          */
84126         function transformEnumMember(member) {
84127             // enums don't support computed properties
84128             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
84129             // old emitter always generate 'expression' part of the name as-is.
84130             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
84131             var valueExpression = transformEnumMemberDeclarationValue(member);
84132             var innerAssignment = factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, name), valueExpression);
84133             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
84134                 innerAssignment :
84135                 factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, innerAssignment), name);
84136             return ts.setTextRange(factory.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
84137         }
84138         /**
84139          * Transforms the value of an enum member.
84140          *
84141          * @param member The enum member node.
84142          */
84143         function transformEnumMemberDeclarationValue(member) {
84144             var value = resolver.getConstantValue(member);
84145             if (value !== undefined) {
84146                 return typeof value === "string" ? factory.createStringLiteral(value) : factory.createNumericLiteral(value);
84147             }
84148             else {
84149                 enableSubstitutionForNonQualifiedEnumMembers();
84150                 if (member.initializer) {
84151                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
84152                 }
84153                 else {
84154                     return factory.createVoidZero();
84155                 }
84156             }
84157         }
84158         /**
84159          * Determines whether to elide a module declaration.
84160          *
84161          * @param node The module declaration node.
84162          */
84163         function shouldEmitModuleDeclaration(nodeIn) {
84164             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
84165             if (!node) {
84166                 // If we can't find a parse tree node, assume the node is instantiated.
84167                 return true;
84168             }
84169             return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
84170         }
84171         /**
84172          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
84173          * or `exports.x`).
84174          */
84175         function hasNamespaceQualifiedExportName(node) {
84176             return isExportOfNamespace(node)
84177                 || (isExternalModuleExport(node)
84178                     && moduleKind !== ts.ModuleKind.ES2015
84179                     && moduleKind !== ts.ModuleKind.ES2020
84180                     && moduleKind !== ts.ModuleKind.ESNext
84181                     && moduleKind !== ts.ModuleKind.System);
84182         }
84183         /**
84184          * Records that a declaration was emitted in the current scope, if it was the first
84185          * declaration for the provided symbol.
84186          */
84187         function recordEmittedDeclarationInScope(node) {
84188             if (!currentScopeFirstDeclarationsOfName) {
84189                 currentScopeFirstDeclarationsOfName = new ts.Map();
84190             }
84191             var name = declaredNameInScope(node);
84192             if (!currentScopeFirstDeclarationsOfName.has(name)) {
84193                 currentScopeFirstDeclarationsOfName.set(name, node);
84194             }
84195         }
84196         /**
84197          * Determines whether a declaration is the first declaration with
84198          * the same name emitted in the current scope.
84199          */
84200         function isFirstEmittedDeclarationInScope(node) {
84201             if (currentScopeFirstDeclarationsOfName) {
84202                 var name = declaredNameInScope(node);
84203                 return currentScopeFirstDeclarationsOfName.get(name) === node;
84204             }
84205             return true;
84206         }
84207         function declaredNameInScope(node) {
84208             ts.Debug.assertNode(node.name, ts.isIdentifier);
84209             return node.name.escapedText;
84210         }
84211         /**
84212          * Adds a leading VariableStatement for a enum or module declaration.
84213          */
84214         function addVarForEnumOrModuleDeclaration(statements, node) {
84215             // Emit a variable statement for the module. We emit top-level enums as a `var`
84216             // declaration to avoid static errors in global scripts scripts due to redeclaration.
84217             // enums in any other scope are emitted as a `let` declaration.
84218             var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
84219                 factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
84220             ], currentLexicalScope.kind === 297 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
84221             ts.setOriginalNode(statement, node);
84222             recordEmittedDeclarationInScope(node);
84223             if (isFirstEmittedDeclarationInScope(node)) {
84224                 // Adjust the source map emit to match the old emitter.
84225                 if (node.kind === 255 /* EnumDeclaration */) {
84226                     ts.setSourceMapRange(statement.declarationList, node);
84227                 }
84228                 else {
84229                     ts.setSourceMapRange(statement, node);
84230                 }
84231                 // Trailing comments for module declaration should be emitted after the function closure
84232                 // instead of the variable statement:
84233                 //
84234                 //     /** Module comment*/
84235                 //     module m1 {
84236                 //         function foo4Export() {
84237                 //         }
84238                 //     } // trailing comment module
84239                 //
84240                 // Should emit:
84241                 //
84242                 //     /** Module comment*/
84243                 //     var m1;
84244                 //     (function (m1) {
84245                 //         function foo4Export() {
84246                 //         }
84247                 //     })(m1 || (m1 = {})); // trailing comment module
84248                 //
84249                 ts.setCommentRange(statement, node);
84250                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
84251                 statements.push(statement);
84252                 return true;
84253             }
84254             else {
84255                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
84256                 // declaration we do not emit a leading variable declaration. To preserve the
84257                 // begin/end semantics of the declararation and to properly handle exports
84258                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
84259                 var mergeMarker = factory.createMergeDeclarationMarker(statement);
84260                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
84261                 statements.push(mergeMarker);
84262                 return false;
84263             }
84264         }
84265         /**
84266          * Visits a module declaration node.
84267          *
84268          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
84269          *
84270          * @param node The module declaration node.
84271          */
84272         function visitModuleDeclaration(node) {
84273             if (!shouldEmitModuleDeclaration(node)) {
84274                 return factory.createNotEmittedStatement(node);
84275             }
84276             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
84277             enableSubstitutionForNamespaceExports();
84278             var statements = [];
84279             // We request to be advised when the printer is about to print this node. This allows
84280             // us to set up the correct state for later substitutions.
84281             var emitFlags = 2 /* AdviseOnEmitNode */;
84282             // If needed, we should emit a variable declaration for the module. If we emit
84283             // a leading variable declaration, we should not emit leading comments for the
84284             // module body.
84285             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
84286             if (varAdded) {
84287                 // We should still emit the comments if we are emitting a system module.
84288                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
84289                     emitFlags |= 512 /* NoLeadingComments */;
84290                 }
84291             }
84292             // `parameterName` is the declaration name used inside of the namespace.
84293             var parameterName = getNamespaceParameterName(node);
84294             // `containerName` is the expression used inside of the namespace for exports.
84295             var containerName = getNamespaceContainerName(node);
84296             // `exportName` is the expression used within this node's container for any exported references.
84297             var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
84298                 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
84299                 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
84300             //  x || (x = {})
84301             //  exports.x || (exports.x = {})
84302             var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
84303             if (hasNamespaceQualifiedExportName(node)) {
84304                 // `localName` is the expression used within this node's containing scope for any local references.
84305                 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
84306                 //  x = (exports.x || (exports.x = {}))
84307                 moduleArg = factory.createAssignment(localName, moduleArg);
84308             }
84309             //  (function (x_1) {
84310             //      x_1.y = ...;
84311             //  })(x || (x = {}));
84312             var moduleStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
84313             /*modifiers*/ undefined, 
84314             /*asteriskToken*/ undefined, 
84315             /*name*/ undefined, 
84316             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
84317             /*type*/ undefined, transformModuleBody(node, containerName)), 
84318             /*typeArguments*/ undefined, [moduleArg]));
84319             ts.setOriginalNode(moduleStatement, node);
84320             if (varAdded) {
84321                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
84322                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
84323                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
84324             }
84325             ts.setTextRange(moduleStatement, node);
84326             ts.addEmitFlags(moduleStatement, emitFlags);
84327             statements.push(moduleStatement);
84328             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
84329             // the end of the declaration.
84330             statements.push(factory.createEndOfDeclarationMarker(node));
84331             return statements;
84332         }
84333         /**
84334          * Transforms the body of a module declaration.
84335          *
84336          * @param node The module declaration node.
84337          */
84338         function transformModuleBody(node, namespaceLocalName) {
84339             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
84340             var savedCurrentNamespace = currentNamespace;
84341             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
84342             currentNamespaceContainerName = namespaceLocalName;
84343             currentNamespace = node;
84344             currentScopeFirstDeclarationsOfName = undefined;
84345             var statements = [];
84346             startLexicalEnvironment();
84347             var statementsLocation;
84348             var blockLocation;
84349             if (node.body) {
84350                 if (node.body.kind === 257 /* ModuleBlock */) {
84351                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
84352                     statementsLocation = node.body.statements;
84353                     blockLocation = node.body;
84354                 }
84355                 else {
84356                     var result = visitModuleDeclaration(node.body);
84357                     if (result) {
84358                         if (ts.isArray(result)) {
84359                             ts.addRange(statements, result);
84360                         }
84361                         else {
84362                             statements.push(result);
84363                         }
84364                     }
84365                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
84366                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
84367                 }
84368             }
84369             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
84370             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
84371             currentNamespace = savedCurrentNamespace;
84372             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
84373             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), 
84374             /*location*/ statementsLocation), 
84375             /*multiLine*/ true);
84376             ts.setTextRange(block, blockLocation);
84377             // namespace hello.hi.world {
84378             //      function foo() {}
84379             //
84380             //      // TODO, blah
84381             // }
84382             //
84383             // should be emitted as
84384             //
84385             // var hello;
84386             // (function (hello) {
84387             //     var hi;
84388             //     (function (hi) {
84389             //         var world;
84390             //         (function (world) {
84391             //             function foo() { }
84392             //             // TODO, blah
84393             //         })(world = hi.world || (hi.world = {}));
84394             //     })(hi = hello.hi || (hello.hi = {}));
84395             // })(hello || (hello = {}));
84396             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
84397             if (!node.body || node.body.kind !== 257 /* ModuleBlock */) {
84398                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
84399             }
84400             return block;
84401         }
84402         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
84403             if (moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) {
84404                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
84405                 return recursiveInnerModule || moduleDeclaration.body;
84406             }
84407         }
84408         /**
84409          * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
84410          *
84411          * @param node The import declaration node.
84412          */
84413         function visitImportDeclaration(node) {
84414             if (!node.importClause) {
84415                 // Do not elide a side-effect only import declaration.
84416                 //  import "foo";
84417                 return node;
84418             }
84419             if (node.importClause.isTypeOnly) {
84420                 // Always elide type-only imports
84421                 return undefined;
84422             }
84423             // Elide the declaration if the import clause was elided.
84424             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
84425             return importClause ||
84426                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
84427                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
84428                 ? factory.updateImportDeclaration(node, 
84429                 /*decorators*/ undefined, 
84430                 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
84431                 : undefined;
84432         }
84433         /**
84434          * Visits an import clause, eliding it if it is not referenced.
84435          *
84436          * @param node The import clause node.
84437          */
84438         function visitImportClause(node) {
84439             if (node.isTypeOnly) {
84440                 return undefined;
84441             }
84442             // Elide the import clause if we elide both its name and its named bindings.
84443             var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
84444             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
84445             return (name || namedBindings) ? factory.updateImportClause(node, /*isTypeOnly*/ false, name, namedBindings) : undefined;
84446         }
84447         /**
84448          * Visits named import bindings, eliding it if it is not referenced.
84449          *
84450          * @param node The named import bindings node.
84451          */
84452         function visitNamedImportBindings(node) {
84453             if (node.kind === 263 /* NamespaceImport */) {
84454                 // Elide a namespace import if it is not referenced.
84455                 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
84456             }
84457             else {
84458                 // Elide named imports if all of its import specifiers are elided.
84459                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
84460                 return ts.some(elements) ? factory.updateNamedImports(node, elements) : undefined;
84461             }
84462         }
84463         /**
84464          * Visits an import specifier, eliding it if it is not referenced.
84465          *
84466          * @param node The import specifier node.
84467          */
84468         function visitImportSpecifier(node) {
84469             // Elide an import specifier if it is not referenced.
84470             return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
84471         }
84472         /**
84473          * Visits an export assignment, eliding it if it does not contain a clause that resolves
84474          * to a value.
84475          *
84476          * @param node The export assignment node.
84477          */
84478         function visitExportAssignment(node) {
84479             // Elide the export assignment if it does not reference a value.
84480             return resolver.isValueAliasDeclaration(node)
84481                 ? ts.visitEachChild(node, visitor, context)
84482                 : undefined;
84483         }
84484         /**
84485          * Visits an export declaration, eliding it if it does not contain a clause that resolves
84486          * to a value.
84487          *
84488          * @param node The export declaration node.
84489          */
84490         function visitExportDeclaration(node) {
84491             if (node.isTypeOnly) {
84492                 return undefined;
84493             }
84494             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
84495                 // never elide `export <whatever> from <whereever>` declarations -
84496                 // they should be kept for sideffects/untyped exports, even when the
84497                 // type checker doesn't know about any exports
84498                 return node;
84499             }
84500             if (!resolver.isValueAliasDeclaration(node)) {
84501                 // Elide the export declaration if it does not export a value.
84502                 return undefined;
84503             }
84504             // Elide the export declaration if all of its named exports are elided.
84505             var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
84506             return exportClause
84507                 ? factory.updateExportDeclaration(node, 
84508                 /*decorators*/ undefined, 
84509                 /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier)
84510                 : undefined;
84511         }
84512         /**
84513          * Visits named exports, eliding it if it does not contain an export specifier that
84514          * resolves to a value.
84515          *
84516          * @param node The named exports node.
84517          */
84518         function visitNamedExports(node) {
84519             // Elide the named exports if all of its export specifiers were elided.
84520             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
84521             return ts.some(elements) ? factory.updateNamedExports(node, elements) : undefined;
84522         }
84523         function visitNamespaceExports(node) {
84524             return factory.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
84525         }
84526         function visitNamedExportBindings(node) {
84527             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
84528         }
84529         /**
84530          * Visits an export specifier, eliding it if it does not resolve to a value.
84531          *
84532          * @param node The export specifier node.
84533          */
84534         function visitExportSpecifier(node) {
84535             // Elide an export specifier if it does not reference a value.
84536             return resolver.isValueAliasDeclaration(node) ? node : undefined;
84537         }
84538         /**
84539          * Determines whether to emit an import equals declaration.
84540          *
84541          * @param node The import equals declaration node.
84542          */
84543         function shouldEmitImportEqualsDeclaration(node) {
84544             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
84545             // - current file is not external module
84546             // - import declaration is top level and target is value imported by entity name
84547             return resolver.isReferencedAliasDeclaration(node)
84548                 || (!ts.isExternalModule(currentSourceFile)
84549                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
84550         }
84551         /**
84552          * Visits an import equals declaration.
84553          *
84554          * @param node The import equals declaration node.
84555          */
84556         function visitImportEqualsDeclaration(node) {
84557             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
84558                 var isReferenced = resolver.isReferencedAliasDeclaration(node);
84559                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
84560                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
84561                     return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration(
84562                     /*decorators*/ undefined, 
84563                     /*modifiers*/ undefined, 
84564                     /*importClause*/ undefined, node.moduleReference.expression), node), node);
84565                 }
84566                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
84567             }
84568             if (!shouldEmitImportEqualsDeclaration(node)) {
84569                 return undefined;
84570             }
84571             var moduleReference = ts.createExpressionFromEntityName(factory, node.moduleReference);
84572             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
84573             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
84574                 //  export var ${name} = ${moduleReference};
84575                 //  var ${name} = ${moduleReference};
84576                 return ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
84577                     ts.setOriginalNode(factory.createVariableDeclaration(node.name, 
84578                     /*exclamationToken*/ undefined, 
84579                     /*type*/ undefined, moduleReference), node)
84580                 ])), node), node);
84581             }
84582             else {
84583                 // exports.${name} = ${moduleReference};
84584                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
84585             }
84586         }
84587         /**
84588          * Gets a value indicating whether the node is exported from a namespace.
84589          *
84590          * @param node The node to test.
84591          */
84592         function isExportOfNamespace(node) {
84593             return currentNamespace !== undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
84594         }
84595         /**
84596          * Gets a value indicating whether the node is exported from an external module.
84597          *
84598          * @param node The node to test.
84599          */
84600         function isExternalModuleExport(node) {
84601             return currentNamespace === undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
84602         }
84603         /**
84604          * Gets a value indicating whether the node is a named export from an external module.
84605          *
84606          * @param node The node to test.
84607          */
84608         function isNamedExternalModuleExport(node) {
84609             return isExternalModuleExport(node)
84610                 && !ts.hasSyntacticModifier(node, 512 /* Default */);
84611         }
84612         /**
84613          * Gets a value indicating whether the node is the default export of an external module.
84614          *
84615          * @param node The node to test.
84616          */
84617         function isDefaultExternalModuleExport(node) {
84618             return isExternalModuleExport(node)
84619                 && ts.hasSyntacticModifier(node, 512 /* Default */);
84620         }
84621         /**
84622          * Creates a statement for the provided expression. This is used in calls to `map`.
84623          */
84624         function expressionToStatement(expression) {
84625             return factory.createExpressionStatement(expression);
84626         }
84627         function addExportMemberAssignment(statements, node) {
84628             var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node));
84629             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
84630             var statement = factory.createExpressionStatement(expression);
84631             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
84632             statements.push(statement);
84633         }
84634         function createNamespaceExport(exportName, exportValue, location) {
84635             return ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
84636         }
84637         function createNamespaceExportExpression(exportName, exportValue, location) {
84638             return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
84639         }
84640         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
84641             return factory.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
84642         }
84643         /**
84644          * Gets the declaration name used inside of a namespace or enum.
84645          */
84646         function getNamespaceParameterName(node) {
84647             var name = factory.getGeneratedNameForNode(node);
84648             ts.setSourceMapRange(name, node.name);
84649             return name;
84650         }
84651         /**
84652          * Gets the expression used to refer to a namespace or enum within the body
84653          * of its declaration.
84654          */
84655         function getNamespaceContainerName(node) {
84656             return factory.getGeneratedNameForNode(node);
84657         }
84658         /**
84659          * Gets a local alias for a class declaration if it is a decorated class with an internal
84660          * reference to the static side of the class. This is necessary to avoid issues with
84661          * double-binding semantics for the class name.
84662          */
84663         function getClassAliasIfNeeded(node) {
84664             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
84665                 enableSubstitutionForClassAliases();
84666                 var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
84667                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
84668                 hoistVariableDeclaration(classAlias);
84669                 return classAlias;
84670             }
84671         }
84672         function getClassPrototype(node) {
84673             return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype");
84674         }
84675         function getClassMemberPrefix(node, member) {
84676             return ts.hasSyntacticModifier(member, 32 /* Static */)
84677                 ? factory.getDeclarationName(node)
84678                 : getClassPrototype(node);
84679         }
84680         function enableSubstitutionForNonQualifiedEnumMembers() {
84681             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
84682                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
84683                 context.enableSubstitution(78 /* Identifier */);
84684             }
84685         }
84686         function enableSubstitutionForClassAliases() {
84687             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
84688                 enabledSubstitutions |= 1 /* ClassAliases */;
84689                 // We need to enable substitutions for identifiers. This allows us to
84690                 // substitute class names inside of a class declaration.
84691                 context.enableSubstitution(78 /* Identifier */);
84692                 // Keep track of class aliases.
84693                 classAliases = [];
84694             }
84695         }
84696         function enableSubstitutionForNamespaceExports() {
84697             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
84698                 enabledSubstitutions |= 2 /* NamespaceExports */;
84699                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
84700                 // substitute the names of exported members of a namespace.
84701                 context.enableSubstitution(78 /* Identifier */);
84702                 context.enableSubstitution(289 /* ShorthandPropertyAssignment */);
84703                 // We need to be notified when entering and exiting namespaces.
84704                 context.enableEmitNotification(256 /* ModuleDeclaration */);
84705             }
84706         }
84707         function isTransformedModuleDeclaration(node) {
84708             return ts.getOriginalNode(node).kind === 256 /* ModuleDeclaration */;
84709         }
84710         function isTransformedEnumDeclaration(node) {
84711             return ts.getOriginalNode(node).kind === 255 /* EnumDeclaration */;
84712         }
84713         /**
84714          * Hook for node emit.
84715          *
84716          * @param hint A hint as to the intended usage of the node.
84717          * @param node The node to emit.
84718          * @param emit A callback used to emit the node in the printer.
84719          */
84720         function onEmitNode(hint, node, emitCallback) {
84721             var savedApplicableSubstitutions = applicableSubstitutions;
84722             var savedCurrentSourceFile = currentSourceFile;
84723             if (ts.isSourceFile(node)) {
84724                 currentSourceFile = node;
84725             }
84726             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
84727                 applicableSubstitutions |= 2 /* NamespaceExports */;
84728             }
84729             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
84730                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
84731             }
84732             previousOnEmitNode(hint, node, emitCallback);
84733             applicableSubstitutions = savedApplicableSubstitutions;
84734             currentSourceFile = savedCurrentSourceFile;
84735         }
84736         /**
84737          * Hooks node substitutions.
84738          *
84739          * @param hint A hint as to the intended usage of the node.
84740          * @param node The node to substitute.
84741          */
84742         function onSubstituteNode(hint, node) {
84743             node = previousOnSubstituteNode(hint, node);
84744             if (hint === 1 /* Expression */) {
84745                 return substituteExpression(node);
84746             }
84747             else if (ts.isShorthandPropertyAssignment(node)) {
84748                 return substituteShorthandPropertyAssignment(node);
84749             }
84750             return node;
84751         }
84752         function substituteShorthandPropertyAssignment(node) {
84753             if (enabledSubstitutions & 2 /* NamespaceExports */) {
84754                 var name = node.name;
84755                 var exportedName = trySubstituteNamespaceExportedName(name);
84756                 if (exportedName) {
84757                     // A shorthand property with an assignment initializer is probably part of a
84758                     // destructuring assignment
84759                     if (node.objectAssignmentInitializer) {
84760                         var initializer = factory.createAssignment(exportedName, node.objectAssignmentInitializer);
84761                         return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
84762                     }
84763                     return ts.setTextRange(factory.createPropertyAssignment(name, exportedName), node);
84764                 }
84765             }
84766             return node;
84767         }
84768         function substituteExpression(node) {
84769             switch (node.kind) {
84770                 case 78 /* Identifier */:
84771                     return substituteExpressionIdentifier(node);
84772                 case 201 /* PropertyAccessExpression */:
84773                     return substitutePropertyAccessExpression(node);
84774                 case 202 /* ElementAccessExpression */:
84775                     return substituteElementAccessExpression(node);
84776             }
84777             return node;
84778         }
84779         function substituteExpressionIdentifier(node) {
84780             return trySubstituteClassAlias(node)
84781                 || trySubstituteNamespaceExportedName(node)
84782                 || node;
84783         }
84784         function trySubstituteClassAlias(node) {
84785             if (enabledSubstitutions & 1 /* ClassAliases */) {
84786                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
84787                     // Due to the emit for class decorators, any reference to the class from inside of the class body
84788                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
84789                     // behavior of class names in ES6.
84790                     // Also, when emitting statics for class expressions, we must substitute a class alias for
84791                     // constructor references in static property initializers.
84792                     var declaration = resolver.getReferencedValueDeclaration(node);
84793                     if (declaration) {
84794                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
84795                         if (classAlias) {
84796                             var clone_1 = factory.cloneNode(classAlias);
84797                             ts.setSourceMapRange(clone_1, node);
84798                             ts.setCommentRange(clone_1, node);
84799                             return clone_1;
84800                         }
84801                     }
84802                 }
84803             }
84804             return undefined;
84805         }
84806         function trySubstituteNamespaceExportedName(node) {
84807             // If this is explicitly a local name, do not substitute.
84808             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
84809                 // If we are nested within a namespace declaration, we may need to qualifiy
84810                 // an identifier that is exported from a merged namespace.
84811                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
84812                 if (container && container.kind !== 297 /* SourceFile */) {
84813                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 256 /* ModuleDeclaration */) ||
84814                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 255 /* EnumDeclaration */);
84815                     if (substitute) {
84816                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), 
84817                         /*location*/ node);
84818                     }
84819                 }
84820             }
84821             return undefined;
84822         }
84823         function substitutePropertyAccessExpression(node) {
84824             return substituteConstantValue(node);
84825         }
84826         function substituteElementAccessExpression(node) {
84827             return substituteConstantValue(node);
84828         }
84829         function substituteConstantValue(node) {
84830             var constantValue = tryGetConstEnumValue(node);
84831             if (constantValue !== undefined) {
84832                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
84833                 ts.setConstantValue(node, constantValue);
84834                 var substitute = typeof constantValue === "string" ? factory.createStringLiteral(constantValue) : factory.createNumericLiteral(constantValue);
84835                 if (!compilerOptions.removeComments) {
84836                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
84837                     var propertyName = ts.isPropertyAccessExpression(originalNode)
84838                         ? ts.declarationNameToString(originalNode.name)
84839                         : ts.getTextOfNode(originalNode.argumentExpression);
84840                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
84841                 }
84842                 return substitute;
84843             }
84844             return node;
84845         }
84846         function tryGetConstEnumValue(node) {
84847             if (compilerOptions.isolatedModules) {
84848                 return undefined;
84849             }
84850             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
84851         }
84852     }
84853     ts.transformTypeScript = transformTypeScript;
84854 })(ts || (ts = {}));
84855 /*@internal*/
84856 var ts;
84857 (function (ts) {
84858     var ClassPropertySubstitutionFlags;
84859     (function (ClassPropertySubstitutionFlags) {
84860         /**
84861          * Enables substitutions for class expressions with static fields
84862          * which have initializers that reference the class name.
84863          */
84864         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
84865     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
84866     var PrivateIdentifierPlacement;
84867     (function (PrivateIdentifierPlacement) {
84868         PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
84869     })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
84870     /**
84871      * Transforms ECMAScript Class Syntax.
84872      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
84873      * For now, this transforms public field declarations using TypeScript class semantics,
84874      * where declarations are elided and initializers are transformed as assignments in the constructor.
84875      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
84876      */
84877     function transformClassFields(context) {
84878         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
84879         var resolver = context.getEmitResolver();
84880         var compilerOptions = context.getCompilerOptions();
84881         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
84882         var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
84883         var previousOnSubstituteNode = context.onSubstituteNode;
84884         context.onSubstituteNode = onSubstituteNode;
84885         var enabledSubstitutions;
84886         var classAliases;
84887         /**
84888          * Tracks what computed name expressions originating from elided names must be inlined
84889          * at the next execution site, in document order
84890          */
84891         var pendingExpressions;
84892         /**
84893          * Tracks what computed name expression statements and static property initializers must be
84894          * emitted at the next execution site, in document order (for decorated classes).
84895          */
84896         var pendingStatements;
84897         var privateIdentifierEnvironmentStack = [];
84898         var currentPrivateIdentifierEnvironment;
84899         return ts.chainBundle(context, transformSourceFile);
84900         function transformSourceFile(node) {
84901             var options = context.getCompilerOptions();
84902             if (node.isDeclarationFile
84903                 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
84904                 return node;
84905             }
84906             var visited = ts.visitEachChild(node, visitor, context);
84907             ts.addEmitHelpers(visited, context.readEmitHelpers());
84908             return visited;
84909         }
84910         function visitor(node) {
84911             if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
84912                 return node;
84913             switch (node.kind) {
84914                 case 221 /* ClassExpression */:
84915                 case 252 /* ClassDeclaration */:
84916                     return visitClassLike(node);
84917                 case 163 /* PropertyDeclaration */:
84918                     return visitPropertyDeclaration(node);
84919                 case 232 /* VariableStatement */:
84920                     return visitVariableStatement(node);
84921                 case 158 /* ComputedPropertyName */:
84922                     return visitComputedPropertyName(node);
84923                 case 201 /* PropertyAccessExpression */:
84924                     return visitPropertyAccessExpression(node);
84925                 case 214 /* PrefixUnaryExpression */:
84926                     return visitPrefixUnaryExpression(node);
84927                 case 215 /* PostfixUnaryExpression */:
84928                     return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
84929                 case 203 /* CallExpression */:
84930                     return visitCallExpression(node);
84931                 case 216 /* BinaryExpression */:
84932                     return visitBinaryExpression(node);
84933                 case 79 /* PrivateIdentifier */:
84934                     return visitPrivateIdentifier(node);
84935                 case 233 /* ExpressionStatement */:
84936                     return visitExpressionStatement(node);
84937                 case 237 /* ForStatement */:
84938                     return visitForStatement(node);
84939                 case 205 /* TaggedTemplateExpression */:
84940                     return visitTaggedTemplateExpression(node);
84941             }
84942             return ts.visitEachChild(node, visitor, context);
84943         }
84944         function visitorDestructuringTarget(node) {
84945             switch (node.kind) {
84946                 case 200 /* ObjectLiteralExpression */:
84947                 case 199 /* ArrayLiteralExpression */:
84948                     return visitAssignmentPattern(node);
84949                 default:
84950                     return visitor(node);
84951             }
84952         }
84953         /**
84954          * If we visit a private name, this means it is an undeclared private name.
84955          * Replace it with an empty identifier to indicate a problem with the code.
84956          */
84957         function visitPrivateIdentifier(node) {
84958             if (!shouldTransformPrivateFields) {
84959                 return node;
84960             }
84961             return ts.setOriginalNode(factory.createIdentifier(""), node);
84962         }
84963         /**
84964          * Visits the members of a class that has fields.
84965          *
84966          * @param node The node to visit.
84967          */
84968         function classElementVisitor(node) {
84969             switch (node.kind) {
84970                 case 166 /* Constructor */:
84971                     // Constructors for classes using class fields are transformed in
84972                     // `visitClassDeclaration` or `visitClassExpression`.
84973                     return undefined;
84974                 case 167 /* GetAccessor */:
84975                 case 168 /* SetAccessor */:
84976                 case 165 /* MethodDeclaration */:
84977                     // Visit the name of the member (if it's a computed property name).
84978                     return ts.visitEachChild(node, classElementVisitor, context);
84979                 case 163 /* PropertyDeclaration */:
84980                     return visitPropertyDeclaration(node);
84981                 case 158 /* ComputedPropertyName */:
84982                     return visitComputedPropertyName(node);
84983                 case 229 /* SemicolonClassElement */:
84984                     return node;
84985                 default:
84986                     return visitor(node);
84987             }
84988         }
84989         function visitVariableStatement(node) {
84990             var savedPendingStatements = pendingStatements;
84991             pendingStatements = [];
84992             var visitedNode = ts.visitEachChild(node, visitor, context);
84993             var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
84994                 visitedNode;
84995             pendingStatements = savedPendingStatements;
84996             return statement;
84997         }
84998         function visitComputedPropertyName(name) {
84999             var node = ts.visitEachChild(name, visitor, context);
85000             if (ts.some(pendingExpressions)) {
85001                 var expressions = pendingExpressions;
85002                 expressions.push(name.expression);
85003                 pendingExpressions = [];
85004                 node = factory.updateComputedPropertyName(node, factory.inlineExpressions(expressions));
85005             }
85006             return node;
85007         }
85008         function visitPropertyDeclaration(node) {
85009             ts.Debug.assert(!ts.some(node.decorators));
85010             if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
85011                 // Initializer is elided as the field is initialized in transformConstructor.
85012                 return factory.updatePropertyDeclaration(node, 
85013                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
85014                 /*questionOrExclamationToken*/ undefined, 
85015                 /*type*/ undefined, 
85016                 /*initializer*/ undefined);
85017             }
85018             // Create a temporary variable to store a computed property name (if necessary).
85019             // If it's not inlineable, then we emit an expression after the class which assigns
85020             // the property name to the temporary variable.
85021             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
85022             if (expr && !ts.isSimpleInlineableExpression(expr)) {
85023                 getPendingExpressions().push(expr);
85024             }
85025             return undefined;
85026         }
85027         function createPrivateIdentifierAccess(info, receiver) {
85028             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
85029             switch (info.placement) {
85030                 case 0 /* InstanceField */:
85031                     return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName);
85032                 default: return ts.Debug.fail("Unexpected private identifier placement");
85033             }
85034         }
85035         function visitPropertyAccessExpression(node) {
85036             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
85037                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
85038                 if (privateIdentifierInfo) {
85039                     return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
85040                 }
85041             }
85042             return ts.visitEachChild(node, visitor, context);
85043         }
85044         function visitPrefixUnaryExpression(node) {
85045             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
85046                 var operator = node.operator === 45 /* PlusPlusToken */ ?
85047                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
85048                     40 /* MinusToken */ : undefined;
85049                 var info = void 0;
85050                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
85051                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
85052                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
85053                     var existingValue = factory.createPrefixUnaryExpression(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
85054                     return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, factory.createBinaryExpression(existingValue, operator, factory.createNumericLiteral(1)), 62 /* EqualsToken */), node);
85055                 }
85056             }
85057             return ts.visitEachChild(node, visitor, context);
85058         }
85059         function visitPostfixUnaryExpression(node, valueIsDiscarded) {
85060             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
85061                 var operator = node.operator === 45 /* PlusPlusToken */ ?
85062                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
85063                     40 /* MinusToken */ : undefined;
85064                 var info = void 0;
85065                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
85066                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
85067                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
85068                     var existingValue = factory.createPrefixUnaryExpression(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
85069                     // Create a temporary variable to store the value returned by the expression.
85070                     var returnValue = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
85071                     return ts.setOriginalNode(factory.inlineExpressions(ts.compact([
85072                         createPrivateIdentifierAssignment(info, initializeExpression || readExpression, factory.createBinaryExpression(returnValue ? factory.createAssignment(returnValue, existingValue) : existingValue, operator, factory.createNumericLiteral(1)), 62 /* EqualsToken */),
85073                         returnValue
85074                     ])), node);
85075                 }
85076             }
85077             return ts.visitEachChild(node, visitor, context);
85078         }
85079         function visitForStatement(node) {
85080             if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
85081                 return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitNode(node.statement, visitor, ts.isStatement));
85082             }
85083             return ts.visitEachChild(node, visitor, context);
85084         }
85085         function visitExpressionStatement(node) {
85086             if (ts.isPostfixUnaryExpression(node.expression)) {
85087                 return factory.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
85088             }
85089             return ts.visitEachChild(node, visitor, context);
85090         }
85091         function createCopiableReceiverExpr(receiver) {
85092             var clone = ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver);
85093             if (ts.isSimpleInlineableExpression(receiver)) {
85094                 return { readExpression: clone, initializeExpression: undefined };
85095             }
85096             var readExpression = factory.createTempVariable(hoistVariableDeclaration);
85097             var initializeExpression = factory.createAssignment(readExpression, clone);
85098             return { readExpression: readExpression, initializeExpression: initializeExpression };
85099         }
85100         function visitCallExpression(node) {
85101             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
85102                 // Transform call expressions of private names to properly bind the `this` parameter.
85103                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
85104                 return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), 
85105                 /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
85106             }
85107             return ts.visitEachChild(node, visitor, context);
85108         }
85109         function visitTaggedTemplateExpression(node) {
85110             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
85111                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
85112                 var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
85113                 return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), 
85114                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), 
85115                 /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
85116             }
85117             return ts.visitEachChild(node, visitor, context);
85118         }
85119         function visitBinaryExpression(node) {
85120             if (shouldTransformPrivateFields) {
85121                 if (ts.isDestructuringAssignment(node)) {
85122                     var savedPendingExpressions = pendingExpressions;
85123                     pendingExpressions = undefined;
85124                     node = factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorDestructuringTarget), node.operatorToken, ts.visitNode(node.right, visitor));
85125                     var expr = ts.some(pendingExpressions) ?
85126                         factory.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
85127                         node;
85128                     pendingExpressions = savedPendingExpressions;
85129                     return expr;
85130                 }
85131                 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
85132                     var info = accessPrivateIdentifier(node.left.name);
85133                     if (info) {
85134                         return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
85135                     }
85136                 }
85137             }
85138             return ts.visitEachChild(node, visitor, context);
85139         }
85140         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
85141             switch (info.placement) {
85142                 case 0 /* InstanceField */: {
85143                     return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
85144                 }
85145                 default: return ts.Debug.fail("Unexpected private identifier placement");
85146             }
85147         }
85148         function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
85149             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
85150             right = ts.visitNode(right, visitor, ts.isExpression);
85151             if (ts.isCompoundAssignment(operator)) {
85152                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
85153                 return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
85154             }
85155             else {
85156                 return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right);
85157             }
85158         }
85159         /**
85160          * Set up the environment for a class.
85161          */
85162         function visitClassLike(node) {
85163             var savedPendingExpressions = pendingExpressions;
85164             pendingExpressions = undefined;
85165             if (shouldTransformPrivateFields) {
85166                 startPrivateIdentifierEnvironment();
85167             }
85168             var result = ts.isClassDeclaration(node) ?
85169                 visitClassDeclaration(node) :
85170                 visitClassExpression(node);
85171             if (shouldTransformPrivateFields) {
85172                 endPrivateIdentifierEnvironment();
85173             }
85174             pendingExpressions = savedPendingExpressions;
85175             return result;
85176         }
85177         function doesClassElementNeedTransform(node) {
85178             return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
85179         }
85180         function visitClassDeclaration(node) {
85181             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
85182                 return ts.visitEachChild(node, visitor, context);
85183             }
85184             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
85185             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */);
85186             var statements = [
85187                 factory.updateClassDeclaration(node, 
85188                 /*decorators*/ undefined, node.modifiers, node.name, 
85189                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
85190             ];
85191             // Write any pending expressions from elided or moved computed property names
85192             if (ts.some(pendingExpressions)) {
85193                 statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
85194             }
85195             // Emit static property assignment. Because classDeclaration is lexically evaluated,
85196             // it is safe to emit static property assignment after classDeclaration
85197             // From ES6 specification:
85198             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
85199             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
85200             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
85201             if (ts.some(staticProperties)) {
85202                 addPropertyStatements(statements, staticProperties, factory.getInternalName(node));
85203             }
85204             return statements;
85205         }
85206         function visitClassExpression(node) {
85207             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
85208                 return ts.visitEachChild(node, visitor, context);
85209             }
85210             // If this class expression is a transformation of a decorated class declaration,
85211             // then we want to output the pendingExpressions as statements, not as inlined
85212             // expressions with the class statement.
85213             //
85214             // In this case, we use pendingStatements to produce the same output as the
85215             // class declaration transformation. The VariableStatement visitor will insert
85216             // these statements after the class expression variable statement.
85217             var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
85218             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
85219             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
85220             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */);
85221             var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, 
85222             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
85223             if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
85224                 if (isDecoratedClassDeclaration) {
85225                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
85226                     // Write any pending expressions from elided or moved computed property names
85227                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
85228                         pendingStatements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
85229                     }
85230                     if (pendingStatements && ts.some(staticProperties)) {
85231                         addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node));
85232                     }
85233                     return classExpression;
85234                 }
85235                 else {
85236                     var expressions = [];
85237                     var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
85238                     var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
85239                     if (isClassWithConstructorReference) {
85240                         // record an alias as the class name is not in scope for statics.
85241                         enableSubstitutionForClassAliases();
85242                         var alias = factory.cloneNode(temp);
85243                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
85244                         classAliases[ts.getOriginalNodeId(node)] = alias;
85245                     }
85246                     // To preserve the behavior of the old emitter, we explicitly indent
85247                     // the body of a class with static initializers.
85248                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
85249                     expressions.push(ts.startOnNewLine(factory.createAssignment(temp, classExpression)));
85250                     // Add any pending expressions leftover from elided or relocated computed property names
85251                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
85252                     ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
85253                     expressions.push(ts.startOnNewLine(temp));
85254                     return factory.inlineExpressions(expressions);
85255                 }
85256             }
85257             return classExpression;
85258         }
85259         function transformClassMembers(node, isDerivedClass) {
85260             if (shouldTransformPrivateFields) {
85261                 // Declare private names.
85262                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
85263                     var member = _a[_i];
85264                     if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
85265                         addPrivateIdentifierToEnvironment(member.name);
85266                     }
85267                 }
85268             }
85269             var members = [];
85270             var constructor = transformConstructor(node, isDerivedClass);
85271             if (constructor) {
85272                 members.push(constructor);
85273             }
85274             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
85275             return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
85276         }
85277         function isPropertyDeclarationThatRequiresConstructorStatement(member) {
85278             if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
85279                 return false;
85280             }
85281             if (context.getCompilerOptions().useDefineForClassFields) {
85282                 // If we are using define semantics and targeting ESNext or higher,
85283                 // then we don't need to transform any class properties.
85284                 return languageVersion < 99 /* ESNext */;
85285             }
85286             return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
85287         }
85288         function transformConstructor(node, isDerivedClass) {
85289             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
85290             var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
85291             if (!ts.some(properties)) {
85292                 return constructor;
85293             }
85294             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
85295             var body = transformConstructorBody(node, constructor, isDerivedClass);
85296             if (!body) {
85297                 return undefined;
85298             }
85299             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration(
85300             /*decorators*/ undefined, 
85301             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
85302         }
85303         function transformConstructorBody(node, constructor, isDerivedClass) {
85304             var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
85305             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
85306             if (!useDefineForClassFields) {
85307                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
85308             }
85309             // Only generate synthetic constructor when there are property initializers to move.
85310             if (!constructor && !ts.some(properties)) {
85311                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
85312             }
85313             resumeLexicalEnvironment();
85314             var indexOfFirstStatement = 0;
85315             var statements = [];
85316             if (!constructor && isDerivedClass) {
85317                 // Add a synthetic `super` call:
85318                 //
85319                 //  super(...arguments);
85320                 //
85321                 statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(), 
85322                 /*typeArguments*/ undefined, [factory.createSpreadElement(factory.createIdentifier("arguments"))])));
85323             }
85324             if (constructor) {
85325                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
85326             }
85327             // Add the property initializers. Transforms this:
85328             //
85329             //  public x = 1;
85330             //
85331             // Into this:
85332             //
85333             //  constructor() {
85334             //      this.x = 1;
85335             //  }
85336             //
85337             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
85338                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
85339                 if (afterParameterProperties === -1) {
85340                     afterParameterProperties = constructor.body.statements.length;
85341                 }
85342                 if (afterParameterProperties > indexOfFirstStatement) {
85343                     if (!useDefineForClassFields) {
85344                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
85345                     }
85346                     indexOfFirstStatement = afterParameterProperties;
85347                 }
85348             }
85349             addPropertyStatements(statements, properties, factory.createThis());
85350             // Add existing statements, skipping the initial super call.
85351             if (constructor) {
85352                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
85353             }
85354             statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
85355             return ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), 
85356             /*location*/ constructor ? constructor.body.statements : node.members), 
85357             /*multiLine*/ true), 
85358             /*location*/ constructor ? constructor.body : undefined);
85359         }
85360         /**
85361          * Generates assignment statements for property initializers.
85362          *
85363          * @param properties An array of property declarations to transform.
85364          * @param receiver The receiver on which each property should be assigned.
85365          */
85366         function addPropertyStatements(statements, properties, receiver) {
85367             for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) {
85368                 var property = properties_7[_i];
85369                 var expression = transformProperty(property, receiver);
85370                 if (!expression) {
85371                     continue;
85372                 }
85373                 var statement = factory.createExpressionStatement(expression);
85374                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
85375                 ts.setCommentRange(statement, property);
85376                 ts.setOriginalNode(statement, property);
85377                 statements.push(statement);
85378             }
85379         }
85380         /**
85381          * Generates assignment expressions for property initializers.
85382          *
85383          * @param properties An array of property declarations to transform.
85384          * @param receiver The receiver on which each property should be assigned.
85385          */
85386         function generateInitializedPropertyExpressions(properties, receiver) {
85387             var expressions = [];
85388             for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
85389                 var property = properties_8[_i];
85390                 var expression = transformProperty(property, receiver);
85391                 if (!expression) {
85392                     continue;
85393                 }
85394                 ts.startOnNewLine(expression);
85395                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
85396                 ts.setCommentRange(expression, property);
85397                 ts.setOriginalNode(expression, property);
85398                 expressions.push(expression);
85399             }
85400             return expressions;
85401         }
85402         /**
85403          * Transforms a property initializer into an assignment statement.
85404          *
85405          * @param property The property declaration.
85406          * @param receiver The object receiving the property assignment.
85407          */
85408         function transformProperty(property, receiver) {
85409             var _a;
85410             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
85411             var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
85412             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
85413                 ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name))
85414                 : property.name;
85415             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
85416                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
85417                 if (privateIdentifierInfo) {
85418                     switch (privateIdentifierInfo.placement) {
85419                         case 0 /* InstanceField */: {
85420                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
85421                         }
85422                     }
85423                 }
85424                 else {
85425                     ts.Debug.fail("Undeclared private name for property declaration.");
85426                 }
85427             }
85428             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
85429                 return undefined;
85430             }
85431             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
85432                 return undefined;
85433             }
85434             var propertyOriginalNode = ts.getOriginalNode(property);
85435             var initializer = property.initializer || emitAssignment ? (_a = ts.visitNode(property.initializer, visitor, ts.isExpression)) !== null && _a !== void 0 ? _a : factory.createVoidZero() : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
85436                 : factory.createVoidZero();
85437             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
85438                 var memberAccess = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ propertyName);
85439                 return factory.createAssignment(memberAccess, initializer);
85440             }
85441             else {
85442                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
85443                     : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
85444                         : propertyName;
85445                 var descriptor = factory.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
85446                 return factory.createObjectDefinePropertyCall(receiver, name, descriptor);
85447             }
85448         }
85449         function enableSubstitutionForClassAliases() {
85450             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
85451                 enabledSubstitutions |= 1 /* ClassAliases */;
85452                 // We need to enable substitutions for identifiers. This allows us to
85453                 // substitute class names inside of a class declaration.
85454                 context.enableSubstitution(78 /* Identifier */);
85455                 // Keep track of class aliases.
85456                 classAliases = [];
85457             }
85458         }
85459         /**
85460          * Hooks node substitutions.
85461          *
85462          * @param hint The context for the emitter.
85463          * @param node The node to substitute.
85464          */
85465         function onSubstituteNode(hint, node) {
85466             node = previousOnSubstituteNode(hint, node);
85467             if (hint === 1 /* Expression */) {
85468                 return substituteExpression(node);
85469             }
85470             return node;
85471         }
85472         function substituteExpression(node) {
85473             switch (node.kind) {
85474                 case 78 /* Identifier */:
85475                     return substituteExpressionIdentifier(node);
85476             }
85477             return node;
85478         }
85479         function substituteExpressionIdentifier(node) {
85480             return trySubstituteClassAlias(node) || node;
85481         }
85482         function trySubstituteClassAlias(node) {
85483             if (enabledSubstitutions & 1 /* ClassAliases */) {
85484                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
85485                     // Due to the emit for class decorators, any reference to the class from inside of the class body
85486                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
85487                     // behavior of class names in ES6.
85488                     // Also, when emitting statics for class expressions, we must substitute a class alias for
85489                     // constructor references in static property initializers.
85490                     var declaration = resolver.getReferencedValueDeclaration(node);
85491                     if (declaration) {
85492                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
85493                         if (classAlias) {
85494                             var clone_2 = factory.cloneNode(classAlias);
85495                             ts.setSourceMapRange(clone_2, node);
85496                             ts.setCommentRange(clone_2, node);
85497                             return clone_2;
85498                         }
85499                     }
85500                 }
85501             }
85502             return undefined;
85503         }
85504         /**
85505          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
85506          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
85507          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
85508          */
85509         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
85510             if (ts.isComputedPropertyName(name)) {
85511                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
85512                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
85513                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
85514                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
85515                 if (!alreadyTransformed && !inlinable && shouldHoist) {
85516                     var generatedName = factory.getGeneratedNameForNode(name);
85517                     hoistVariableDeclaration(generatedName);
85518                     return factory.createAssignment(generatedName, expression);
85519                 }
85520                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
85521             }
85522         }
85523         function startPrivateIdentifierEnvironment() {
85524             privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
85525             currentPrivateIdentifierEnvironment = undefined;
85526         }
85527         function endPrivateIdentifierEnvironment() {
85528             currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
85529         }
85530         function getPrivateIdentifierEnvironment() {
85531             return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map());
85532         }
85533         function getPendingExpressions() {
85534             return pendingExpressions || (pendingExpressions = []);
85535         }
85536         function addPrivateIdentifierToEnvironment(name) {
85537             var text = ts.getTextOfPropertyName(name);
85538             var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */);
85539             hoistVariableDeclaration(weakMapName);
85540             getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
85541             getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), 
85542             /*typeArguments*/ undefined, [])));
85543         }
85544         function accessPrivateIdentifier(name) {
85545             if (currentPrivateIdentifierEnvironment) {
85546                 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
85547                 if (info) {
85548                     return info;
85549                 }
85550             }
85551             for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
85552                 var env = privateIdentifierEnvironmentStack[i];
85553                 if (!env) {
85554                     continue;
85555                 }
85556                 var info = env.get(name.escapedText);
85557                 if (info) {
85558                     return info;
85559                 }
85560             }
85561             return undefined;
85562         }
85563         function wrapPrivateIdentifierForDestructuringTarget(node) {
85564             var parameter = factory.getGeneratedNameForNode(node);
85565             var info = accessPrivateIdentifier(node.name);
85566             if (!info) {
85567                 return ts.visitEachChild(node, visitor, context);
85568             }
85569             var receiver = node.expression;
85570             // We cannot copy `this` or `super` into the function because they will be bound
85571             // differently inside the function.
85572             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
85573                 receiver = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true);
85574                 getPendingExpressions().push(factory.createBinaryExpression(receiver, 62 /* EqualsToken */, node.expression));
85575             }
85576             return factory.createPropertyAccessExpression(
85577             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
85578             factory.createParenthesizedExpression(factory.createObjectLiteralExpression([
85579                 factory.createSetAccessorDeclaration(
85580                 /*decorators*/ undefined, 
85581                 /*modifiers*/ undefined, "value", [factory.createParameterDeclaration(
85582                     /*decorators*/ undefined, 
85583                     /*modifiers*/ undefined, 
85584                     /*dotDotDotToken*/ undefined, parameter, 
85585                     /*questionToken*/ undefined, 
85586                     /*type*/ undefined, 
85587                     /*initializer*/ undefined)], factory.createBlock([factory.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
85588             ])), "value");
85589         }
85590         function visitArrayAssignmentTarget(node) {
85591             var target = ts.getTargetOfBindingOrAssignmentElement(node);
85592             if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
85593                 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
85594                 if (ts.isAssignmentExpression(node)) {
85595                     return factory.updateBinaryExpression(node, wrapped, node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
85596                 }
85597                 else if (ts.isSpreadElement(node)) {
85598                     return factory.updateSpreadElement(node, wrapped);
85599                 }
85600                 else {
85601                     return wrapped;
85602                 }
85603             }
85604             return ts.visitNode(node, visitorDestructuringTarget);
85605         }
85606         function visitObjectAssignmentTarget(node) {
85607             if (ts.isPropertyAssignment(node)) {
85608                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
85609                 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
85610                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
85611                     var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
85612                     return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? factory.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
85613                 }
85614                 return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
85615             }
85616             return ts.visitNode(node, visitor);
85617         }
85618         function visitAssignmentPattern(node) {
85619             if (ts.isArrayLiteralExpression(node)) {
85620                 // Transforms private names in destructuring assignment array bindings.
85621                 //
85622                 // Source:
85623                 // ([ this.#myProp ] = [ "hello" ]);
85624                 //
85625                 // Transformation:
85626                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
85627                 return factory.updateArrayLiteralExpression(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
85628             }
85629             else {
85630                 // Transforms private names in destructuring assignment object bindings.
85631                 //
85632                 // Source:
85633                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
85634                 //
85635                 // Transformation:
85636                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
85637                 return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
85638             }
85639         }
85640     }
85641     ts.transformClassFields = transformClassFields;
85642     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
85643         return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), 
85644         /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]);
85645     }
85646 })(ts || (ts = {}));
85647 /*@internal*/
85648 var ts;
85649 (function (ts) {
85650     var ES2017SubstitutionFlags;
85651     (function (ES2017SubstitutionFlags) {
85652         /** Enables substitutions for async methods with `super` calls. */
85653         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
85654     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
85655     var ContextFlags;
85656     (function (ContextFlags) {
85657         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
85658         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
85659     })(ContextFlags || (ContextFlags = {}));
85660     function transformES2017(context) {
85661         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
85662         var resolver = context.getEmitResolver();
85663         var compilerOptions = context.getCompilerOptions();
85664         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
85665         /**
85666          * Keeps track of whether expression substitution has been enabled for specific edge cases.
85667          * They are persisted between each SourceFile transformation and should not be reset.
85668          */
85669         var enabledSubstitutions;
85670         /**
85671          * This keeps track of containers where `super` is valid, for use with
85672          * just-in-time substitution for `super` expressions inside of async methods.
85673          */
85674         var enclosingSuperContainerFlags = 0;
85675         var enclosingFunctionParameterNames;
85676         /**
85677          * Keeps track of property names accessed on super (`super.x`) within async functions.
85678          */
85679         var capturedSuperProperties;
85680         /** Whether the async function contains an element access on super (`super[x]`). */
85681         var hasSuperElementAccess;
85682         /** A set of node IDs for generated super accessors (variable statements). */
85683         var substitutedSuperAccessors = [];
85684         var contextFlags = 0;
85685         // Save the previous transformation hooks.
85686         var previousOnEmitNode = context.onEmitNode;
85687         var previousOnSubstituteNode = context.onSubstituteNode;
85688         // Set new transformation hooks.
85689         context.onEmitNode = onEmitNode;
85690         context.onSubstituteNode = onSubstituteNode;
85691         return ts.chainBundle(context, transformSourceFile);
85692         function transformSourceFile(node) {
85693             if (node.isDeclarationFile) {
85694                 return node;
85695             }
85696             setContextFlag(1 /* NonTopLevel */, false);
85697             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
85698             var visited = ts.visitEachChild(node, visitor, context);
85699             ts.addEmitHelpers(visited, context.readEmitHelpers());
85700             return visited;
85701         }
85702         function setContextFlag(flag, val) {
85703             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
85704         }
85705         function inContext(flags) {
85706             return (contextFlags & flags) !== 0;
85707         }
85708         function inTopLevelContext() {
85709             return !inContext(1 /* NonTopLevel */);
85710         }
85711         function inHasLexicalThisContext() {
85712             return inContext(2 /* HasLexicalThis */);
85713         }
85714         function doWithContext(flags, cb, value) {
85715             var contextFlagsToSet = flags & ~contextFlags;
85716             if (contextFlagsToSet) {
85717                 setContextFlag(contextFlagsToSet, /*val*/ true);
85718                 var result = cb(value);
85719                 setContextFlag(contextFlagsToSet, /*val*/ false);
85720                 return result;
85721             }
85722             return cb(value);
85723         }
85724         function visitDefault(node) {
85725             return ts.visitEachChild(node, visitor, context);
85726         }
85727         function visitor(node) {
85728             if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
85729                 return node;
85730             }
85731             switch (node.kind) {
85732                 case 129 /* AsyncKeyword */:
85733                     // ES2017 async modifier should be elided for targets < ES2017
85734                     return undefined;
85735                 case 213 /* AwaitExpression */:
85736                     return visitAwaitExpression(node);
85737                 case 165 /* MethodDeclaration */:
85738                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
85739                 case 251 /* FunctionDeclaration */:
85740                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
85741                 case 208 /* FunctionExpression */:
85742                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
85743                 case 209 /* ArrowFunction */:
85744                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
85745                 case 201 /* PropertyAccessExpression */:
85746                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) {
85747                         capturedSuperProperties.add(node.name.escapedText);
85748                     }
85749                     return ts.visitEachChild(node, visitor, context);
85750                 case 202 /* ElementAccessExpression */:
85751                     if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) {
85752                         hasSuperElementAccess = true;
85753                     }
85754                     return ts.visitEachChild(node, visitor, context);
85755                 case 167 /* GetAccessor */:
85756                 case 168 /* SetAccessor */:
85757                 case 166 /* Constructor */:
85758                 case 252 /* ClassDeclaration */:
85759                 case 221 /* ClassExpression */:
85760                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
85761                 default:
85762                     return ts.visitEachChild(node, visitor, context);
85763             }
85764         }
85765         function asyncBodyVisitor(node) {
85766             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
85767                 switch (node.kind) {
85768                     case 232 /* VariableStatement */:
85769                         return visitVariableStatementInAsyncBody(node);
85770                     case 237 /* ForStatement */:
85771                         return visitForStatementInAsyncBody(node);
85772                     case 238 /* ForInStatement */:
85773                         return visitForInStatementInAsyncBody(node);
85774                     case 239 /* ForOfStatement */:
85775                         return visitForOfStatementInAsyncBody(node);
85776                     case 287 /* CatchClause */:
85777                         return visitCatchClauseInAsyncBody(node);
85778                     case 230 /* Block */:
85779                     case 244 /* SwitchStatement */:
85780                     case 258 /* CaseBlock */:
85781                     case 284 /* CaseClause */:
85782                     case 285 /* DefaultClause */:
85783                     case 247 /* TryStatement */:
85784                     case 235 /* DoStatement */:
85785                     case 236 /* WhileStatement */:
85786                     case 234 /* IfStatement */:
85787                     case 243 /* WithStatement */:
85788                     case 245 /* LabeledStatement */:
85789                         return ts.visitEachChild(node, asyncBodyVisitor, context);
85790                     default:
85791                         return ts.Debug.assertNever(node, "Unhandled node.");
85792                 }
85793             }
85794             return visitor(node);
85795         }
85796         function visitCatchClauseInAsyncBody(node) {
85797             var catchClauseNames = new ts.Set();
85798             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
85799             // names declared in a catch variable are block scoped
85800             var catchClauseUnshadowedNames;
85801             catchClauseNames.forEach(function (_, escapedName) {
85802                 if (enclosingFunctionParameterNames.has(escapedName)) {
85803                     if (!catchClauseUnshadowedNames) {
85804                         catchClauseUnshadowedNames = new ts.Set(enclosingFunctionParameterNames);
85805                     }
85806                     catchClauseUnshadowedNames.delete(escapedName);
85807                 }
85808             });
85809             if (catchClauseUnshadowedNames) {
85810                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
85811                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
85812                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
85813                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
85814                 return result;
85815             }
85816             else {
85817                 return ts.visitEachChild(node, asyncBodyVisitor, context);
85818             }
85819         }
85820         function visitVariableStatementInAsyncBody(node) {
85821             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
85822                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
85823                 return expression ? factory.createExpressionStatement(expression) : undefined;
85824             }
85825             return ts.visitEachChild(node, visitor, context);
85826         }
85827         function visitForInStatementInAsyncBody(node) {
85828             return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer)
85829                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
85830                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock));
85831         }
85832         function visitForOfStatementInAsyncBody(node) {
85833             return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
85834                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
85835                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock));
85836         }
85837         function visitForStatementInAsyncBody(node) {
85838             var initializer = node.initializer; // TODO: GH#18217
85839             return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer)
85840                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
85841                 : 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, factory.liftToBlock));
85842         }
85843         /**
85844          * Visits an AwaitExpression node.
85845          *
85846          * This function will be called any time a ES2017 await expression is encountered.
85847          *
85848          * @param node The node to visit.
85849          */
85850         function visitAwaitExpression(node) {
85851             // do not downlevel a top-level await as it is module syntax...
85852             if (inTopLevelContext()) {
85853                 return ts.visitEachChild(node, visitor, context);
85854             }
85855             return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
85856             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
85857         }
85858         /**
85859          * Visits a MethodDeclaration node.
85860          *
85861          * This function will be called when one of the following conditions are met:
85862          * - The node is marked as async
85863          *
85864          * @param node The node to visit.
85865          */
85866         function visitMethodDeclaration(node) {
85867             return factory.updateMethodDeclaration(node, 
85868             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
85869             /*questionToken*/ undefined, 
85870             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
85871             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
85872                 ? transformAsyncFunctionBody(node)
85873                 : ts.visitFunctionBody(node.body, visitor, context));
85874         }
85875         /**
85876          * Visits a FunctionDeclaration node.
85877          *
85878          * This function will be called when one of the following conditions are met:
85879          * - The node is marked async
85880          *
85881          * @param node The node to visit.
85882          */
85883         function visitFunctionDeclaration(node) {
85884             return factory.updateFunctionDeclaration(node, 
85885             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
85886             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
85887             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
85888                 ? transformAsyncFunctionBody(node)
85889                 : ts.visitFunctionBody(node.body, visitor, context));
85890         }
85891         /**
85892          * Visits a FunctionExpression node.
85893          *
85894          * This function will be called when one of the following conditions are met:
85895          * - The node is marked async
85896          *
85897          * @param node The node to visit.
85898          */
85899         function visitFunctionExpression(node) {
85900             return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
85901             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
85902             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
85903                 ? transformAsyncFunctionBody(node)
85904                 : ts.visitFunctionBody(node.body, visitor, context));
85905         }
85906         /**
85907          * Visits an ArrowFunction.
85908          *
85909          * This function will be called when one of the following conditions are met:
85910          * - The node is marked async
85911          *
85912          * @param node The node to visit.
85913          */
85914         function visitArrowFunction(node) {
85915             return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
85916             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
85917             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
85918                 ? transformAsyncFunctionBody(node)
85919                 : ts.visitFunctionBody(node.body, visitor, context));
85920         }
85921         function recordDeclarationName(_a, names) {
85922             var name = _a.name;
85923             if (ts.isIdentifier(name)) {
85924                 names.add(name.escapedText);
85925             }
85926             else {
85927                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
85928                     var element = _b[_i];
85929                     if (!ts.isOmittedExpression(element)) {
85930                         recordDeclarationName(element, names);
85931                     }
85932                 }
85933             }
85934         }
85935         function isVariableDeclarationListWithCollidingName(node) {
85936             return !!node
85937                 && ts.isVariableDeclarationList(node)
85938                 && !(node.flags & 3 /* BlockScoped */)
85939                 && node.declarations.some(collidesWithParameterName);
85940         }
85941         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
85942             hoistVariableDeclarationList(node);
85943             var variables = ts.getInitializedVariables(node);
85944             if (variables.length === 0) {
85945                 if (hasReceiver) {
85946                     return ts.visitNode(factory.converters.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
85947                 }
85948                 return undefined;
85949             }
85950             return factory.inlineExpressions(ts.map(variables, transformInitializedVariable));
85951         }
85952         function hoistVariableDeclarationList(node) {
85953             ts.forEach(node.declarations, hoistVariable);
85954         }
85955         function hoistVariable(_a) {
85956             var name = _a.name;
85957             if (ts.isIdentifier(name)) {
85958                 hoistVariableDeclaration(name);
85959             }
85960             else {
85961                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
85962                     var element = _b[_i];
85963                     if (!ts.isOmittedExpression(element)) {
85964                         hoistVariable(element);
85965                     }
85966                 }
85967             }
85968         }
85969         function transformInitializedVariable(node) {
85970             var converted = ts.setSourceMapRange(factory.createAssignment(factory.converters.convertToAssignmentElementTarget(node.name), node.initializer), node);
85971             return ts.visitNode(converted, visitor, ts.isExpression);
85972         }
85973         function collidesWithParameterName(_a) {
85974             var name = _a.name;
85975             if (ts.isIdentifier(name)) {
85976                 return enclosingFunctionParameterNames.has(name.escapedText);
85977             }
85978             else {
85979                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
85980                     var element = _b[_i];
85981                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
85982                         return true;
85983                     }
85984                 }
85985             }
85986             return false;
85987         }
85988         function transformAsyncFunctionBody(node) {
85989             resumeLexicalEnvironment();
85990             var original = ts.getOriginalNode(node, ts.isFunctionLike);
85991             var nodeType = original.type;
85992             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
85993             var isArrowFunction = node.kind === 209 /* ArrowFunction */;
85994             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
85995             // An async function is emit as an outer function that calls an inner
85996             // generator function. To preserve lexical bindings, we pass the current
85997             // `this` and `arguments` objects to `__awaiter`. The generator function
85998             // passed to `__awaiter` is executed inside of the callback to the
85999             // promise constructor.
86000             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
86001             enclosingFunctionParameterNames = new ts.Set();
86002             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
86003                 var parameter = _a[_i];
86004                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
86005             }
86006             var savedCapturedSuperProperties = capturedSuperProperties;
86007             var savedHasSuperElementAccess = hasSuperElementAccess;
86008             if (!isArrowFunction) {
86009                 capturedSuperProperties = new ts.Set();
86010                 hasSuperElementAccess = false;
86011             }
86012             var result;
86013             if (!isArrowFunction) {
86014                 var statements = [];
86015                 var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
86016                 statements.push(factory.createReturnStatement(emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
86017                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86018                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
86019                 // This step isn't needed if we eventually transform this to ES5.
86020                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
86021                 if (emitSuperHelpers) {
86022                     enableSubstitutionForAsyncMethodsWithSuper();
86023                     if (capturedSuperProperties.size) {
86024                         var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
86025                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
86026                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
86027                     }
86028                 }
86029                 var block = factory.createBlock(statements, /*multiLine*/ true);
86030                 ts.setTextRange(block, node.body);
86031                 if (emitSuperHelpers && hasSuperElementAccess) {
86032                     // Emit helpers for super element access expressions (`super[x]`).
86033                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
86034                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
86035                     }
86036                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
86037                         ts.addEmitHelper(block, ts.asyncSuperHelper);
86038                     }
86039                 }
86040                 result = block;
86041             }
86042             else {
86043                 var expression = emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
86044                 var declarations = endLexicalEnvironment();
86045                 if (ts.some(declarations)) {
86046                     var block = factory.converters.convertToFunctionBlock(expression);
86047                     result = factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
86048                 }
86049                 else {
86050                     result = expression;
86051                 }
86052             }
86053             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
86054             if (!isArrowFunction) {
86055                 capturedSuperProperties = savedCapturedSuperProperties;
86056                 hasSuperElementAccess = savedHasSuperElementAccess;
86057             }
86058             return result;
86059         }
86060         function transformAsyncFunctionBodyWorker(body, start) {
86061             if (ts.isBlock(body)) {
86062                 return factory.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
86063             }
86064             else {
86065                 return factory.converters.convertToFunctionBlock(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
86066             }
86067         }
86068         function getPromiseConstructor(type) {
86069             var typeName = type && ts.getEntityNameFromTypeNode(type);
86070             if (typeName && ts.isEntityName(typeName)) {
86071                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
86072                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
86073                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
86074                     return typeName;
86075                 }
86076             }
86077             return undefined;
86078         }
86079         function enableSubstitutionForAsyncMethodsWithSuper() {
86080             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
86081                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
86082                 // We need to enable substitutions for call, property access, and element access
86083                 // if we need to rewrite super calls.
86084                 context.enableSubstitution(203 /* CallExpression */);
86085                 context.enableSubstitution(201 /* PropertyAccessExpression */);
86086                 context.enableSubstitution(202 /* ElementAccessExpression */);
86087                 // We need to be notified when entering and exiting declarations that bind super.
86088                 context.enableEmitNotification(252 /* ClassDeclaration */);
86089                 context.enableEmitNotification(165 /* MethodDeclaration */);
86090                 context.enableEmitNotification(167 /* GetAccessor */);
86091                 context.enableEmitNotification(168 /* SetAccessor */);
86092                 context.enableEmitNotification(166 /* Constructor */);
86093                 // We need to be notified when entering the generated accessor arrow functions.
86094                 context.enableEmitNotification(232 /* VariableStatement */);
86095             }
86096         }
86097         /**
86098          * Hook for node emit.
86099          *
86100          * @param hint A hint as to the intended usage of the node.
86101          * @param node The node to emit.
86102          * @param emit A callback used to emit the node in the printer.
86103          */
86104         function onEmitNode(hint, node, emitCallback) {
86105             // If we need to support substitutions for `super` in an async method,
86106             // we should track it here.
86107             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
86108                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
86109                 if (superContainerFlags !== enclosingSuperContainerFlags) {
86110                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
86111                     enclosingSuperContainerFlags = superContainerFlags;
86112                     previousOnEmitNode(hint, node, emitCallback);
86113                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
86114                     return;
86115                 }
86116             }
86117             // Disable substitution in the generated super accessor itself.
86118             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
86119                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
86120                 enclosingSuperContainerFlags = 0;
86121                 previousOnEmitNode(hint, node, emitCallback);
86122                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
86123                 return;
86124             }
86125             previousOnEmitNode(hint, node, emitCallback);
86126         }
86127         /**
86128          * Hooks node substitutions.
86129          *
86130          * @param hint A hint as to the intended usage of the node.
86131          * @param node The node to substitute.
86132          */
86133         function onSubstituteNode(hint, node) {
86134             node = previousOnSubstituteNode(hint, node);
86135             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
86136                 return substituteExpression(node);
86137             }
86138             return node;
86139         }
86140         function substituteExpression(node) {
86141             switch (node.kind) {
86142                 case 201 /* PropertyAccessExpression */:
86143                     return substitutePropertyAccessExpression(node);
86144                 case 202 /* ElementAccessExpression */:
86145                     return substituteElementAccessExpression(node);
86146                 case 203 /* CallExpression */:
86147                     return substituteCallExpression(node);
86148             }
86149             return node;
86150         }
86151         function substitutePropertyAccessExpression(node) {
86152             if (node.expression.kind === 105 /* SuperKeyword */) {
86153                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
86154             }
86155             return node;
86156         }
86157         function substituteElementAccessExpression(node) {
86158             if (node.expression.kind === 105 /* SuperKeyword */) {
86159                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
86160             }
86161             return node;
86162         }
86163         function substituteCallExpression(node) {
86164             var expression = node.expression;
86165             if (ts.isSuperProperty(expression)) {
86166                 var argumentExpression = ts.isPropertyAccessExpression(expression)
86167                     ? substitutePropertyAccessExpression(expression)
86168                     : substituteElementAccessExpression(expression);
86169                 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"), 
86170                 /*typeArguments*/ undefined, __spreadArrays([
86171                     factory.createThis()
86172                 ], node.arguments));
86173             }
86174             return node;
86175         }
86176         function isSuperContainer(node) {
86177             var kind = node.kind;
86178             return kind === 252 /* ClassDeclaration */
86179                 || kind === 166 /* Constructor */
86180                 || kind === 165 /* MethodDeclaration */
86181                 || kind === 167 /* GetAccessor */
86182                 || kind === 168 /* SetAccessor */;
86183         }
86184         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
86185             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
86186                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), 
86187                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
86188             }
86189             else {
86190                 return ts.setTextRange(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), 
86191                 /*typeArguments*/ undefined, [argumentExpression]), location);
86192             }
86193         }
86194     }
86195     ts.transformES2017 = transformES2017;
86196     /** Creates a variable named `_super` with accessor properties for the given property names. */
86197     function createSuperAccessVariableStatement(factory, resolver, node, names) {
86198         // Create a variable declaration with a getter/setter (if binding) definition for each name:
86199         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
86200         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
86201         var accessors = [];
86202         names.forEach(function (_, key) {
86203             var name = ts.unescapeLeadingUnderscores(key);
86204             var getterAndSetter = [];
86205             getterAndSetter.push(factory.createPropertyAssignment("get", factory.createArrowFunction(
86206             /* modifiers */ undefined, 
86207             /* typeParameters */ undefined, 
86208             /* parameters */ [], 
86209             /* type */ undefined, 
86210             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
86211             if (hasBinding) {
86212                 getterAndSetter.push(factory.createPropertyAssignment("set", factory.createArrowFunction(
86213                 /* modifiers */ undefined, 
86214                 /* typeParameters */ undefined, 
86215                 /* parameters */ [
86216                     factory.createParameterDeclaration(
86217                     /* decorators */ undefined, 
86218                     /* modifiers */ undefined, 
86219                     /* dotDotDotToken */ undefined, "v", 
86220                     /* questionToken */ undefined, 
86221                     /* type */ undefined, 
86222                     /* initializer */ undefined)
86223                 ], 
86224                 /* type */ undefined, 
86225                 /* equalsGreaterThanToken */ undefined, factory.createAssignment(ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), factory.createIdentifier("v")))));
86226             }
86227             accessors.push(factory.createPropertyAssignment(name, factory.createObjectLiteralExpression(getterAndSetter)));
86228         });
86229         return factory.createVariableStatement(
86230         /* modifiers */ undefined, factory.createVariableDeclarationList([
86231             factory.createVariableDeclaration(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), 
86232             /*exclamationToken*/ undefined, 
86233             /* type */ undefined, factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "create"), 
86234             /* typeArguments */ undefined, [
86235                 factory.createNull(),
86236                 factory.createObjectLiteralExpression(accessors, /* multiline */ true)
86237             ]))
86238         ], 2 /* Const */));
86239     }
86240     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
86241 })(ts || (ts = {}));
86242 /*@internal*/
86243 var ts;
86244 (function (ts) {
86245     var ESNextSubstitutionFlags;
86246     (function (ESNextSubstitutionFlags) {
86247         /** Enables substitutions for async methods with `super` calls. */
86248         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
86249     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
86250     // Facts we track as we traverse the tree
86251     var HierarchyFacts;
86252     (function (HierarchyFacts) {
86253         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
86254         //
86255         // Ancestor facts
86256         //
86257         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
86258         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
86259         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
86260         //
86261         // Ancestor masks
86262         //
86263         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
86264         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
86265         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
86266         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
86267         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
86268         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
86269         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
86270         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
86271         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
86272         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
86273     })(HierarchyFacts || (HierarchyFacts = {}));
86274     function transformES2018(context) {
86275         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
86276         var resolver = context.getEmitResolver();
86277         var compilerOptions = context.getCompilerOptions();
86278         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
86279         var previousOnEmitNode = context.onEmitNode;
86280         context.onEmitNode = onEmitNode;
86281         var previousOnSubstituteNode = context.onSubstituteNode;
86282         context.onSubstituteNode = onSubstituteNode;
86283         var exportedVariableStatement = false;
86284         var enabledSubstitutions;
86285         var enclosingFunctionFlags;
86286         var enclosingSuperContainerFlags = 0;
86287         var hierarchyFacts = 0;
86288         var currentSourceFile;
86289         var taggedTemplateStringDeclarations;
86290         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
86291         var capturedSuperProperties;
86292         /** Whether the async function contains an element access on super (`super[x]`). */
86293         var hasSuperElementAccess;
86294         /** A set of node IDs for generated super accessors. */
86295         var substitutedSuperAccessors = [];
86296         return ts.chainBundle(context, transformSourceFile);
86297         function affectsSubtree(excludeFacts, includeFacts) {
86298             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
86299         }
86300         /**
86301          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
86302          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
86303          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
86304          */
86305         function enterSubtree(excludeFacts, includeFacts) {
86306             var ancestorFacts = hierarchyFacts;
86307             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
86308             return ancestorFacts;
86309         }
86310         /**
86311          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
86312          * subtree.
86313          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
86314          */
86315         function exitSubtree(ancestorFacts) {
86316             hierarchyFacts = ancestorFacts;
86317         }
86318         function recordTaggedTemplateString(temp) {
86319             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
86320         }
86321         function transformSourceFile(node) {
86322             if (node.isDeclarationFile) {
86323                 return node;
86324             }
86325             currentSourceFile = node;
86326             var visited = visitSourceFile(node);
86327             ts.addEmitHelpers(visited, context.readEmitHelpers());
86328             currentSourceFile = undefined;
86329             taggedTemplateStringDeclarations = undefined;
86330             return visited;
86331         }
86332         function visitor(node) {
86333             return visitorWorker(node, /*expressionResultIsUnused*/ false);
86334         }
86335         function visitorWithUnusedExpressionResult(node) {
86336             return visitorWorker(node, /*expressionResultIsUnused*/ true);
86337         }
86338         function visitorNoAsyncModifier(node) {
86339             if (node.kind === 129 /* AsyncKeyword */) {
86340                 return undefined;
86341             }
86342             return node;
86343         }
86344         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
86345             if (affectsSubtree(excludeFacts, includeFacts)) {
86346                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
86347                 var result = cb(value);
86348                 exitSubtree(ancestorFacts);
86349                 return result;
86350             }
86351             return cb(value);
86352         }
86353         function visitDefault(node) {
86354             return ts.visitEachChild(node, visitor, context);
86355         }
86356         /**
86357          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
86358          * expression of an `ExpressionStatement`).
86359          */
86360         function visitorWorker(node, expressionResultIsUnused) {
86361             if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
86362                 return node;
86363             }
86364             switch (node.kind) {
86365                 case 213 /* AwaitExpression */:
86366                     return visitAwaitExpression(node);
86367                 case 219 /* YieldExpression */:
86368                     return visitYieldExpression(node);
86369                 case 242 /* ReturnStatement */:
86370                     return visitReturnStatement(node);
86371                 case 245 /* LabeledStatement */:
86372                     return visitLabeledStatement(node);
86373                 case 200 /* ObjectLiteralExpression */:
86374                     return visitObjectLiteralExpression(node);
86375                 case 216 /* BinaryExpression */:
86376                     return visitBinaryExpression(node, expressionResultIsUnused);
86377                 case 337 /* CommaListExpression */:
86378                     return visitCommaListExpression(node, expressionResultIsUnused);
86379                 case 287 /* CatchClause */:
86380                     return visitCatchClause(node);
86381                 case 232 /* VariableStatement */:
86382                     return visitVariableStatement(node);
86383                 case 249 /* VariableDeclaration */:
86384                     return visitVariableDeclaration(node);
86385                 case 235 /* DoStatement */:
86386                 case 236 /* WhileStatement */:
86387                 case 238 /* ForInStatement */:
86388                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
86389                 case 239 /* ForOfStatement */:
86390                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
86391                 case 237 /* ForStatement */:
86392                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
86393                 case 212 /* VoidExpression */:
86394                     return visitVoidExpression(node);
86395                 case 166 /* Constructor */:
86396                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86397                 case 165 /* MethodDeclaration */:
86398                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86399                 case 167 /* GetAccessor */:
86400                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86401                 case 168 /* SetAccessor */:
86402                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86403                 case 251 /* FunctionDeclaration */:
86404                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86405                 case 208 /* FunctionExpression */:
86406                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86407                 case 209 /* ArrowFunction */:
86408                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
86409                 case 160 /* Parameter */:
86410                     return visitParameter(node);
86411                 case 233 /* ExpressionStatement */:
86412                     return visitExpressionStatement(node);
86413                 case 207 /* ParenthesizedExpression */:
86414                     return visitParenthesizedExpression(node, expressionResultIsUnused);
86415                 case 205 /* TaggedTemplateExpression */:
86416                     return visitTaggedTemplateExpression(node);
86417                 case 201 /* PropertyAccessExpression */:
86418                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) {
86419                         capturedSuperProperties.add(node.name.escapedText);
86420                     }
86421                     return ts.visitEachChild(node, visitor, context);
86422                 case 202 /* ElementAccessExpression */:
86423                     if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) {
86424                         hasSuperElementAccess = true;
86425                     }
86426                     return ts.visitEachChild(node, visitor, context);
86427                 case 252 /* ClassDeclaration */:
86428                 case 221 /* ClassExpression */:
86429                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86430                 default:
86431                     return ts.visitEachChild(node, visitor, context);
86432             }
86433         }
86434         function visitAwaitExpression(node) {
86435             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
86436                 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(ts.visitNode(node.expression, visitor, ts.isExpression))), 
86437                 /*location*/ node), node);
86438             }
86439             return ts.visitEachChild(node, visitor, context);
86440         }
86441         function visitYieldExpression(node) {
86442             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
86443                 if (node.asteriskToken) {
86444                     var expression = ts.visitNode(ts.Debug.assertDefined(node.expression), visitor, ts.isExpression);
86445                     return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
86446                     /*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(factory.updateYieldExpression(node, node.asteriskToken, ts.setTextRange(emitHelpers().createAsyncDelegatorHelper(ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), expression)), expression)))), node), node);
86447                 }
86448                 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
86449                 /*asteriskToken*/ undefined, createDownlevelAwait(node.expression
86450                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
86451                     : factory.createVoidZero())), node), node);
86452             }
86453             return ts.visitEachChild(node, visitor, context);
86454         }
86455         function visitReturnStatement(node) {
86456             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
86457                 return factory.updateReturnStatement(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : factory.createVoidZero()));
86458             }
86459             return ts.visitEachChild(node, visitor, context);
86460         }
86461         function visitLabeledStatement(node) {
86462             if (enclosingFunctionFlags & 2 /* Async */) {
86463                 var statement = ts.unwrapInnermostStatementOfLabel(node);
86464                 if (statement.kind === 239 /* ForOfStatement */ && statement.awaitModifier) {
86465                     return visitForOfStatement(statement, node);
86466                 }
86467                 return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node);
86468             }
86469             return ts.visitEachChild(node, visitor, context);
86470         }
86471         function chunkObjectLiteralElements(elements) {
86472             var chunkObject;
86473             var objects = [];
86474             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
86475                 var e = elements_4[_i];
86476                 if (e.kind === 290 /* SpreadAssignment */) {
86477                     if (chunkObject) {
86478                         objects.push(factory.createObjectLiteralExpression(chunkObject));
86479                         chunkObject = undefined;
86480                     }
86481                     var target = e.expression;
86482                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
86483                 }
86484                 else {
86485                     chunkObject = ts.append(chunkObject, e.kind === 288 /* PropertyAssignment */
86486                         ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
86487                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
86488                 }
86489             }
86490             if (chunkObject) {
86491                 objects.push(factory.createObjectLiteralExpression(chunkObject));
86492             }
86493             return objects;
86494         }
86495         function visitObjectLiteralExpression(node) {
86496             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86497                 // spread elements emit like so:
86498                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
86499                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
86500                 // If the first element is a spread element, then the first argument to __assign is {}:
86501                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
86502                 //
86503                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
86504                 // example:
86505                 //      var k = { a: 1, b: 2 };
86506                 //      var o = { a: 3, ...k, b: k.a++ };
86507                 //      // expected: { a: 1, b: 1 }
86508                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
86509                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
86510                 //
86511                 // This also occurs for spread elements, not just property assignments:
86512                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
86513                 //      var l = { c: 3 };
86514                 //      var o = { ...k, ...l };
86515                 //      // expected: { a: 1, b: 2, z: 9 }
86516                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
86517                 // end up with `{ a: 1, b: 2, c: 3 }`
86518                 var objects = chunkObjectLiteralElements(node.properties);
86519                 if (objects.length && objects[0].kind !== 200 /* ObjectLiteralExpression */) {
86520                     objects.unshift(factory.createObjectLiteralExpression());
86521                 }
86522                 var expression = objects[0];
86523                 if (objects.length > 1) {
86524                     for (var i = 1; i < objects.length; i++) {
86525                         expression = emitHelpers().createAssignHelper([expression, objects[i]]);
86526                     }
86527                     return expression;
86528                 }
86529                 else {
86530                     return emitHelpers().createAssignHelper(objects);
86531                 }
86532             }
86533             return ts.visitEachChild(node, visitor, context);
86534         }
86535         function visitExpressionStatement(node) {
86536             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
86537         }
86538         /**
86539          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
86540          * expression of an `ExpressionStatement`).
86541          */
86542         function visitParenthesizedExpression(node, expressionResultIsUnused) {
86543             return ts.visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context);
86544         }
86545         function visitSourceFile(node) {
86546             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
86547                 0 /* StrictModeSourceFileIncludes */ :
86548                 1 /* SourceFileIncludes */);
86549             exportedVariableStatement = false;
86550             var visited = ts.visitEachChild(node, visitor, context);
86551             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
86552                 factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations))
86553             ]);
86554             var result = factory.updateSourceFile(visited, ts.setTextRange(factory.createNodeArray(statement), node.statements));
86555             exitSubtree(ancestorFacts);
86556             return result;
86557         }
86558         function visitTaggedTemplateExpression(node) {
86559             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
86560         }
86561         /**
86562          * Visits a BinaryExpression that contains a destructuring assignment.
86563          *
86564          * @param node A BinaryExpression node.
86565          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
86566          * expression of an `ExpressionStatement`).
86567          */
86568         function visitBinaryExpression(node, expressionResultIsUnused) {
86569             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86570                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused);
86571             }
86572             if (node.operatorToken.kind === 27 /* CommaToken */) {
86573                 return factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorWithUnusedExpressionResult, ts.isExpression), node.operatorToken, ts.visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, ts.isExpression));
86574             }
86575             return ts.visitEachChild(node, visitor, context);
86576         }
86577         /**
86578          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
86579          * expression of an `ExpressionStatement`).
86580          */
86581         function visitCommaListExpression(node, expressionResultIsUnused) {
86582             if (expressionResultIsUnused) {
86583                 return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
86584             }
86585             var result;
86586             for (var i = 0; i < node.elements.length; i++) {
86587                 var element = node.elements[i];
86588                 var visited = ts.visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, ts.isExpression);
86589                 if (result || visited !== element) {
86590                     result || (result = node.elements.slice(0, i));
86591                     result.push(visited);
86592                 }
86593             }
86594             var elements = result ? ts.setTextRange(factory.createNodeArray(result), node.elements) : node.elements;
86595             return factory.updateCommaListExpression(node, elements);
86596         }
86597         function visitCatchClause(node) {
86598             if (node.variableDeclaration &&
86599                 ts.isBindingPattern(node.variableDeclaration.name) &&
86600                 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86601                 var name = factory.getGeneratedNameForNode(node.variableDeclaration.name);
86602                 var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name);
86603                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
86604                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
86605                 if (ts.some(visitedBindings)) {
86606                     block = factory.updateBlock(block, __spreadArrays([
86607                         factory.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
86608                     ], block.statements));
86609                 }
86610                 return factory.updateCatchClause(node, factory.updateVariableDeclaration(node.variableDeclaration, name, /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined), block);
86611             }
86612             return ts.visitEachChild(node, visitor, context);
86613         }
86614         function visitVariableStatement(node) {
86615             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
86616                 var savedExportedVariableStatement = exportedVariableStatement;
86617                 exportedVariableStatement = true;
86618                 var visited = ts.visitEachChild(node, visitor, context);
86619                 exportedVariableStatement = savedExportedVariableStatement;
86620                 return visited;
86621             }
86622             return ts.visitEachChild(node, visitor, context);
86623         }
86624         /**
86625          * Visits a VariableDeclaration node with a binding pattern.
86626          *
86627          * @param node A VariableDeclaration node.
86628          */
86629         function visitVariableDeclaration(node) {
86630             if (exportedVariableStatement) {
86631                 var savedExportedVariableStatement = exportedVariableStatement;
86632                 exportedVariableStatement = false;
86633                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
86634                 exportedVariableStatement = savedExportedVariableStatement;
86635                 return visited;
86636             }
86637             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
86638         }
86639         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
86640             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
86641             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86642                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
86643                 /*rval*/ undefined, exportedVariableStatement);
86644             }
86645             return ts.visitEachChild(node, visitor, context);
86646         }
86647         function visitForStatement(node) {
86648             return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement));
86649         }
86650         function visitVoidExpression(node) {
86651             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
86652         }
86653         /**
86654          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
86655          *
86656          * @param node A ForOfStatement.
86657          */
86658         function visitForOfStatement(node, outermostLabeledStatement) {
86659             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
86660             if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86661                 node = transformForOfStatementWithObjectRest(node);
86662             }
86663             var result = node.awaitModifier ?
86664                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
86665                 factory.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
86666             exitSubtree(ancestorFacts);
86667             return result;
86668         }
86669         function transformForOfStatementWithObjectRest(node) {
86670             var initializerWithoutParens = ts.skipParentheses(node.initializer);
86671             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
86672                 var bodyLocation = void 0;
86673                 var statementsLocation = void 0;
86674                 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
86675                 var statements = [ts.createForOfBindingStatement(factory, initializerWithoutParens, temp)];
86676                 if (ts.isBlock(node.statement)) {
86677                     ts.addRange(statements, node.statement.statements);
86678                     bodyLocation = node.statement;
86679                     statementsLocation = node.statement.statements;
86680                 }
86681                 else if (node.statement) {
86682                     ts.append(statements, node.statement);
86683                     bodyLocation = node.statement;
86684                     statementsLocation = node.statement;
86685                 }
86686                 return factory.updateForOfStatement(node, node.awaitModifier, ts.setTextRange(factory.createVariableDeclarationList([
86687                     ts.setTextRange(factory.createVariableDeclaration(temp), node.initializer)
86688                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), 
86689                 /*multiLine*/ true), bodyLocation));
86690             }
86691             return node;
86692         }
86693         function convertForOfStatementHead(node, boundValue) {
86694             var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue);
86695             var bodyLocation;
86696             var statementsLocation;
86697             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
86698             var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
86699             if (ts.isBlock(statement)) {
86700                 ts.addRange(statements, statement.statements);
86701                 bodyLocation = statement;
86702                 statementsLocation = statement.statements;
86703             }
86704             else {
86705                 statements.push(statement);
86706             }
86707             return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), 
86708             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
86709         }
86710         function createDownlevelAwait(expression) {
86711             return enclosingFunctionFlags & 1 /* Generator */
86712                 ? factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(expression))
86713                 : factory.createAwaitExpression(expression);
86714         }
86715         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
86716             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
86717             var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
86718             var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
86719             var errorRecord = factory.createUniqueName("e");
86720             var catchVariable = factory.getGeneratedNameForNode(errorRecord);
86721             var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
86722             var callValues = ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression);
86723             var callNext = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
86724             var getDone = factory.createPropertyAccessExpression(result, "done");
86725             var getValue = factory.createPropertyAccessExpression(result, "value");
86726             var callReturn = factory.createFunctionCallCall(returnMethod, iterator, []);
86727             hoistVariableDeclaration(errorRecord);
86728             hoistVariableDeclaration(returnMethod);
86729             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
86730             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
86731                 factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), callValues]) :
86732                 callValues;
86733             var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
86734             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
86735                 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
86736                 factory.createVariableDeclaration(result)
86737             ]), node.expression), 2097152 /* NoHoisting */), 
86738             /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), 
86739             /*incrementor*/ undefined, 
86740             /*statement*/ convertForOfStatementHead(node, getValue)), 
86741             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
86742             return factory.createTryStatement(factory.createBlock([
86743                 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
86744             ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
86745                 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
86746                     factory.createPropertyAssignment("error", catchVariable)
86747                 ])))
86748             ]), 1 /* SingleLine */)), factory.createBlock([
86749                 factory.createTryStatement(
86750                 /*tryBlock*/ factory.createBlock([
86751                     ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(getDone)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */)
86752                 ]), 
86753                 /*catchClause*/ undefined, 
86754                 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
86755                     ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
86756                 ]), 1 /* SingleLine */))
86757             ]));
86758         }
86759         function visitParameter(node) {
86760             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86761                 // Binding patterns are converted into a generated name and are
86762                 // evaluated inside the function body.
86763                 return factory.updateParameterDeclaration(node, 
86764                 /*decorators*/ undefined, 
86765                 /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), 
86766                 /*questionToken*/ undefined, 
86767                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
86768             }
86769             return ts.visitEachChild(node, visitor, context);
86770         }
86771         function visitConstructorDeclaration(node) {
86772             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86773             enclosingFunctionFlags = 0 /* Normal */;
86774             var updated = factory.updateConstructorDeclaration(node, 
86775             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
86776             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86777             return updated;
86778         }
86779         function visitGetAccessorDeclaration(node) {
86780             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86781             enclosingFunctionFlags = 0 /* Normal */;
86782             var updated = factory.updateGetAccessorDeclaration(node, 
86783             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
86784             /*type*/ undefined, transformFunctionBody(node));
86785             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86786             return updated;
86787         }
86788         function visitSetAccessorDeclaration(node) {
86789             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86790             enclosingFunctionFlags = 0 /* Normal */;
86791             var updated = factory.updateSetAccessorDeclaration(node, 
86792             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
86793             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86794             return updated;
86795         }
86796         function visitMethodDeclaration(node) {
86797             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86798             enclosingFunctionFlags = ts.getFunctionFlags(node);
86799             var updated = factory.updateMethodDeclaration(node, 
86800             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
86801                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
86802                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
86803                 ? undefined
86804                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
86805             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86806             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
86807                 ? transformAsyncGeneratorFunctionBody(node)
86808                 : transformFunctionBody(node));
86809             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86810             return updated;
86811         }
86812         function visitFunctionDeclaration(node) {
86813             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86814             enclosingFunctionFlags = ts.getFunctionFlags(node);
86815             var updated = factory.updateFunctionDeclaration(node, 
86816             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
86817                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
86818                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
86819                 ? undefined
86820                 : node.asteriskToken, node.name, 
86821             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86822             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
86823                 ? transformAsyncGeneratorFunctionBody(node)
86824                 : transformFunctionBody(node));
86825             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86826             return updated;
86827         }
86828         function visitArrowFunction(node) {
86829             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86830             enclosingFunctionFlags = ts.getFunctionFlags(node);
86831             var updated = factory.updateArrowFunction(node, node.modifiers, 
86832             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86833             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
86834             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86835             return updated;
86836         }
86837         function visitFunctionExpression(node) {
86838             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86839             enclosingFunctionFlags = ts.getFunctionFlags(node);
86840             var updated = factory.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
86841                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
86842                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
86843                 ? undefined
86844                 : node.asteriskToken, node.name, 
86845             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86846             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
86847                 ? transformAsyncGeneratorFunctionBody(node)
86848                 : transformFunctionBody(node));
86849             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86850             return updated;
86851         }
86852         function transformAsyncGeneratorFunctionBody(node) {
86853             resumeLexicalEnvironment();
86854             var statements = [];
86855             var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
86856             appendObjectRestAssignmentsIfNeeded(statements, node);
86857             var savedCapturedSuperProperties = capturedSuperProperties;
86858             var savedHasSuperElementAccess = hasSuperElementAccess;
86859             capturedSuperProperties = new ts.Set();
86860             hasSuperElementAccess = false;
86861             var returnStatement = factory.createReturnStatement(emitHelpers().createAsyncGeneratorHelper(factory.createFunctionExpression(
86862             /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */), node.name && factory.getGeneratedNameForNode(node.name), 
86863             /*typeParameters*/ undefined, 
86864             /*parameters*/ [], 
86865             /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
86866             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
86867             // This step isn't needed if we eventually transform this to ES5.
86868             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
86869             if (emitSuperHelpers) {
86870                 enableSubstitutionForAsyncMethodsWithSuper();
86871                 var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
86872                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
86873                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
86874             }
86875             statements.push(returnStatement);
86876             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86877             var block = factory.updateBlock(node.body, statements);
86878             if (emitSuperHelpers && hasSuperElementAccess) {
86879                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
86880                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
86881                 }
86882                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
86883                     ts.addEmitHelper(block, ts.asyncSuperHelper);
86884                 }
86885             }
86886             capturedSuperProperties = savedCapturedSuperProperties;
86887             hasSuperElementAccess = savedHasSuperElementAccess;
86888             return block;
86889         }
86890         function transformFunctionBody(node) {
86891             var _a;
86892             resumeLexicalEnvironment();
86893             var statementOffset = 0;
86894             var statements = [];
86895             var body = (_a = ts.visitNode(node.body, visitor, ts.isConciseBody)) !== null && _a !== void 0 ? _a : factory.createBlock([]);
86896             if (ts.isBlock(body)) {
86897                 statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
86898             }
86899             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
86900             var leadingStatements = endLexicalEnvironment();
86901             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
86902                 var block = factory.converters.convertToFunctionBlock(body, /*multiLine*/ true);
86903                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
86904                 ts.addRange(statements, block.statements.slice(statementOffset));
86905                 return factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(statements), block.statements));
86906             }
86907             return body;
86908         }
86909         function appendObjectRestAssignmentsIfNeeded(statements, node) {
86910             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
86911                 var parameter = _a[_i];
86912                 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86913                     var temp = factory.getGeneratedNameForNode(parameter);
86914                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
86915                     /*doNotRecordTempVariablesInLine*/ false, 
86916                     /*skipInitializer*/ true);
86917                     if (ts.some(declarations)) {
86918                         var statement = factory.createVariableStatement(
86919                         /*modifiers*/ undefined, factory.createVariableDeclarationList(declarations));
86920                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
86921                         statements = ts.append(statements, statement);
86922                     }
86923                 }
86924             }
86925             return statements;
86926         }
86927         function enableSubstitutionForAsyncMethodsWithSuper() {
86928             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
86929                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
86930                 // We need to enable substitutions for call, property access, and element access
86931                 // if we need to rewrite super calls.
86932                 context.enableSubstitution(203 /* CallExpression */);
86933                 context.enableSubstitution(201 /* PropertyAccessExpression */);
86934                 context.enableSubstitution(202 /* ElementAccessExpression */);
86935                 // We need to be notified when entering and exiting declarations that bind super.
86936                 context.enableEmitNotification(252 /* ClassDeclaration */);
86937                 context.enableEmitNotification(165 /* MethodDeclaration */);
86938                 context.enableEmitNotification(167 /* GetAccessor */);
86939                 context.enableEmitNotification(168 /* SetAccessor */);
86940                 context.enableEmitNotification(166 /* Constructor */);
86941                 // We need to be notified when entering the generated accessor arrow functions.
86942                 context.enableEmitNotification(232 /* VariableStatement */);
86943             }
86944         }
86945         /**
86946          * Called by the printer just before a node is printed.
86947          *
86948          * @param hint A hint as to the intended usage of the node.
86949          * @param node The node to be printed.
86950          * @param emitCallback The callback used to emit the node.
86951          */
86952         function onEmitNode(hint, node, emitCallback) {
86953             // If we need to support substitutions for `super` in an async method,
86954             // we should track it here.
86955             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
86956                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
86957                 if (superContainerFlags !== enclosingSuperContainerFlags) {
86958                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
86959                     enclosingSuperContainerFlags = superContainerFlags;
86960                     previousOnEmitNode(hint, node, emitCallback);
86961                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
86962                     return;
86963                 }
86964             }
86965             // Disable substitution in the generated super accessor itself.
86966             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
86967                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
86968                 enclosingSuperContainerFlags = 0;
86969                 previousOnEmitNode(hint, node, emitCallback);
86970                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
86971                 return;
86972             }
86973             previousOnEmitNode(hint, node, emitCallback);
86974         }
86975         /**
86976          * Hooks node substitutions.
86977          *
86978          * @param hint The context for the emitter.
86979          * @param node The node to substitute.
86980          */
86981         function onSubstituteNode(hint, node) {
86982             node = previousOnSubstituteNode(hint, node);
86983             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
86984                 return substituteExpression(node);
86985             }
86986             return node;
86987         }
86988         function substituteExpression(node) {
86989             switch (node.kind) {
86990                 case 201 /* PropertyAccessExpression */:
86991                     return substitutePropertyAccessExpression(node);
86992                 case 202 /* ElementAccessExpression */:
86993                     return substituteElementAccessExpression(node);
86994                 case 203 /* CallExpression */:
86995                     return substituteCallExpression(node);
86996             }
86997             return node;
86998         }
86999         function substitutePropertyAccessExpression(node) {
87000             if (node.expression.kind === 105 /* SuperKeyword */) {
87001                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
87002             }
87003             return node;
87004         }
87005         function substituteElementAccessExpression(node) {
87006             if (node.expression.kind === 105 /* SuperKeyword */) {
87007                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
87008             }
87009             return node;
87010         }
87011         function substituteCallExpression(node) {
87012             var expression = node.expression;
87013             if (ts.isSuperProperty(expression)) {
87014                 var argumentExpression = ts.isPropertyAccessExpression(expression)
87015                     ? substitutePropertyAccessExpression(expression)
87016                     : substituteElementAccessExpression(expression);
87017                 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"), 
87018                 /*typeArguments*/ undefined, __spreadArrays([
87019                     factory.createThis()
87020                 ], node.arguments));
87021             }
87022             return node;
87023         }
87024         function isSuperContainer(node) {
87025             var kind = node.kind;
87026             return kind === 252 /* ClassDeclaration */
87027                 || kind === 166 /* Constructor */
87028                 || kind === 165 /* MethodDeclaration */
87029                 || kind === 167 /* GetAccessor */
87030                 || kind === 168 /* SetAccessor */;
87031         }
87032         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
87033             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
87034                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), 
87035                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
87036             }
87037             else {
87038                 return ts.setTextRange(factory.createCallExpression(factory.createIdentifier("_superIndex"), 
87039                 /*typeArguments*/ undefined, [argumentExpression]), location);
87040             }
87041         }
87042     }
87043     ts.transformES2018 = transformES2018;
87044 })(ts || (ts = {}));
87045 /*@internal*/
87046 var ts;
87047 (function (ts) {
87048     function transformES2019(context) {
87049         var factory = context.factory;
87050         return ts.chainBundle(context, transformSourceFile);
87051         function transformSourceFile(node) {
87052             if (node.isDeclarationFile) {
87053                 return node;
87054             }
87055             return ts.visitEachChild(node, visitor, context);
87056         }
87057         function visitor(node) {
87058             if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
87059                 return node;
87060             }
87061             switch (node.kind) {
87062                 case 287 /* CatchClause */:
87063                     return visitCatchClause(node);
87064                 default:
87065                     return ts.visitEachChild(node, visitor, context);
87066             }
87067         }
87068         function visitCatchClause(node) {
87069             if (!node.variableDeclaration) {
87070                 return factory.updateCatchClause(node, factory.createVariableDeclaration(factory.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
87071             }
87072             return ts.visitEachChild(node, visitor, context);
87073         }
87074     }
87075     ts.transformES2019 = transformES2019;
87076 })(ts || (ts = {}));
87077 /*@internal*/
87078 var ts;
87079 (function (ts) {
87080     function transformES2020(context) {
87081         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
87082         return ts.chainBundle(context, transformSourceFile);
87083         function transformSourceFile(node) {
87084             if (node.isDeclarationFile) {
87085                 return node;
87086             }
87087             return ts.visitEachChild(node, visitor, context);
87088         }
87089         function visitor(node) {
87090             if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
87091                 return node;
87092             }
87093             switch (node.kind) {
87094                 case 201 /* PropertyAccessExpression */:
87095                 case 202 /* ElementAccessExpression */:
87096                 case 203 /* CallExpression */:
87097                     if (node.flags & 32 /* OptionalChain */) {
87098                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
87099                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
87100                         return updated;
87101                     }
87102                     return ts.visitEachChild(node, visitor, context);
87103                 case 216 /* BinaryExpression */:
87104                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
87105                         return transformNullishCoalescingExpression(node);
87106                     }
87107                     return ts.visitEachChild(node, visitor, context);
87108                 case 210 /* DeleteExpression */:
87109                     return visitDeleteExpression(node);
87110                 default:
87111                     return ts.visitEachChild(node, visitor, context);
87112             }
87113         }
87114         function flattenChain(chain) {
87115             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
87116             var links = [chain];
87117             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
87118                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
87119                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
87120                 links.unshift(chain);
87121             }
87122             return { expression: chain.expression, chain: links };
87123         }
87124         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
87125             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
87126             if (ts.isSyntheticReference(expression)) {
87127                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
87128                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
87129                 return factory.createSyntheticReferenceExpression(factory.updateParenthesizedExpression(node, expression.expression), expression.thisArg);
87130             }
87131             return factory.updateParenthesizedExpression(node, expression);
87132         }
87133         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
87134             if (ts.isOptionalChain(node)) {
87135                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
87136                 return visitOptionalExpression(node, captureThisArg, isDelete);
87137             }
87138             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87139             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
87140             var thisArg;
87141             if (captureThisArg) {
87142                 if (!ts.isSimpleCopiableExpression(expression)) {
87143                     thisArg = factory.createTempVariable(hoistVariableDeclaration);
87144                     expression = factory.createAssignment(thisArg, expression);
87145                     // if (inParameterInitializer) tempVariableInParameter = true;
87146                 }
87147                 else {
87148                     thisArg = expression;
87149                 }
87150             }
87151             expression = node.kind === 201 /* PropertyAccessExpression */
87152                 ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
87153                 : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
87154             return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression;
87155         }
87156         function visitNonOptionalCallExpression(node, captureThisArg) {
87157             if (ts.isOptionalChain(node)) {
87158                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
87159                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
87160             }
87161             return ts.visitEachChild(node, visitor, context);
87162         }
87163         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
87164             switch (node.kind) {
87165                 case 207 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
87166                 case 201 /* PropertyAccessExpression */:
87167                 case 202 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
87168                 case 203 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
87169                 default: return ts.visitNode(node, visitor, ts.isExpression);
87170             }
87171         }
87172         function visitOptionalExpression(node, captureThisArg, isDelete) {
87173             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
87174             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
87175             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
87176             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
87177             var capturedLeft = leftExpression;
87178             if (!ts.isSimpleCopiableExpression(leftExpression)) {
87179                 capturedLeft = factory.createTempVariable(hoistVariableDeclaration);
87180                 leftExpression = factory.createAssignment(capturedLeft, leftExpression);
87181                 // if (inParameterInitializer) tempVariableInParameter = true;
87182             }
87183             var rightExpression = capturedLeft;
87184             var thisArg;
87185             for (var i = 0; i < chain.length; i++) {
87186                 var segment = chain[i];
87187                 switch (segment.kind) {
87188                     case 201 /* PropertyAccessExpression */:
87189                     case 202 /* ElementAccessExpression */:
87190                         if (i === chain.length - 1 && captureThisArg) {
87191                             if (!ts.isSimpleCopiableExpression(rightExpression)) {
87192                                 thisArg = factory.createTempVariable(hoistVariableDeclaration);
87193                                 rightExpression = factory.createAssignment(thisArg, rightExpression);
87194                                 // if (inParameterInitializer) tempVariableInParameter = true;
87195                             }
87196                             else {
87197                                 thisArg = rightExpression;
87198                             }
87199                         }
87200                         rightExpression = segment.kind === 201 /* PropertyAccessExpression */
87201                             ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
87202                             : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
87203                         break;
87204                     case 203 /* CallExpression */:
87205                         if (i === 0 && leftThisArg) {
87206                             rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
87207                         }
87208                         else {
87209                             rightExpression = factory.createCallExpression(rightExpression, 
87210                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
87211                         }
87212                         break;
87213                 }
87214                 ts.setOriginalNode(rightExpression, segment);
87215             }
87216             var target = isDelete
87217                 ? factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createTrue(), /*colonToken*/ undefined, factory.createDeleteExpression(rightExpression))
87218                 : factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createVoidZero(), /*colonToken*/ undefined, rightExpression);
87219             return thisArg ? factory.createSyntheticReferenceExpression(target, thisArg) : target;
87220         }
87221         function createNotNullCondition(left, right, invert) {
87222             return factory.createBinaryExpression(factory.createBinaryExpression(left, factory.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), factory.createNull()), factory.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), factory.createBinaryExpression(right, factory.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), factory.createVoidZero()));
87223         }
87224         function transformNullishCoalescingExpression(node) {
87225             var left = ts.visitNode(node.left, visitor, ts.isExpression);
87226             var right = left;
87227             if (!ts.isSimpleCopiableExpression(left)) {
87228                 right = factory.createTempVariable(hoistVariableDeclaration);
87229                 left = factory.createAssignment(right, left);
87230                 // if (inParameterInitializer) tempVariableInParameter = true;
87231             }
87232             return factory.createConditionalExpression(createNotNullCondition(left, right), 
87233             /*questionToken*/ undefined, right, 
87234             /*colonToken*/ undefined, ts.visitNode(node.right, visitor, ts.isExpression));
87235         }
87236         function visitDeleteExpression(node) {
87237             return ts.isOptionalChain(ts.skipParentheses(node.expression))
87238                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
87239                 : factory.updateDeleteExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression));
87240         }
87241     }
87242     ts.transformES2020 = transformES2020;
87243 })(ts || (ts = {}));
87244 /*@internal*/
87245 var ts;
87246 (function (ts) {
87247     function transformESNext(context) {
87248         var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory;
87249         return ts.chainBundle(context, transformSourceFile);
87250         function transformSourceFile(node) {
87251             if (node.isDeclarationFile) {
87252                 return node;
87253             }
87254             return ts.visitEachChild(node, visitor, context);
87255         }
87256         function visitor(node) {
87257             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
87258                 return node;
87259             }
87260             switch (node.kind) {
87261                 case 216 /* BinaryExpression */:
87262                     var binaryExpression = node;
87263                     if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) {
87264                         return transformLogicalAssignment(binaryExpression);
87265                     }
87266                 // falls through
87267                 default:
87268                     return ts.visitEachChild(node, visitor, context);
87269             }
87270         }
87271         function transformLogicalAssignment(binaryExpression) {
87272             var operator = binaryExpression.operatorToken;
87273             var nonAssignmentOperator = ts.getNonAssignmentOperatorForCompoundAssignment(operator.kind);
87274             var left = ts.skipParentheses(ts.visitNode(binaryExpression.left, visitor, ts.isLeftHandSideExpression));
87275             var assignmentTarget = left;
87276             var right = ts.skipParentheses(ts.visitNode(binaryExpression.right, visitor, ts.isExpression));
87277             if (ts.isAccessExpression(left)) {
87278                 var propertyAccessTargetSimpleCopiable = ts.isSimpleCopiableExpression(left.expression);
87279                 var propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression :
87280                     factory.createTempVariable(hoistVariableDeclaration);
87281                 var propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory.createAssignment(propertyAccessTarget, left.expression);
87282                 if (ts.isPropertyAccessExpression(left)) {
87283                     assignmentTarget = factory.createPropertyAccessExpression(propertyAccessTarget, left.name);
87284                     left = factory.createPropertyAccessExpression(propertyAccessTargetAssignment, left.name);
87285                 }
87286                 else {
87287                     var elementAccessArgumentSimpleCopiable = ts.isSimpleCopiableExpression(left.argumentExpression);
87288                     var elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression :
87289                         factory.createTempVariable(hoistVariableDeclaration);
87290                     assignmentTarget = factory.createElementAccessExpression(propertyAccessTarget, elementAccessArgument);
87291                     left = factory.createElementAccessExpression(propertyAccessTargetAssignment, elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory.createAssignment(elementAccessArgument, left.argumentExpression));
87292                 }
87293             }
87294             return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right)));
87295         }
87296     }
87297     ts.transformESNext = transformESNext;
87298 })(ts || (ts = {}));
87299 /*@internal*/
87300 var ts;
87301 (function (ts) {
87302     function transformJsx(context) {
87303         var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
87304         var compilerOptions = context.getCompilerOptions();
87305         var currentSourceFile;
87306         var currentFileState;
87307         return ts.chainBundle(context, transformSourceFile);
87308         function getCurrentFileNameExpression() {
87309             if (currentFileState.filenameDeclaration) {
87310                 return currentFileState.filenameDeclaration.name;
87311             }
87312             var declaration = factory.createVariableDeclaration(factory.createUniqueName("_jsxFileName", 16 /* Optimistic */ | 32 /* FileLevel */), /*exclaimationToken*/ undefined, /*type*/ undefined, factory.createStringLiteral(currentSourceFile.fileName));
87313             currentFileState.filenameDeclaration = declaration;
87314             return currentFileState.filenameDeclaration.name;
87315         }
87316         function getJsxFactoryCalleePrimitive(childrenLength) {
87317             return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx";
87318         }
87319         function getJsxFactoryCallee(childrenLength) {
87320             var type = getJsxFactoryCalleePrimitive(childrenLength);
87321             return getImplicitImportForName(type);
87322         }
87323         function getImplicitJsxFragmentReference() {
87324             return getImplicitImportForName("Fragment");
87325         }
87326         function getImplicitImportForName(name) {
87327             var _a, _b;
87328             var importSource = name === "createElement"
87329                 ? currentFileState.importSpecifier
87330                 : ts.getJSXRuntimeImport(currentFileState.importSpecifier, compilerOptions);
87331             var existing = (_b = (_a = currentFileState.utilizedImplicitRuntimeImports) === null || _a === void 0 ? void 0 : _a.get(importSource)) === null || _b === void 0 ? void 0 : _b.get(name);
87332             if (existing) {
87333                 return existing.name;
87334             }
87335             if (!currentFileState.utilizedImplicitRuntimeImports) {
87336                 currentFileState.utilizedImplicitRuntimeImports = ts.createMap();
87337             }
87338             var specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource);
87339             if (!specifierSourceImports) {
87340                 specifierSourceImports = ts.createMap();
87341                 currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports);
87342             }
87343             var generatedName = factory.createUniqueName("_" + name, 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */);
87344             var specifier = factory.createImportSpecifier(factory.createIdentifier(name), generatedName);
87345             generatedName.generatedImportReference = specifier;
87346             specifierSourceImports.set(name, specifier);
87347             return generatedName;
87348         }
87349         /**
87350          * Transform JSX-specific syntax in a SourceFile.
87351          *
87352          * @param node A SourceFile node.
87353          */
87354         function transformSourceFile(node) {
87355             if (node.isDeclarationFile) {
87356                 return node;
87357             }
87358             currentSourceFile = node;
87359             currentFileState = {};
87360             currentFileState.importSpecifier = ts.getJSXImplicitImportBase(compilerOptions, node);
87361             var visited = ts.visitEachChild(node, visitor, context);
87362             ts.addEmitHelpers(visited, context.readEmitHelpers());
87363             var statements = visited.statements;
87364             if (currentFileState.filenameDeclaration) {
87365                 statements = ts.insertStatementAfterCustomPrologue(statements.slice(), factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([currentFileState.filenameDeclaration], 2 /* Const */)));
87366             }
87367             if (currentFileState.utilizedImplicitRuntimeImports) {
87368                 for (var _i = 0, _a = ts.arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries()); _i < _a.length; _i++) {
87369                     var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1];
87370                     if (ts.isExternalModule(node)) {
87371                         // Add `import` statement
87372                         var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource));
87373                         ts.setParentRecursive(importStatement, /*incremental*/ false);
87374                         statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement);
87375                     }
87376                     else if (ts.isExternalOrCommonJsModule(node)) {
87377                         // Add `require` statement
87378                         var requireStatement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([
87379                             factory.createVariableDeclaration(factory.createObjectBindingPattern(ts.map(ts.arrayFrom(importSpecifiersMap.values()), function (s) { return factory.createBindingElement(/*dotdotdot*/ undefined, s.propertyName, s.name); })), 
87380                             /*exclaimationToken*/ undefined, 
87381                             /*type*/ undefined, factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, [factory.createStringLiteral(importSource)]))
87382                         ], 2 /* Const */));
87383                         ts.setParentRecursive(requireStatement, /*incremental*/ false);
87384                         statements = ts.insertStatementAfterCustomPrologue(statements.slice(), requireStatement);
87385                     }
87386                     else {
87387                         // Do nothing (script file) - consider an error in the checker?
87388                     }
87389                 }
87390             }
87391             if (statements !== visited.statements) {
87392                 visited = factory.updateSourceFile(visited, statements);
87393             }
87394             currentFileState = undefined;
87395             return visited;
87396         }
87397         function visitor(node) {
87398             if (node.transformFlags & 2 /* ContainsJsx */) {
87399                 return visitorWorker(node);
87400             }
87401             else {
87402                 return node;
87403             }
87404         }
87405         function visitorWorker(node) {
87406             switch (node.kind) {
87407                 case 273 /* JsxElement */:
87408                     return visitJsxElement(node, /*isChild*/ false);
87409                 case 274 /* JsxSelfClosingElement */:
87410                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
87411                 case 277 /* JsxFragment */:
87412                     return visitJsxFragment(node, /*isChild*/ false);
87413                 case 283 /* JsxExpression */:
87414                     return visitJsxExpression(node);
87415                 default:
87416                     return ts.visitEachChild(node, visitor, context);
87417             }
87418         }
87419         function transformJsxChildToExpression(node) {
87420             switch (node.kind) {
87421                 case 11 /* JsxText */:
87422                     return visitJsxText(node);
87423                 case 283 /* JsxExpression */:
87424                     return visitJsxExpression(node);
87425                 case 273 /* JsxElement */:
87426                     return visitJsxElement(node, /*isChild*/ true);
87427                 case 274 /* JsxSelfClosingElement */:
87428                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
87429                 case 277 /* JsxFragment */:
87430                     return visitJsxFragment(node, /*isChild*/ true);
87431                 default:
87432                     return ts.Debug.failBadSyntaxKind(node);
87433             }
87434         }
87435         /**
87436          * The react jsx/jsxs transform falls back to `createElement` when an explicit `key` argument comes after a spread
87437          */
87438         function hasKeyAfterPropsSpread(node) {
87439             var spread = false;
87440             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
87441                 var elem = _a[_i];
87442                 if (ts.isJsxSpreadAttribute(elem)) {
87443                     spread = true;
87444                 }
87445                 else if (spread && ts.isJsxAttribute(elem) && elem.name.escapedText === "key") {
87446                     return true;
87447                 }
87448             }
87449             return false;
87450         }
87451         function shouldUseCreateElement(node) {
87452             return currentFileState.importSpecifier === undefined || hasKeyAfterPropsSpread(node);
87453         }
87454         function visitJsxElement(node, isChild) {
87455             var tagTransform = shouldUseCreateElement(node.openingElement) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
87456             return tagTransform(node.openingElement, node.children, isChild, /*location*/ node);
87457         }
87458         function visitJsxSelfClosingElement(node, isChild) {
87459             var tagTransform = shouldUseCreateElement(node) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
87460             return tagTransform(node, /*children*/ undefined, isChild, /*location*/ node);
87461         }
87462         function visitJsxFragment(node, isChild) {
87463             var tagTransform = currentFileState.importSpecifier === undefined ? visitJsxOpeningFragmentCreateElement : visitJsxOpeningFragmentJSX;
87464             return tagTransform(node.openingFragment, node.children, isChild, /*location*/ node);
87465         }
87466         function convertJsxChildrenToChildrenPropObject(children) {
87467             var nonWhitespaceChildren = ts.getSemanticJsxChildren(children);
87468             if (ts.length(nonWhitespaceChildren) === 1) {
87469                 var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]);
87470                 return result_13 && factory.createObjectLiteralExpression([
87471                     factory.createPropertyAssignment("children", result_13)
87472                 ]);
87473             }
87474             var result = ts.mapDefined(children, transformJsxChildToExpression);
87475             return !result.length ? undefined : factory.createObjectLiteralExpression([
87476                 factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result))
87477             ]);
87478         }
87479         function visitJsxOpeningLikeElementJSX(node, children, isChild, location) {
87480             var tagName = getTagName(node);
87481             var objectProperties;
87482             var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; });
87483             var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties;
87484             var segments = [];
87485             if (attrs.length) {
87486                 // Map spans of JsxAttribute nodes into object literals and spans
87487                 // of JsxSpreadAttribute nodes into expressions.
87488                 segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
87489                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
87490                     : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
87491                 if (ts.isJsxSpreadAttribute(attrs[0])) {
87492                     // We must always emit at least one object literal before a spread
87493                     // argument.factory.createObjectLiteral
87494                     segments.unshift(factory.createObjectLiteralExpression());
87495                 }
87496             }
87497             if (children && children.length) {
87498                 var result = convertJsxChildrenToChildrenPropObject(children);
87499                 if (result) {
87500                     segments.push(result);
87501                 }
87502             }
87503             if (segments.length === 0) {
87504                 objectProperties = factory.createObjectLiteralExpression([]);
87505                 // When there are no attributes, React wants {}
87506             }
87507             else {
87508                 // Either emit one big object literal (no spread attribs), or
87509                 // a call to the __assign helper.
87510                 objectProperties = ts.singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments);
87511             }
87512             return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, ts.length(ts.getSemanticJsxChildren(children || ts.emptyArray)), isChild, location);
87513         }
87514         function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, childrenLength, isChild, location) {
87515             var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)];
87516             if (compilerOptions.jsx === 5 /* ReactJSXDev */) {
87517                 var originalFile = ts.getOriginalNode(currentSourceFile);
87518                 if (originalFile && ts.isSourceFile(originalFile)) {
87519                     // isStaticChildren development flag
87520                     args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse());
87521                     // __source development flag
87522                     var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos);
87523                     args.push(factory.createObjectLiteralExpression([
87524                         factory.createPropertyAssignment("fileName", getCurrentFileNameExpression()),
87525                         factory.createPropertyAssignment("lineNumber", factory.createNumericLiteral(lineCol.line + 1)),
87526                         factory.createPropertyAssignment("columnNumber", factory.createNumericLiteral(lineCol.character + 1))
87527                     ]));
87528                     // __self development flag
87529                     args.push(factory.createThis());
87530                 }
87531             }
87532             var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), /*typeArguments*/ undefined, args), location);
87533             if (isChild) {
87534                 ts.startOnNewLine(element);
87535             }
87536             return element;
87537         }
87538         function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) {
87539             var tagName = getTagName(node);
87540             var objectProperties;
87541             var attrs = node.attributes.properties;
87542             if (attrs.length === 0) {
87543                 objectProperties = factory.createNull();
87544                 // When there are no attributes, React wants "null"
87545             }
87546             else {
87547                 // Map spans of JsxAttribute nodes into object literals and spans
87548                 // of JsxSpreadAttribute nodes into expressions.
87549                 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
87550                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
87551                     : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
87552                 if (ts.isJsxSpreadAttribute(attrs[0])) {
87553                     // We must always emit at least one object literal before a spread
87554                     // argument.factory.createObjectLiteral
87555                     segments.unshift(factory.createObjectLiteralExpression());
87556                 }
87557                 // Either emit one big object literal (no spread attribs), or
87558                 // a call to the __assign helper.
87559                 objectProperties = ts.singleOrUndefined(segments);
87560                 if (!objectProperties) {
87561                     objectProperties = emitHelpers().createAssignHelper(segments);
87562                 }
87563             }
87564             var callee = currentFileState.importSpecifier === undefined
87565                 ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
87566                 node)
87567                 : getImplicitImportForName("createElement");
87568             var element = ts.createExpressionForJsxElement(factory, callee, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), location);
87569             if (isChild) {
87570                 ts.startOnNewLine(element);
87571             }
87572             return element;
87573         }
87574         function visitJsxOpeningFragmentJSX(_node, children, isChild, location) {
87575             var childrenProps;
87576             if (children && children.length) {
87577                 var result = convertJsxChildrenToChildrenPropObject(children);
87578                 if (result) {
87579                     childrenProps = result;
87580                 }
87581             }
87582             return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), 
87583             /*keyAttr*/ undefined, ts.length(ts.getSemanticJsxChildren(children)), isChild, location);
87584         }
87585         function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) {
87586             var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
87587             ts.mapDefined(children, transformJsxChildToExpression), node, location);
87588             if (isChild) {
87589                 ts.startOnNewLine(element);
87590             }
87591             return element;
87592         }
87593         function transformJsxSpreadAttributeToExpression(node) {
87594             return ts.visitNode(node.expression, visitor, ts.isExpression);
87595         }
87596         function transformJsxAttributeToObjectLiteralElement(node) {
87597             var name = getAttributeName(node);
87598             var expression = transformJsxAttributeInitializer(node.initializer);
87599             return factory.createPropertyAssignment(name, expression);
87600         }
87601         function transformJsxAttributeInitializer(node) {
87602             if (node === undefined) {
87603                 return factory.createTrue();
87604             }
87605             else if (node.kind === 10 /* StringLiteral */) {
87606                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
87607                 // Need to be escaped to be handled correctly in a normal string
87608                 var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
87609                 var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote);
87610                 return ts.setTextRange(literal, node);
87611             }
87612             else if (node.kind === 283 /* JsxExpression */) {
87613                 if (node.expression === undefined) {
87614                     return factory.createTrue();
87615                 }
87616                 return ts.visitNode(node.expression, visitor, ts.isExpression);
87617             }
87618             else {
87619                 return ts.Debug.failBadSyntaxKind(node);
87620             }
87621         }
87622         function visitJsxText(node) {
87623             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
87624             return fixed === undefined ? undefined : factory.createStringLiteral(fixed);
87625         }
87626         /**
87627          * JSX trims whitespace at the end and beginning of lines, except that the
87628          * start/end of a tag is considered a start/end of a line only if that line is
87629          * on the same line as the closing tag. See examples in
87630          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
87631          * 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
87632          *
87633          * An equivalent algorithm would be:
87634          * - If there is only one line, return it.
87635          * - If there is only whitespace (but multiple lines), return `undefined`.
87636          * - Split the text into lines.
87637          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
87638          * - Decode entities on each line (individually).
87639          * - Remove empty lines and join the rest with " ".
87640          */
87641         function fixupWhitespaceAndDecodeEntities(text) {
87642             var acc;
87643             // First non-whitespace character on this line.
87644             var firstNonWhitespace = 0;
87645             // Last non-whitespace character on this line.
87646             var lastNonWhitespace = -1;
87647             // These initial values are special because the first line is:
87648             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
87649             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
87650             for (var i = 0; i < text.length; i++) {
87651                 var c = text.charCodeAt(i);
87652                 if (ts.isLineBreak(c)) {
87653                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
87654                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
87655                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
87656                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
87657                     }
87658                     // Reset firstNonWhitespace for the next line.
87659                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
87660                     firstNonWhitespace = -1;
87661                 }
87662                 else if (!ts.isWhiteSpaceSingleLine(c)) {
87663                     lastNonWhitespace = i;
87664                     if (firstNonWhitespace === -1) {
87665                         firstNonWhitespace = i;
87666                     }
87667                 }
87668             }
87669             return firstNonWhitespace !== -1
87670                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
87671                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
87672                 // Last line was all whitespace, so ignore it
87673                 : acc;
87674         }
87675         function addLineOfJsxText(acc, trimmedLine) {
87676             // We do not escape the string here as that is handled by the printer
87677             // when it emits the literal. We do, however, need to decode JSX entities.
87678             var decoded = decodeEntities(trimmedLine);
87679             return acc === undefined ? decoded : acc + " " + decoded;
87680         }
87681         /**
87682          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
87683          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
87684          */
87685         function decodeEntities(text) {
87686             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
87687                 if (decimal) {
87688                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
87689                 }
87690                 else if (hex) {
87691                     return ts.utf16EncodeAsString(parseInt(hex, 16));
87692                 }
87693                 else {
87694                     var ch = entities.get(word);
87695                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
87696                     return ch ? ts.utf16EncodeAsString(ch) : match;
87697                 }
87698             });
87699         }
87700         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
87701         function tryDecodeEntities(text) {
87702             var decoded = decodeEntities(text);
87703             return decoded === text ? undefined : decoded;
87704         }
87705         function getTagName(node) {
87706             if (node.kind === 273 /* JsxElement */) {
87707                 return getTagName(node.openingElement);
87708             }
87709             else {
87710                 var name = node.tagName;
87711                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
87712                     return factory.createStringLiteral(ts.idText(name));
87713                 }
87714                 else {
87715                     return ts.createExpressionFromEntityName(factory, name);
87716                 }
87717             }
87718         }
87719         /**
87720          * Emit an attribute name, which is quoted if it needs to be quoted. Because
87721          * these emit into an object literal property name, we don't need to be worried
87722          * about keywords, just non-identifier characters
87723          */
87724         function getAttributeName(node) {
87725             var name = node.name;
87726             var text = ts.idText(name);
87727             if (/^[A-Za-z_]\w*$/.test(text)) {
87728                 return name;
87729             }
87730             else {
87731                 return factory.createStringLiteral(text);
87732             }
87733         }
87734         function visitJsxExpression(node) {
87735             return ts.visitNode(node.expression, visitor, ts.isExpression);
87736         }
87737     }
87738     ts.transformJsx = transformJsx;
87739     var entities = new ts.Map(ts.getEntries({
87740         quot: 0x0022,
87741         amp: 0x0026,
87742         apos: 0x0027,
87743         lt: 0x003C,
87744         gt: 0x003E,
87745         nbsp: 0x00A0,
87746         iexcl: 0x00A1,
87747         cent: 0x00A2,
87748         pound: 0x00A3,
87749         curren: 0x00A4,
87750         yen: 0x00A5,
87751         brvbar: 0x00A6,
87752         sect: 0x00A7,
87753         uml: 0x00A8,
87754         copy: 0x00A9,
87755         ordf: 0x00AA,
87756         laquo: 0x00AB,
87757         not: 0x00AC,
87758         shy: 0x00AD,
87759         reg: 0x00AE,
87760         macr: 0x00AF,
87761         deg: 0x00B0,
87762         plusmn: 0x00B1,
87763         sup2: 0x00B2,
87764         sup3: 0x00B3,
87765         acute: 0x00B4,
87766         micro: 0x00B5,
87767         para: 0x00B6,
87768         middot: 0x00B7,
87769         cedil: 0x00B8,
87770         sup1: 0x00B9,
87771         ordm: 0x00BA,
87772         raquo: 0x00BB,
87773         frac14: 0x00BC,
87774         frac12: 0x00BD,
87775         frac34: 0x00BE,
87776         iquest: 0x00BF,
87777         Agrave: 0x00C0,
87778         Aacute: 0x00C1,
87779         Acirc: 0x00C2,
87780         Atilde: 0x00C3,
87781         Auml: 0x00C4,
87782         Aring: 0x00C5,
87783         AElig: 0x00C6,
87784         Ccedil: 0x00C7,
87785         Egrave: 0x00C8,
87786         Eacute: 0x00C9,
87787         Ecirc: 0x00CA,
87788         Euml: 0x00CB,
87789         Igrave: 0x00CC,
87790         Iacute: 0x00CD,
87791         Icirc: 0x00CE,
87792         Iuml: 0x00CF,
87793         ETH: 0x00D0,
87794         Ntilde: 0x00D1,
87795         Ograve: 0x00D2,
87796         Oacute: 0x00D3,
87797         Ocirc: 0x00D4,
87798         Otilde: 0x00D5,
87799         Ouml: 0x00D6,
87800         times: 0x00D7,
87801         Oslash: 0x00D8,
87802         Ugrave: 0x00D9,
87803         Uacute: 0x00DA,
87804         Ucirc: 0x00DB,
87805         Uuml: 0x00DC,
87806         Yacute: 0x00DD,
87807         THORN: 0x00DE,
87808         szlig: 0x00DF,
87809         agrave: 0x00E0,
87810         aacute: 0x00E1,
87811         acirc: 0x00E2,
87812         atilde: 0x00E3,
87813         auml: 0x00E4,
87814         aring: 0x00E5,
87815         aelig: 0x00E6,
87816         ccedil: 0x00E7,
87817         egrave: 0x00E8,
87818         eacute: 0x00E9,
87819         ecirc: 0x00EA,
87820         euml: 0x00EB,
87821         igrave: 0x00EC,
87822         iacute: 0x00ED,
87823         icirc: 0x00EE,
87824         iuml: 0x00EF,
87825         eth: 0x00F0,
87826         ntilde: 0x00F1,
87827         ograve: 0x00F2,
87828         oacute: 0x00F3,
87829         ocirc: 0x00F4,
87830         otilde: 0x00F5,
87831         ouml: 0x00F6,
87832         divide: 0x00F7,
87833         oslash: 0x00F8,
87834         ugrave: 0x00F9,
87835         uacute: 0x00FA,
87836         ucirc: 0x00FB,
87837         uuml: 0x00FC,
87838         yacute: 0x00FD,
87839         thorn: 0x00FE,
87840         yuml: 0x00FF,
87841         OElig: 0x0152,
87842         oelig: 0x0153,
87843         Scaron: 0x0160,
87844         scaron: 0x0161,
87845         Yuml: 0x0178,
87846         fnof: 0x0192,
87847         circ: 0x02C6,
87848         tilde: 0x02DC,
87849         Alpha: 0x0391,
87850         Beta: 0x0392,
87851         Gamma: 0x0393,
87852         Delta: 0x0394,
87853         Epsilon: 0x0395,
87854         Zeta: 0x0396,
87855         Eta: 0x0397,
87856         Theta: 0x0398,
87857         Iota: 0x0399,
87858         Kappa: 0x039A,
87859         Lambda: 0x039B,
87860         Mu: 0x039C,
87861         Nu: 0x039D,
87862         Xi: 0x039E,
87863         Omicron: 0x039F,
87864         Pi: 0x03A0,
87865         Rho: 0x03A1,
87866         Sigma: 0x03A3,
87867         Tau: 0x03A4,
87868         Upsilon: 0x03A5,
87869         Phi: 0x03A6,
87870         Chi: 0x03A7,
87871         Psi: 0x03A8,
87872         Omega: 0x03A9,
87873         alpha: 0x03B1,
87874         beta: 0x03B2,
87875         gamma: 0x03B3,
87876         delta: 0x03B4,
87877         epsilon: 0x03B5,
87878         zeta: 0x03B6,
87879         eta: 0x03B7,
87880         theta: 0x03B8,
87881         iota: 0x03B9,
87882         kappa: 0x03BA,
87883         lambda: 0x03BB,
87884         mu: 0x03BC,
87885         nu: 0x03BD,
87886         xi: 0x03BE,
87887         omicron: 0x03BF,
87888         pi: 0x03C0,
87889         rho: 0x03C1,
87890         sigmaf: 0x03C2,
87891         sigma: 0x03C3,
87892         tau: 0x03C4,
87893         upsilon: 0x03C5,
87894         phi: 0x03C6,
87895         chi: 0x03C7,
87896         psi: 0x03C8,
87897         omega: 0x03C9,
87898         thetasym: 0x03D1,
87899         upsih: 0x03D2,
87900         piv: 0x03D6,
87901         ensp: 0x2002,
87902         emsp: 0x2003,
87903         thinsp: 0x2009,
87904         zwnj: 0x200C,
87905         zwj: 0x200D,
87906         lrm: 0x200E,
87907         rlm: 0x200F,
87908         ndash: 0x2013,
87909         mdash: 0x2014,
87910         lsquo: 0x2018,
87911         rsquo: 0x2019,
87912         sbquo: 0x201A,
87913         ldquo: 0x201C,
87914         rdquo: 0x201D,
87915         bdquo: 0x201E,
87916         dagger: 0x2020,
87917         Dagger: 0x2021,
87918         bull: 0x2022,
87919         hellip: 0x2026,
87920         permil: 0x2030,
87921         prime: 0x2032,
87922         Prime: 0x2033,
87923         lsaquo: 0x2039,
87924         rsaquo: 0x203A,
87925         oline: 0x203E,
87926         frasl: 0x2044,
87927         euro: 0x20AC,
87928         image: 0x2111,
87929         weierp: 0x2118,
87930         real: 0x211C,
87931         trade: 0x2122,
87932         alefsym: 0x2135,
87933         larr: 0x2190,
87934         uarr: 0x2191,
87935         rarr: 0x2192,
87936         darr: 0x2193,
87937         harr: 0x2194,
87938         crarr: 0x21B5,
87939         lArr: 0x21D0,
87940         uArr: 0x21D1,
87941         rArr: 0x21D2,
87942         dArr: 0x21D3,
87943         hArr: 0x21D4,
87944         forall: 0x2200,
87945         part: 0x2202,
87946         exist: 0x2203,
87947         empty: 0x2205,
87948         nabla: 0x2207,
87949         isin: 0x2208,
87950         notin: 0x2209,
87951         ni: 0x220B,
87952         prod: 0x220F,
87953         sum: 0x2211,
87954         minus: 0x2212,
87955         lowast: 0x2217,
87956         radic: 0x221A,
87957         prop: 0x221D,
87958         infin: 0x221E,
87959         ang: 0x2220,
87960         and: 0x2227,
87961         or: 0x2228,
87962         cap: 0x2229,
87963         cup: 0x222A,
87964         int: 0x222B,
87965         there4: 0x2234,
87966         sim: 0x223C,
87967         cong: 0x2245,
87968         asymp: 0x2248,
87969         ne: 0x2260,
87970         equiv: 0x2261,
87971         le: 0x2264,
87972         ge: 0x2265,
87973         sub: 0x2282,
87974         sup: 0x2283,
87975         nsub: 0x2284,
87976         sube: 0x2286,
87977         supe: 0x2287,
87978         oplus: 0x2295,
87979         otimes: 0x2297,
87980         perp: 0x22A5,
87981         sdot: 0x22C5,
87982         lceil: 0x2308,
87983         rceil: 0x2309,
87984         lfloor: 0x230A,
87985         rfloor: 0x230B,
87986         lang: 0x2329,
87987         rang: 0x232A,
87988         loz: 0x25CA,
87989         spades: 0x2660,
87990         clubs: 0x2663,
87991         hearts: 0x2665,
87992         diams: 0x2666
87993     }));
87994 })(ts || (ts = {}));
87995 /*@internal*/
87996 var ts;
87997 (function (ts) {
87998     function transformES2016(context) {
87999         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
88000         return ts.chainBundle(context, transformSourceFile);
88001         function transformSourceFile(node) {
88002             if (node.isDeclarationFile) {
88003                 return node;
88004             }
88005             return ts.visitEachChild(node, visitor, context);
88006         }
88007         function visitor(node) {
88008             if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
88009                 return node;
88010             }
88011             switch (node.kind) {
88012                 case 216 /* BinaryExpression */:
88013                     return visitBinaryExpression(node);
88014                 default:
88015                     return ts.visitEachChild(node, visitor, context);
88016             }
88017         }
88018         function visitBinaryExpression(node) {
88019             switch (node.operatorToken.kind) {
88020                 case 66 /* AsteriskAsteriskEqualsToken */:
88021                     return visitExponentiationAssignmentExpression(node);
88022                 case 42 /* AsteriskAsteriskToken */:
88023                     return visitExponentiationExpression(node);
88024                 default:
88025                     return ts.visitEachChild(node, visitor, context);
88026             }
88027         }
88028         function visitExponentiationAssignmentExpression(node) {
88029             var target;
88030             var value;
88031             var left = ts.visitNode(node.left, visitor, ts.isExpression);
88032             var right = ts.visitNode(node.right, visitor, ts.isExpression);
88033             if (ts.isElementAccessExpression(left)) {
88034                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
88035                 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
88036                 var argumentExpressionTemp = factory.createTempVariable(hoistVariableDeclaration);
88037                 target = ts.setTextRange(factory.createElementAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(factory.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
88038                 value = ts.setTextRange(factory.createElementAccessExpression(expressionTemp, argumentExpressionTemp), left);
88039             }
88040             else if (ts.isPropertyAccessExpression(left)) {
88041                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
88042                 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
88043                 target = ts.setTextRange(factory.createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
88044                 value = ts.setTextRange(factory.createPropertyAccessExpression(expressionTemp, left.name), left);
88045             }
88046             else {
88047                 // Transforms `a **= b` into `a = Math.pow(a, b)`
88048                 target = left;
88049                 value = left;
88050             }
88051             return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [value, right]), node)), node);
88052         }
88053         function visitExponentiationExpression(node) {
88054             // Transforms `a ** b` into `Math.pow(a, b)`
88055             var left = ts.visitNode(node.left, visitor, ts.isExpression);
88056             var right = ts.visitNode(node.right, visitor, ts.isExpression);
88057             return ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [left, right]), node);
88058         }
88059     }
88060     ts.transformES2016 = transformES2016;
88061 })(ts || (ts = {}));
88062 /*@internal*/
88063 var ts;
88064 (function (ts) {
88065     var ES2015SubstitutionFlags;
88066     (function (ES2015SubstitutionFlags) {
88067         /** Enables substitutions for captured `this` */
88068         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
88069         /** Enables substitutions for block-scoped bindings. */
88070         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
88071     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
88072     var LoopOutParameterFlags;
88073     (function (LoopOutParameterFlags) {
88074         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
88075         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
88076     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
88077     var CopyDirection;
88078     (function (CopyDirection) {
88079         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
88080         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
88081     })(CopyDirection || (CopyDirection = {}));
88082     var Jump;
88083     (function (Jump) {
88084         Jump[Jump["Break"] = 2] = "Break";
88085         Jump[Jump["Continue"] = 4] = "Continue";
88086         Jump[Jump["Return"] = 8] = "Return";
88087     })(Jump || (Jump = {}));
88088     // Facts we track as we traverse the tree
88089     var HierarchyFacts;
88090     (function (HierarchyFacts) {
88091         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
88092         //
88093         // Ancestor facts
88094         //
88095         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
88096         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
88097         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
88098         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
88099         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
88100         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
88101         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
88102         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
88103         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
88104         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
88105         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
88106         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
88107         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
88108         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
88109         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
88110         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
88111         //
88112         // Ancestor masks
88113         //
88114         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
88115         // We are always in *some* kind of block scope, but only specific block-scope containers are
88116         // top-level or Blocks.
88117         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
88118         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
88119         // A source file is a top-level block scope.
88120         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
88121         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
88122         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
88123         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
88124         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
88125         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
88126         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
88127         // Arrow functions are lexically scoped to their container, but are new block scopes.
88128         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
88129         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
88130         // Constructors are both new lexical scopes and new block scopes. Constructors are also
88131         // always considered non-static members of a class.
88132         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
88133         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
88134         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
88135         // within an IterationStatement to indicate whether the embedded statement is an
88136         // IterationStatementBlock.
88137         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
88138         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
88139         // 'for' statements are new block scopes and have special handling for 'let' declarations.
88140         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
88141         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
88142         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
88143         // 'let' declarations.
88144         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
88145         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
88146         // Blocks (other than function bodies) are new block scopes.
88147         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
88148         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
88149         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
88150         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
88151         //
88152         // Subtree facts
88153         //
88154         HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
88155         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
88156         //
88157         // Subtree masks
88158         //
88159         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
88160         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
88161         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
88162     })(HierarchyFacts || (HierarchyFacts = {}));
88163     function transformES2015(context) {
88164         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
88165         var compilerOptions = context.getCompilerOptions();
88166         var resolver = context.getEmitResolver();
88167         var previousOnSubstituteNode = context.onSubstituteNode;
88168         var previousOnEmitNode = context.onEmitNode;
88169         context.onEmitNode = onEmitNode;
88170         context.onSubstituteNode = onSubstituteNode;
88171         var currentSourceFile;
88172         var currentText;
88173         var hierarchyFacts;
88174         var taggedTemplateStringDeclarations;
88175         function recordTaggedTemplateString(temp) {
88176             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
88177         }
88178         /**
88179          * Used to track if we are emitting body of the converted loop
88180          */
88181         var convertedLoopState;
88182         /**
88183          * Keeps track of whether substitutions have been enabled for specific cases.
88184          * They are persisted between each SourceFile transformation and should not
88185          * be reset.
88186          */
88187         var enabledSubstitutions;
88188         return ts.chainBundle(context, transformSourceFile);
88189         function transformSourceFile(node) {
88190             if (node.isDeclarationFile) {
88191                 return node;
88192             }
88193             currentSourceFile = node;
88194             currentText = node.text;
88195             var visited = visitSourceFile(node);
88196             ts.addEmitHelpers(visited, context.readEmitHelpers());
88197             currentSourceFile = undefined;
88198             currentText = undefined;
88199             taggedTemplateStringDeclarations = undefined;
88200             hierarchyFacts = 0 /* None */;
88201             return visited;
88202         }
88203         /**
88204          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
88205          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
88206          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
88207          */
88208         function enterSubtree(excludeFacts, includeFacts) {
88209             var ancestorFacts = hierarchyFacts;
88210             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
88211             return ancestorFacts;
88212         }
88213         /**
88214          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
88215          * subtree, propagating specific facts from the subtree.
88216          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
88217          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
88218          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
88219          */
88220         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
88221             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
88222         }
88223         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
88224             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
88225                 && node.kind === 242 /* ReturnStatement */
88226                 && !node.expression;
88227         }
88228         function isOrMayContainReturnCompletion(node) {
88229             return node.transformFlags & 1048576 /* ContainsHoistedDeclarationOrCompletion */
88230                 && (ts.isReturnStatement(node)
88231                     || ts.isIfStatement(node)
88232                     || ts.isWithStatement(node)
88233                     || ts.isSwitchStatement(node)
88234                     || ts.isCaseBlock(node)
88235                     || ts.isCaseClause(node)
88236                     || ts.isDefaultClause(node)
88237                     || ts.isTryStatement(node)
88238                     || ts.isCatchClause(node)
88239                     || ts.isLabeledStatement(node)
88240                     || ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)
88241                     || ts.isBlock(node));
88242         }
88243         function shouldVisitNode(node) {
88244             return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
88245                 || convertedLoopState !== undefined
88246                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node))
88247                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
88248                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
88249         }
88250         function visitor(node) {
88251             return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ false) : node;
88252         }
88253         function visitorWithUnusedExpressionResult(node) {
88254             return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ true) : node;
88255         }
88256         function callExpressionVisitor(node) {
88257             if (node.kind === 105 /* SuperKeyword */) {
88258                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
88259             }
88260             return visitor(node);
88261         }
88262         function visitorWorker(node, expressionResultIsUnused) {
88263             switch (node.kind) {
88264                 case 123 /* StaticKeyword */:
88265                     return undefined; // elide static keyword
88266                 case 252 /* ClassDeclaration */:
88267                     return visitClassDeclaration(node);
88268                 case 221 /* ClassExpression */:
88269                     return visitClassExpression(node);
88270                 case 160 /* Parameter */:
88271                     return visitParameter(node);
88272                 case 251 /* FunctionDeclaration */:
88273                     return visitFunctionDeclaration(node);
88274                 case 209 /* ArrowFunction */:
88275                     return visitArrowFunction(node);
88276                 case 208 /* FunctionExpression */:
88277                     return visitFunctionExpression(node);
88278                 case 249 /* VariableDeclaration */:
88279                     return visitVariableDeclaration(node);
88280                 case 78 /* Identifier */:
88281                     return visitIdentifier(node);
88282                 case 250 /* VariableDeclarationList */:
88283                     return visitVariableDeclarationList(node);
88284                 case 244 /* SwitchStatement */:
88285                     return visitSwitchStatement(node);
88286                 case 258 /* CaseBlock */:
88287                     return visitCaseBlock(node);
88288                 case 230 /* Block */:
88289                     return visitBlock(node, /*isFunctionBody*/ false);
88290                 case 241 /* BreakStatement */:
88291                 case 240 /* ContinueStatement */:
88292                     return visitBreakOrContinueStatement(node);
88293                 case 245 /* LabeledStatement */:
88294                     return visitLabeledStatement(node);
88295                 case 235 /* DoStatement */:
88296                 case 236 /* WhileStatement */:
88297                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
88298                 case 237 /* ForStatement */:
88299                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
88300                 case 238 /* ForInStatement */:
88301                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
88302                 case 239 /* ForOfStatement */:
88303                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
88304                 case 233 /* ExpressionStatement */:
88305                     return visitExpressionStatement(node);
88306                 case 200 /* ObjectLiteralExpression */:
88307                     return visitObjectLiteralExpression(node);
88308                 case 287 /* CatchClause */:
88309                     return visitCatchClause(node);
88310                 case 289 /* ShorthandPropertyAssignment */:
88311                     return visitShorthandPropertyAssignment(node);
88312                 case 158 /* ComputedPropertyName */:
88313                     return visitComputedPropertyName(node);
88314                 case 199 /* ArrayLiteralExpression */:
88315                     return visitArrayLiteralExpression(node);
88316                 case 203 /* CallExpression */:
88317                     return visitCallExpression(node);
88318                 case 204 /* NewExpression */:
88319                     return visitNewExpression(node);
88320                 case 207 /* ParenthesizedExpression */:
88321                     return visitParenthesizedExpression(node, expressionResultIsUnused);
88322                 case 216 /* BinaryExpression */:
88323                     return visitBinaryExpression(node, expressionResultIsUnused);
88324                 case 337 /* CommaListExpression */:
88325                     return visitCommaListExpression(node, expressionResultIsUnused);
88326                 case 14 /* NoSubstitutionTemplateLiteral */:
88327                 case 15 /* TemplateHead */:
88328                 case 16 /* TemplateMiddle */:
88329                 case 17 /* TemplateTail */:
88330                     return visitTemplateLiteral(node);
88331                 case 10 /* StringLiteral */:
88332                     return visitStringLiteral(node);
88333                 case 8 /* NumericLiteral */:
88334                     return visitNumericLiteral(node);
88335                 case 205 /* TaggedTemplateExpression */:
88336                     return visitTaggedTemplateExpression(node);
88337                 case 218 /* TemplateExpression */:
88338                     return visitTemplateExpression(node);
88339                 case 219 /* YieldExpression */:
88340                     return visitYieldExpression(node);
88341                 case 220 /* SpreadElement */:
88342                     return visitSpreadElement(node);
88343                 case 105 /* SuperKeyword */:
88344                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
88345                 case 107 /* ThisKeyword */:
88346                     return visitThisKeyword(node);
88347                 case 226 /* MetaProperty */:
88348                     return visitMetaProperty(node);
88349                 case 165 /* MethodDeclaration */:
88350                     return visitMethodDeclaration(node);
88351                 case 167 /* GetAccessor */:
88352                 case 168 /* SetAccessor */:
88353                     return visitAccessorDeclaration(node);
88354                 case 232 /* VariableStatement */:
88355                     return visitVariableStatement(node);
88356                 case 242 /* ReturnStatement */:
88357                     return visitReturnStatement(node);
88358                 case 212 /* VoidExpression */:
88359                     return visitVoidExpression(node);
88360                 default:
88361                     return ts.visitEachChild(node, visitor, context);
88362             }
88363         }
88364         function visitSourceFile(node) {
88365             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
88366             var prologue = [];
88367             var statements = [];
88368             startLexicalEnvironment();
88369             var statementOffset = factory.copyPrologue(node.statements, prologue, /*ensureUseStrict*/ false, visitor);
88370             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
88371             if (taggedTemplateStringDeclarations) {
88372                 statements.push(factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations)));
88373             }
88374             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
88375             insertCaptureThisForNodeIfNeeded(prologue, node);
88376             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
88377             return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
88378         }
88379         function visitSwitchStatement(node) {
88380             if (convertedLoopState !== undefined) {
88381                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
88382                 // for switch statement allow only non-labeled break
88383                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
88384                 var result = ts.visitEachChild(node, visitor, context);
88385                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
88386                 return result;
88387             }
88388             return ts.visitEachChild(node, visitor, context);
88389         }
88390         function visitCaseBlock(node) {
88391             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
88392             var updated = ts.visitEachChild(node, visitor, context);
88393             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
88394             return updated;
88395         }
88396         function returnCapturedThis(node) {
88397             return ts.setOriginalNode(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)), node);
88398         }
88399         function visitReturnStatement(node) {
88400             if (convertedLoopState) {
88401                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
88402                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
88403                     node = returnCapturedThis(node);
88404                 }
88405                 return factory.createReturnStatement(factory.createObjectLiteralExpression([
88406                     factory.createPropertyAssignment(factory.createIdentifier("value"), node.expression
88407                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
88408                         : factory.createVoidZero())
88409                 ]));
88410             }
88411             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
88412                 return returnCapturedThis(node);
88413             }
88414             return ts.visitEachChild(node, visitor, context);
88415         }
88416         function visitThisKeyword(node) {
88417             if (hierarchyFacts & 2 /* ArrowFunction */) {
88418                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
88419             }
88420             if (convertedLoopState) {
88421                 if (hierarchyFacts & 2 /* ArrowFunction */) {
88422                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
88423                     convertedLoopState.containsLexicalThis = true;
88424                     return node;
88425                 }
88426                 return convertedLoopState.thisName || (convertedLoopState.thisName = factory.createUniqueName("this"));
88427             }
88428             return node;
88429         }
88430         function visitVoidExpression(node) {
88431             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
88432         }
88433         function visitIdentifier(node) {
88434             if (!convertedLoopState) {
88435                 return node;
88436             }
88437             if (resolver.isArgumentsLocalBinding(node)) {
88438                 return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments"));
88439             }
88440             return node;
88441         }
88442         function visitBreakOrContinueStatement(node) {
88443             if (convertedLoopState) {
88444                 // check if we can emit break/continue as is
88445                 // it is possible if either
88446                 //   - break/continue is labeled and label is located inside the converted loop
88447                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
88448                 var jump = node.kind === 241 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
88449                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
88450                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
88451                 if (!canUseBreakOrContinue) {
88452                     var labelMarker = void 0;
88453                     var label = node.label;
88454                     if (!label) {
88455                         if (node.kind === 241 /* BreakStatement */) {
88456                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
88457                             labelMarker = "break";
88458                         }
88459                         else {
88460                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
88461                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
88462                             labelMarker = "continue";
88463                         }
88464                     }
88465                     else {
88466                         if (node.kind === 241 /* BreakStatement */) {
88467                             labelMarker = "break-" + label.escapedText;
88468                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
88469                         }
88470                         else {
88471                             labelMarker = "continue-" + label.escapedText;
88472                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
88473                         }
88474                     }
88475                     var returnExpression = factory.createStringLiteral(labelMarker);
88476                     if (convertedLoopState.loopOutParameters.length) {
88477                         var outParams = convertedLoopState.loopOutParameters;
88478                         var expr = void 0;
88479                         for (var i = 0; i < outParams.length; i++) {
88480                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
88481                             if (i === 0) {
88482                                 expr = copyExpr;
88483                             }
88484                             else {
88485                                 expr = factory.createBinaryExpression(expr, 27 /* CommaToken */, copyExpr);
88486                             }
88487                         }
88488                         returnExpression = factory.createBinaryExpression(expr, 27 /* CommaToken */, returnExpression);
88489                     }
88490                     return factory.createReturnStatement(returnExpression);
88491                 }
88492             }
88493             return ts.visitEachChild(node, visitor, context);
88494         }
88495         /**
88496          * Visits a ClassDeclaration and transforms it into a variable statement.
88497          *
88498          * @param node A ClassDeclaration node.
88499          */
88500         function visitClassDeclaration(node) {
88501             // [source]
88502             //      class C { }
88503             //
88504             // [output]
88505             //      var C = (function () {
88506             //          function C() {
88507             //          }
88508             //          return C;
88509             //      }());
88510             var variable = factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ true), 
88511             /*exclamationToken*/ undefined, 
88512             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
88513             ts.setOriginalNode(variable, node);
88514             var statements = [];
88515             var statement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([variable]));
88516             ts.setOriginalNode(statement, node);
88517             ts.setTextRange(statement, node);
88518             ts.startOnNewLine(statement);
88519             statements.push(statement);
88520             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
88521             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
88522                 var exportStatement = ts.hasSyntacticModifier(node, 512 /* Default */)
88523                     ? factory.createExportDefault(factory.getLocalName(node))
88524                     : factory.createExternalModuleExport(factory.getLocalName(node));
88525                 ts.setOriginalNode(exportStatement, statement);
88526                 statements.push(exportStatement);
88527             }
88528             var emitFlags = ts.getEmitFlags(node);
88529             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
88530                 // Add a DeclarationMarker as a marker for the end of the declaration
88531                 statements.push(factory.createEndOfDeclarationMarker(node));
88532                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
88533             }
88534             return ts.singleOrMany(statements);
88535         }
88536         /**
88537          * Visits a ClassExpression and transforms it into an expression.
88538          *
88539          * @param node A ClassExpression node.
88540          */
88541         function visitClassExpression(node) {
88542             // [source]
88543             //      C = class { }
88544             //
88545             // [output]
88546             //      C = (function () {
88547             //          function class_1() {
88548             //          }
88549             //          return class_1;
88550             //      }())
88551             return transformClassLikeDeclarationToExpression(node);
88552         }
88553         /**
88554          * Transforms a ClassExpression or ClassDeclaration into an expression.
88555          *
88556          * @param node A ClassExpression or ClassDeclaration node.
88557          */
88558         function transformClassLikeDeclarationToExpression(node) {
88559             // [source]
88560             //      class C extends D {
88561             //          constructor() {}
88562             //          method() {}
88563             //          get prop() {}
88564             //          set prop(v) {}
88565             //      }
88566             //
88567             // [output]
88568             //      (function (_super) {
88569             //          __extends(C, _super);
88570             //          function C() {
88571             //          }
88572             //          C.prototype.method = function () {}
88573             //          Object.defineProperty(C.prototype, "prop", {
88574             //              get: function() {},
88575             //              set: function() {},
88576             //              enumerable: true,
88577             //              configurable: true
88578             //          });
88579             //          return C;
88580             //      }(D))
88581             if (node.name) {
88582                 enableSubstitutionsForBlockScopedBindings();
88583             }
88584             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
88585             var classFunction = factory.createFunctionExpression(
88586             /*modifiers*/ undefined, 
88587             /*asteriskToken*/ undefined, 
88588             /*name*/ undefined, 
88589             /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */))] : [], 
88590             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
88591             // To preserve the behavior of the old emitter, we explicitly indent
88592             // the body of the function here if it was requested in an earlier
88593             // transformation.
88594             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
88595             // "inner" and "outer" below are added purely to preserve source map locations from
88596             // the old emitter
88597             var inner = factory.createPartiallyEmittedExpression(classFunction);
88598             ts.setTextRangeEnd(inner, node.end);
88599             ts.setEmitFlags(inner, 1536 /* NoComments */);
88600             var outer = factory.createPartiallyEmittedExpression(inner);
88601             ts.setTextRangeEnd(outer, ts.skipTrivia(currentText, node.pos));
88602             ts.setEmitFlags(outer, 1536 /* NoComments */);
88603             var result = factory.createParenthesizedExpression(factory.createCallExpression(outer, 
88604             /*typeArguments*/ undefined, extendsClauseElement
88605                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
88606                 : []));
88607             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
88608             return result;
88609         }
88610         /**
88611          * Transforms a ClassExpression or ClassDeclaration into a function body.
88612          *
88613          * @param node A ClassExpression or ClassDeclaration node.
88614          * @param extendsClauseElement The expression for the class `extends` clause.
88615          */
88616         function transformClassBody(node, extendsClauseElement) {
88617             var statements = [];
88618             var name = factory.getInternalName(node);
88619             var constructorLikeName = ts.isIdentifierANonContextualKeyword(name) ? factory.getGeneratedNameForNode(name) : name;
88620             startLexicalEnvironment();
88621             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
88622             addConstructor(statements, node, constructorLikeName, extendsClauseElement);
88623             addClassMembers(statements, node);
88624             // Create a synthetic text range for the return statement.
88625             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
88626             // The following partially-emitted expression exists purely to align our sourcemap
88627             // emit with the original emitter.
88628             var outer = factory.createPartiallyEmittedExpression(constructorLikeName);
88629             ts.setTextRangeEnd(outer, closingBraceLocation.end);
88630             ts.setEmitFlags(outer, 1536 /* NoComments */);
88631             var statement = factory.createReturnStatement(outer);
88632             ts.setTextRangePos(statement, closingBraceLocation.pos);
88633             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
88634             statements.push(statement);
88635             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
88636             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
88637             ts.setEmitFlags(block, 1536 /* NoComments */);
88638             return block;
88639         }
88640         /**
88641          * Adds a call to the `__extends` helper if needed for a class.
88642          *
88643          * @param statements The statements of the class body function.
88644          * @param node The ClassExpression or ClassDeclaration node.
88645          * @param extendsClauseElement The expression for the class `extends` clause.
88646          */
88647         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
88648             if (extendsClauseElement) {
88649                 statements.push(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExtendsHelper(factory.getInternalName(node))), 
88650                 /*location*/ extendsClauseElement));
88651             }
88652         }
88653         /**
88654          * Adds the constructor of the class to a class body function.
88655          *
88656          * @param statements The statements of the class body function.
88657          * @param node The ClassExpression or ClassDeclaration node.
88658          * @param extendsClauseElement The expression for the class `extends` clause.
88659          */
88660         function addConstructor(statements, node, name, extendsClauseElement) {
88661             var savedConvertedLoopState = convertedLoopState;
88662             convertedLoopState = undefined;
88663             var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
88664             var constructor = ts.getFirstConstructorWithBody(node);
88665             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
88666             var constructorFunction = factory.createFunctionDeclaration(
88667             /*decorators*/ undefined, 
88668             /*modifiers*/ undefined, 
88669             /*asteriskToken*/ undefined, name, 
88670             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
88671             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
88672             ts.setTextRange(constructorFunction, constructor || node);
88673             if (extendsClauseElement) {
88674                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
88675             }
88676             statements.push(constructorFunction);
88677             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
88678             convertedLoopState = savedConvertedLoopState;
88679         }
88680         /**
88681          * Transforms the parameters of the constructor declaration of a class.
88682          *
88683          * @param constructor The constructor for the class.
88684          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
88685          *                            synthesized `super` call.
88686          */
88687         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
88688             // If the TypeScript transformer needed to synthesize a constructor for property
88689             // initializers, it would have also added a synthetic `...args` parameter and
88690             // `super` call.
88691             // If this is the case, we do not include the synthetic `...args` parameter and
88692             // will instead use the `arguments` object in ES5/3.
88693             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
88694                 || [];
88695         }
88696         function createDefaultConstructorBody(node, isDerivedClass) {
88697             // We must be here because the user didn't write a constructor
88698             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
88699             // If that's the case we can just immediately return the result of a 'super()' call.
88700             var statements = [];
88701             resumeLexicalEnvironment();
88702             factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
88703             if (isDerivedClass) {
88704                 // return _super !== null && _super.apply(this, arguments) || this;
88705                 statements.push(factory.createReturnStatement(createDefaultSuperCallOrThis()));
88706             }
88707             var statementsArray = factory.createNodeArray(statements);
88708             ts.setTextRange(statementsArray, node.members);
88709             var block = factory.createBlock(statementsArray, /*multiLine*/ true);
88710             ts.setTextRange(block, node);
88711             ts.setEmitFlags(block, 1536 /* NoComments */);
88712             return block;
88713         }
88714         /**
88715          * Transforms the body of a constructor declaration of a class.
88716          *
88717          * @param constructor The constructor for the class.
88718          * @param node The node which contains the constructor.
88719          * @param extendsClauseElement The expression for the class `extends` clause.
88720          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
88721          *                            synthesized `super` call.
88722          */
88723         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
88724             // determine whether the class is known syntactically to be a derived class (e.g. a
88725             // class that extends a value that is not syntactically known to be `null`).
88726             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */;
88727             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
88728             // representation:
88729             //
88730             // ```
88731             // // es2015 (source)
88732             // class C extends Base { }
88733             //
88734             // // es5 (transformed)
88735             // var C = (function (_super) {
88736             //     function C() {
88737             //         return _super.apply(this, arguments) || this;
88738             //     }
88739             //     return C;
88740             // })(Base);
88741             // ```
88742             if (!constructor)
88743                 return createDefaultConstructorBody(node, isDerivedClass);
88744             // The prologue will contain all leading standard and custom prologue statements added by this transform
88745             var prologue = [];
88746             var statements = [];
88747             resumeLexicalEnvironment();
88748             // If a super call has already been synthesized,
88749             // we're going to assume that we should just transform everything after that.
88750             // The assumption is that no prior step in the pipeline has added any prologue directives.
88751             var statementOffset = 0;
88752             if (!hasSynthesizedSuper)
88753                 statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, /*ensureUseStrict*/ false);
88754             addDefaultValueAssignmentsIfNeeded(statements, constructor);
88755             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
88756             if (!hasSynthesizedSuper)
88757                 statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor);
88758             // If the first statement is a call to `super()`, visit the statement directly
88759             var superCallExpression;
88760             if (hasSynthesizedSuper) {
88761                 superCallExpression = createDefaultSuperCallOrThis();
88762             }
88763             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
88764                 var firstStatement = constructor.body.statements[statementOffset];
88765                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
88766                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
88767                 }
88768             }
88769             if (superCallExpression) {
88770                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
88771                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
88772             }
88773             // visit the remaining statements
88774             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
88775             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
88776             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
88777             if (isDerivedClass) {
88778                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
88779                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
88780                     // following representation:
88781                     //
88782                     // ```
88783                     // // es2015 (source)
88784                     // class C extends Base {
88785                     //     constructor() {
88786                     //         super("foo");
88787                     //     }
88788                     // }
88789                     //
88790                     // // es5 (transformed)
88791                     // var C = (function (_super) {
88792                     //     function C() {
88793                     //         return _super.call(this, "foo") || this;
88794                     //     }
88795                     //     return C;
88796                     // })(Base);
88797                     // ```
88798                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
88799                     var returnStatement = factory.createReturnStatement(superCallExpression);
88800                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
88801                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
88802                     statements.push(returnStatement);
88803                 }
88804                 else {
88805                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
88806                     //
88807                     // ```
88808                     // // es2015 (source)
88809                     // class C extends Base {
88810                     //     constructor() {
88811                     //         super("foo");
88812                     //         this.x = 1;
88813                     //     }
88814                     // }
88815                     //
88816                     // // es5 (transformed)
88817                     // var C = (function (_super) {
88818                     //     function C() {
88819                     //         var _this = _super.call(this, "foo") || this;
88820                     //         _this.x = 1;
88821                     //         return _this;
88822                     //     }
88823                     //     return C;
88824                     // })(Base);
88825                     // ```
88826                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
88827                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
88828                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
88829                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
88830                         statements.push(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)));
88831                     }
88832                 }
88833             }
88834             else {
88835                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
88836                 // captured when necessitated by an arrow function capturing the lexical `this`:
88837                 //
88838                 // ```
88839                 // // es2015
88840                 // class C {}
88841                 //
88842                 // // es5
88843                 // var C = (function () {
88844                 //     function C() {
88845                 //     }
88846                 //     return C;
88847                 // })();
88848                 // ```
88849                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
88850             }
88851             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), 
88852             /*location*/ constructor.body.statements), 
88853             /*multiLine*/ true);
88854             ts.setTextRange(block, constructor.body);
88855             return block;
88856         }
88857         /**
88858          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
88859          * It would generate obviously dead code, so we'll try to make things a little bit prettier
88860          * by doing a minimal check on whether some common patterns always explicitly return.
88861          */
88862         function isSufficientlyCoveredByReturnStatements(statement) {
88863             // A return statement is considered covered.
88864             if (statement.kind === 242 /* ReturnStatement */) {
88865                 return true;
88866             }
88867             // An if-statement with two covered branches is covered.
88868             else if (statement.kind === 234 /* IfStatement */) {
88869                 var ifStatement = statement;
88870                 if (ifStatement.elseStatement) {
88871                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
88872                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
88873                 }
88874             }
88875             // A block is covered if it has a last statement which is covered.
88876             else if (statement.kind === 230 /* Block */) {
88877                 var lastStatement = ts.lastOrUndefined(statement.statements);
88878                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
88879                     return true;
88880                 }
88881             }
88882             return false;
88883         }
88884         function createActualThis() {
88885             return ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */);
88886         }
88887         function createDefaultSuperCallOrThis() {
88888             return factory.createLogicalOr(factory.createLogicalAnd(factory.createStrictInequality(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), factory.createNull()), factory.createFunctionApplyCall(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), createActualThis(), factory.createIdentifier("arguments"))), createActualThis());
88889         }
88890         /**
88891          * Visits a parameter declaration.
88892          *
88893          * @param node A ParameterDeclaration node.
88894          */
88895         function visitParameter(node) {
88896             if (node.dotDotDotToken) {
88897                 // rest parameters are elided
88898                 return undefined;
88899             }
88900             else if (ts.isBindingPattern(node.name)) {
88901                 // Binding patterns are converted into a generated name and are
88902                 // evaluated inside the function body.
88903                 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
88904                 /*decorators*/ undefined, 
88905                 /*modifiers*/ undefined, 
88906                 /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), 
88907                 /*questionToken*/ undefined, 
88908                 /*type*/ undefined, 
88909                 /*initializer*/ undefined), 
88910                 /*location*/ node), 
88911                 /*original*/ node);
88912             }
88913             else if (node.initializer) {
88914                 // Initializers are elided
88915                 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
88916                 /*decorators*/ undefined, 
88917                 /*modifiers*/ undefined, 
88918                 /*dotDotDotToken*/ undefined, node.name, 
88919                 /*questionToken*/ undefined, 
88920                 /*type*/ undefined, 
88921                 /*initializer*/ undefined), 
88922                 /*location*/ node), 
88923                 /*original*/ node);
88924             }
88925             else {
88926                 return node;
88927             }
88928         }
88929         function hasDefaultValueOrBindingPattern(node) {
88930             return node.initializer !== undefined
88931                 || ts.isBindingPattern(node.name);
88932         }
88933         /**
88934          * Adds statements to the body of a function-like node if it contains parameters with
88935          * binding patterns or initializers.
88936          *
88937          * @param statements The statements for the new function body.
88938          * @param node A function-like node.
88939          */
88940         function addDefaultValueAssignmentsIfNeeded(statements, node) {
88941             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
88942                 return false;
88943             }
88944             var added = false;
88945             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
88946                 var parameter = _a[_i];
88947                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
88948                 // A rest parameter cannot have a binding pattern or an initializer,
88949                 // so let's just ignore it.
88950                 if (dotDotDotToken) {
88951                     continue;
88952                 }
88953                 if (ts.isBindingPattern(name)) {
88954                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
88955                 }
88956                 else if (initializer) {
88957                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
88958                     added = true;
88959                 }
88960             }
88961             return added;
88962         }
88963         /**
88964          * Adds statements to the body of a function-like node for parameters with binding patterns
88965          *
88966          * @param statements The statements for the new function body.
88967          * @param parameter The parameter for the function.
88968          * @param name The name of the parameter.
88969          * @param initializer The initializer for the parameter.
88970          */
88971         function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
88972             // In cases where a binding pattern is simply '[]' or '{}',
88973             // we usually don't want to emit a var declaration; however, in the presence
88974             // of an initializer, we must emit that expression to preserve side effects.
88975             if (name.elements.length > 0) {
88976                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createVariableStatement(
88977                 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, factory.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
88978                 return true;
88979             }
88980             else if (initializer) {
88981                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createExpressionStatement(factory.createAssignment(factory.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
88982                 return true;
88983             }
88984             return false;
88985         }
88986         /**
88987          * Adds statements to the body of a function-like node for parameters with initializers.
88988          *
88989          * @param statements The statements for the new function body.
88990          * @param parameter The parameter for the function.
88991          * @param name The name of the parameter.
88992          * @param initializer The initializer for the parameter.
88993          */
88994         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
88995             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
88996             var statement = factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
88997                 factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(
88998                 // TODO(rbuckton): Does this need to be parented?
88999                 ts.setEmitFlags(ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
89000             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
89001             ts.startOnNewLine(statement);
89002             ts.setTextRange(statement, parameter);
89003             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
89004             ts.insertStatementAfterCustomPrologue(statements, statement);
89005         }
89006         /**
89007          * Gets a value indicating whether we need to add statements to handle a rest parameter.
89008          *
89009          * @param node A ParameterDeclaration node.
89010          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
89011          *                                          part of a constructor declaration with a
89012          *                                          synthesized call to `super`
89013          */
89014         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
89015             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
89016         }
89017         /**
89018          * Adds statements to the body of a function-like node if it contains a rest parameter.
89019          *
89020          * @param statements The statements for the new function body.
89021          * @param node A function-like node.
89022          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
89023          *                                          part of a constructor declaration with a
89024          *                                          synthesized call to `super`
89025          */
89026         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
89027             var prologueStatements = [];
89028             var parameter = ts.lastOrUndefined(node.parameters);
89029             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
89030                 return false;
89031             }
89032             // `declarationName` is the name of the local declaration for the parameter.
89033             // TODO(rbuckton): Does this need to be parented?
89034             var declarationName = parameter.name.kind === 78 /* Identifier */ ? ts.setParent(ts.setTextRange(factory.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory.createTempVariable(/*recordTempVariable*/ undefined);
89035             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
89036             // `expressionName` is the name of the parameter used in expressions.
89037             var expressionName = parameter.name.kind === 78 /* Identifier */ ? factory.cloneNode(parameter.name) : declarationName;
89038             var restIndex = node.parameters.length - 1;
89039             var temp = factory.createLoopVariable();
89040             // var param = [];
89041             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
89042             /*modifiers*/ undefined, factory.createVariableDeclarationList([
89043                 factory.createVariableDeclaration(declarationName, 
89044                 /*exclamationToken*/ undefined, 
89045                 /*type*/ undefined, factory.createArrayLiteralExpression([]))
89046             ])), 
89047             /*location*/ parameter), 1048576 /* CustomPrologue */));
89048             // for (var _i = restIndex; _i < arguments.length; _i++) {
89049             //   param[_i - restIndex] = arguments[_i];
89050             // }
89051             var forStatement = factory.createForStatement(ts.setTextRange(factory.createVariableDeclarationList([
89052                 factory.createVariableDeclaration(temp, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(restIndex))
89053             ]), parameter), ts.setTextRange(factory.createLessThan(temp, factory.createPropertyAccessExpression(factory.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(factory.createPostfixIncrement(temp), parameter), factory.createBlock([
89054                 ts.startOnNewLine(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(expressionName, restIndex === 0
89055                     ? temp
89056                     : factory.createSubtract(temp, factory.createNumericLiteral(restIndex))), factory.createElementAccessExpression(factory.createIdentifier("arguments"), temp))), 
89057                 /*location*/ parameter))
89058             ]));
89059             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
89060             ts.startOnNewLine(forStatement);
89061             prologueStatements.push(forStatement);
89062             if (parameter.name.kind !== 78 /* Identifier */) {
89063                 // do the actual destructuring of the rest parameter if necessary
89064                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
89065                 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
89066             }
89067             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
89068             return true;
89069         }
89070         /**
89071          * Adds a statement to capture the `this` of a function declaration if it is needed.
89072          * NOTE: This must be executed *after* the subtree has been visited.
89073          *
89074          * @param statements The statements for the new function body.
89075          * @param node A node.
89076          */
89077         function insertCaptureThisForNodeIfNeeded(statements, node) {
89078             if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 209 /* ArrowFunction */) {
89079                 insertCaptureThisForNode(statements, node, factory.createThis());
89080                 return true;
89081             }
89082             return false;
89083         }
89084         function insertCaptureThisForNode(statements, node, initializer) {
89085             enableSubstitutionsForCapturedThis();
89086             var captureThisStatement = factory.createVariableStatement(
89087             /*modifiers*/ undefined, factory.createVariableDeclarationList([
89088                 factory.createVariableDeclaration(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), 
89089                 /*exclamationToken*/ undefined, 
89090                 /*type*/ undefined, initializer)
89091             ]));
89092             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
89093             ts.setSourceMapRange(captureThisStatement, node);
89094             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
89095         }
89096         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
89097             if (hierarchyFacts & 16384 /* NewTarget */) {
89098                 var newTarget = void 0;
89099                 switch (node.kind) {
89100                     case 209 /* ArrowFunction */:
89101                         return statements;
89102                     case 165 /* MethodDeclaration */:
89103                     case 167 /* GetAccessor */:
89104                     case 168 /* SetAccessor */:
89105                         // Methods and accessors cannot be constructors, so 'new.target' will
89106                         // always return 'undefined'.
89107                         newTarget = factory.createVoidZero();
89108                         break;
89109                     case 166 /* Constructor */:
89110                         // Class constructors can only be called with `new`, so `this.constructor`
89111                         // should be relatively safe to use.
89112                         newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor");
89113                         break;
89114                     case 251 /* FunctionDeclaration */:
89115                     case 208 /* FunctionExpression */:
89116                         // Functions can be called or constructed, and may have a `this` due to
89117                         // being a member or when calling an imported function via `other_1.f()`.
89118                         newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 101 /* InstanceOfKeyword */, factory.getLocalName(node))), 
89119                         /*questionToken*/ undefined, factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"), 
89120                         /*colonToken*/ undefined, factory.createVoidZero());
89121                         break;
89122                     default:
89123                         return ts.Debug.failBadSyntaxKind(node);
89124                 }
89125                 var captureNewTargetStatement = factory.createVariableStatement(
89126                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
89127                     factory.createVariableDeclaration(factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */), 
89128                     /*exclamationToken*/ undefined, 
89129                     /*type*/ undefined, newTarget)
89130                 ]));
89131                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
89132                 if (copyOnWrite) {
89133                     statements = statements.slice();
89134                 }
89135                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
89136             }
89137             return statements;
89138         }
89139         /**
89140          * Adds statements to the class body function for a class to define the members of the
89141          * class.
89142          *
89143          * @param statements The statements for the class body function.
89144          * @param node The ClassExpression or ClassDeclaration node.
89145          */
89146         function addClassMembers(statements, node) {
89147             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
89148                 var member = _a[_i];
89149                 switch (member.kind) {
89150                     case 229 /* SemicolonClassElement */:
89151                         statements.push(transformSemicolonClassElementToStatement(member));
89152                         break;
89153                     case 165 /* MethodDeclaration */:
89154                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
89155                         break;
89156                     case 167 /* GetAccessor */:
89157                     case 168 /* SetAccessor */:
89158                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
89159                         if (member === accessors.firstAccessor) {
89160                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
89161                         }
89162                         break;
89163                     case 166 /* Constructor */:
89164                         // Constructors are handled in visitClassExpression/visitClassDeclaration
89165                         break;
89166                     default:
89167                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
89168                         break;
89169                 }
89170             }
89171         }
89172         /**
89173          * Transforms a SemicolonClassElement into a statement for a class body function.
89174          *
89175          * @param member The SemicolonClassElement node.
89176          */
89177         function transformSemicolonClassElementToStatement(member) {
89178             return ts.setTextRange(factory.createEmptyStatement(), member);
89179         }
89180         /**
89181          * Transforms a MethodDeclaration into a statement for a class body function.
89182          *
89183          * @param receiver The receiver for the member.
89184          * @param member The MethodDeclaration node.
89185          */
89186         function transformClassMethodDeclarationToStatement(receiver, member, container) {
89187             var commentRange = ts.getCommentRange(member);
89188             var sourceMapRange = ts.getSourceMapRange(member);
89189             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
89190             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
89191             var e;
89192             if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
89193                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
89194                     : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
89195                         : propertyName;
89196                 e = factory.createObjectDefinePropertyCall(receiver, name, factory.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
89197             }
89198             else {
89199                 var memberName = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ member.name);
89200                 e = factory.createAssignment(memberName, memberFunction);
89201             }
89202             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
89203             ts.setSourceMapRange(memberFunction, sourceMapRange);
89204             var statement = ts.setTextRange(factory.createExpressionStatement(e), /*location*/ member);
89205             ts.setOriginalNode(statement, member);
89206             ts.setCommentRange(statement, commentRange);
89207             // The location for the statement is used to emit comments only.
89208             // No source map should be emitted for this statement to align with the
89209             // old emitter.
89210             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
89211             return statement;
89212         }
89213         /**
89214          * Transforms a set of related of get/set accessors into a statement for a class body function.
89215          *
89216          * @param receiver The receiver for the member.
89217          * @param accessors The set of related get/set accessors.
89218          */
89219         function transformAccessorsToStatement(receiver, accessors, container) {
89220             var statement = factory.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
89221             // The location for the statement is used to emit source maps only.
89222             // No comments should be emitted for this statement to align with the
89223             // old emitter.
89224             ts.setEmitFlags(statement, 1536 /* NoComments */);
89225             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
89226             return statement;
89227         }
89228         /**
89229          * Transforms a set of related get/set accessors into an expression for either a class
89230          * body function or an ObjectLiteralExpression with computed properties.
89231          *
89232          * @param receiver The receiver for the member.
89233          */
89234         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
89235             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
89236             // To align with source maps in the old emitter, the receiver and property name
89237             // arguments are both mapped contiguously to the accessor name.
89238             // TODO(rbuckton): Does this need to be parented?
89239             var target = ts.setParent(ts.setTextRange(factory.cloneNode(receiver), receiver), receiver.parent);
89240             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
89241             ts.setSourceMapRange(target, firstAccessor.name);
89242             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
89243             if (ts.isPrivateIdentifier(visitedAccessorName)) {
89244                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
89245             }
89246             var propertyName = ts.createExpressionForPropertyName(factory, visitedAccessorName);
89247             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
89248             ts.setSourceMapRange(propertyName, firstAccessor.name);
89249             var properties = [];
89250             if (getAccessor) {
89251                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
89252                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
89253                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
89254                 var getter = factory.createPropertyAssignment("get", getterFunction);
89255                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
89256                 properties.push(getter);
89257             }
89258             if (setAccessor) {
89259                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
89260                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
89261                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
89262                 var setter = factory.createPropertyAssignment("set", setterFunction);
89263                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
89264                 properties.push(setter);
89265             }
89266             properties.push(factory.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory.createFalse() : factory.createTrue()), factory.createPropertyAssignment("configurable", factory.createTrue()));
89267             var call = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
89268             /*typeArguments*/ undefined, [
89269                 target,
89270                 propertyName,
89271                 factory.createObjectLiteralExpression(properties, /*multiLine*/ true)
89272             ]);
89273             if (startsOnNewLine) {
89274                 ts.startOnNewLine(call);
89275             }
89276             return call;
89277         }
89278         /**
89279          * Visits an ArrowFunction and transforms it into a FunctionExpression.
89280          *
89281          * @param node An ArrowFunction node.
89282          */
89283         function visitArrowFunction(node) {
89284             if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
89285                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
89286             }
89287             var savedConvertedLoopState = convertedLoopState;
89288             convertedLoopState = undefined;
89289             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
89290             var func = factory.createFunctionExpression(
89291             /*modifiers*/ undefined, 
89292             /*asteriskToken*/ undefined, 
89293             /*name*/ undefined, 
89294             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
89295             /*type*/ undefined, transformFunctionBody(node));
89296             ts.setTextRange(func, node);
89297             ts.setOriginalNode(func, node);
89298             ts.setEmitFlags(func, 8 /* CapturesThis */);
89299             if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
89300                 enableSubstitutionsForCapturedThis();
89301             }
89302             // If an arrow function contains
89303             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
89304             convertedLoopState = savedConvertedLoopState;
89305             return func;
89306         }
89307         /**
89308          * Visits a FunctionExpression node.
89309          *
89310          * @param node a FunctionExpression node.
89311          */
89312         function visitFunctionExpression(node) {
89313             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
89314                 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
89315                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
89316             var savedConvertedLoopState = convertedLoopState;
89317             convertedLoopState = undefined;
89318             var parameters = ts.visitParameterList(node.parameters, visitor, context);
89319             var body = transformFunctionBody(node);
89320             var name = hierarchyFacts & 16384 /* NewTarget */
89321                 ? factory.getLocalName(node)
89322                 : node.name;
89323             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
89324             convertedLoopState = savedConvertedLoopState;
89325             return factory.updateFunctionExpression(node, 
89326             /*modifiers*/ undefined, node.asteriskToken, name, 
89327             /*typeParameters*/ undefined, parameters, 
89328             /*type*/ undefined, body);
89329         }
89330         /**
89331          * Visits a FunctionDeclaration node.
89332          *
89333          * @param node a FunctionDeclaration node.
89334          */
89335         function visitFunctionDeclaration(node) {
89336             var savedConvertedLoopState = convertedLoopState;
89337             convertedLoopState = undefined;
89338             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
89339             var parameters = ts.visitParameterList(node.parameters, visitor, context);
89340             var body = transformFunctionBody(node);
89341             var name = hierarchyFacts & 16384 /* NewTarget */
89342                 ? factory.getLocalName(node)
89343                 : node.name;
89344             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
89345             convertedLoopState = savedConvertedLoopState;
89346             return factory.updateFunctionDeclaration(node, 
89347             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
89348             /*typeParameters*/ undefined, parameters, 
89349             /*type*/ undefined, body);
89350         }
89351         /**
89352          * Transforms a function-like node into a FunctionExpression.
89353          *
89354          * @param node The function-like node to transform.
89355          * @param location The source-map location for the new FunctionExpression.
89356          * @param name The name of the new FunctionExpression.
89357          */
89358         function transformFunctionLikeToExpression(node, location, name, container) {
89359             var savedConvertedLoopState = convertedLoopState;
89360             convertedLoopState = undefined;
89361             var ancestorFacts = container && ts.isClassLike(container) && !ts.hasSyntacticModifier(node, 32 /* Static */)
89362                 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
89363                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
89364             var parameters = ts.visitParameterList(node.parameters, visitor, context);
89365             var body = transformFunctionBody(node);
89366             if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) {
89367                 name = factory.getGeneratedNameForNode(node);
89368             }
89369             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
89370             convertedLoopState = savedConvertedLoopState;
89371             return ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
89372             /*modifiers*/ undefined, node.asteriskToken, name, 
89373             /*typeParameters*/ undefined, parameters, 
89374             /*type*/ undefined, body), location), 
89375             /*original*/ node);
89376         }
89377         /**
89378          * Transforms the body of a function-like node.
89379          *
89380          * @param node A function-like node.
89381          */
89382         function transformFunctionBody(node) {
89383             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
89384             var singleLine = false; // indicates whether the block *may* be emitted as a single line
89385             var statementsLocation;
89386             var closeBraceLocation;
89387             var prologue = [];
89388             var statements = [];
89389             var body = node.body;
89390             var statementOffset;
89391             resumeLexicalEnvironment();
89392             if (ts.isBlock(body)) {
89393                 // ensureUseStrict is false because no new prologue-directive should be added.
89394                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
89395                 statementOffset = factory.copyStandardPrologue(body.statements, prologue, /*ensureUseStrict*/ false);
89396                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedFunction);
89397                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedVariableStatement);
89398             }
89399             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
89400             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
89401             if (ts.isBlock(body)) {
89402                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
89403                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor);
89404                 statementsLocation = body.statements;
89405                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
89406                 // If the original body was a multi-line block, this must be a multi-line block.
89407                 if (!multiLine && body.multiLine) {
89408                     multiLine = true;
89409                 }
89410             }
89411             else {
89412                 ts.Debug.assert(node.kind === 209 /* ArrowFunction */);
89413                 // To align with the old emitter, we use a synthetic end position on the location
89414                 // for the statement list we synthesize when we down-level an arrow function with
89415                 // an expression function body. This prevents both comments and source maps from
89416                 // being emitted for the end position only.
89417                 statementsLocation = ts.moveRangeEnd(body, -1);
89418                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
89419                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
89420                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
89421                         singleLine = true;
89422                     }
89423                     else {
89424                         multiLine = true;
89425                     }
89426                 }
89427                 var expression = ts.visitNode(body, visitor, ts.isExpression);
89428                 var returnStatement = factory.createReturnStatement(expression);
89429                 ts.setTextRange(returnStatement, body);
89430                 ts.moveSyntheticComments(returnStatement, body);
89431                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
89432                 statements.push(returnStatement);
89433                 // To align with the source map emit for the old emitter, we set a custom
89434                 // source map location for the close brace.
89435                 closeBraceLocation = body;
89436             }
89437             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
89438             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
89439             insertCaptureThisForNodeIfNeeded(prologue, node);
89440             // If we added any final generated statements, this must be a multi-line block
89441             if (ts.some(prologue)) {
89442                 multiLine = true;
89443             }
89444             statements.unshift.apply(statements, prologue);
89445             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
89446                 // no changes were made, preserve the tree
89447                 return body;
89448             }
89449             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), multiLine);
89450             ts.setTextRange(block, node.body);
89451             if (!multiLine && singleLine) {
89452                 ts.setEmitFlags(block, 1 /* SingleLine */);
89453             }
89454             if (closeBraceLocation) {
89455                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
89456             }
89457             ts.setOriginalNode(block, node.body);
89458             return block;
89459         }
89460         function visitBlock(node, isFunctionBody) {
89461             if (isFunctionBody) {
89462                 // A function body is not a block scope.
89463                 return ts.visitEachChild(node, visitor, context);
89464             }
89465             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
89466                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
89467                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
89468             var updated = ts.visitEachChild(node, visitor, context);
89469             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89470             return updated;
89471         }
89472         /**
89473          * Visits an ExpressionStatement that contains a destructuring assignment.
89474          *
89475          * @param node An ExpressionStatement node.
89476          */
89477         function visitExpressionStatement(node) {
89478             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
89479         }
89480         /**
89481          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
89482          *
89483          * @param node A ParenthesizedExpression node.
89484          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
89485          * expression of an `ExpressionStatement`).
89486          */
89487         function visitParenthesizedExpression(node, expressionResultIsUnused) {
89488             return ts.visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context);
89489         }
89490         /**
89491          * Visits a BinaryExpression that contains a destructuring assignment.
89492          *
89493          * @param node A BinaryExpression node.
89494          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
89495          * expression of an `ExpressionStatement`).
89496          */
89497         function visitBinaryExpression(node, expressionResultIsUnused) {
89498             // If we are here it is because this is a destructuring assignment.
89499             if (ts.isDestructuringAssignment(node)) {
89500                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !expressionResultIsUnused);
89501             }
89502             if (node.operatorToken.kind === 27 /* CommaToken */) {
89503                 return factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorWithUnusedExpressionResult, ts.isExpression), node.operatorToken, ts.visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, ts.isExpression));
89504             }
89505             return ts.visitEachChild(node, visitor, context);
89506         }
89507         /**
89508          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
89509          * expression of an `ExpressionStatement`).
89510          */
89511         function visitCommaListExpression(node, expressionResultIsUnused) {
89512             if (expressionResultIsUnused) {
89513                 return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
89514             }
89515             var result;
89516             for (var i = 0; i < node.elements.length; i++) {
89517                 var element = node.elements[i];
89518                 var visited = ts.visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, ts.isExpression);
89519                 if (result || visited !== element) {
89520                     result || (result = node.elements.slice(0, i));
89521                     result.push(visited);
89522                 }
89523             }
89524             var elements = result ? ts.setTextRange(factory.createNodeArray(result), node.elements) : node.elements;
89525             return factory.updateCommaListExpression(node, elements);
89526         }
89527         function isVariableStatementOfTypeScriptClassWrapper(node) {
89528             return node.declarationList.declarations.length === 1
89529                 && !!node.declarationList.declarations[0].initializer
89530                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
89531         }
89532         function visitVariableStatement(node) {
89533             var ancestorFacts = enterSubtree(0 /* None */, ts.hasSyntacticModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
89534             var updated;
89535             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
89536                 // we are inside a converted loop - hoist variable declarations
89537                 var assignments = void 0;
89538                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89539                     var decl = _a[_i];
89540                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
89541                     if (decl.initializer) {
89542                         var assignment = void 0;
89543                         if (ts.isBindingPattern(decl.name)) {
89544                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
89545                         }
89546                         else {
89547                             assignment = factory.createBinaryExpression(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
89548                             ts.setTextRange(assignment, decl);
89549                         }
89550                         assignments = ts.append(assignments, assignment);
89551                     }
89552                 }
89553                 if (assignments) {
89554                     updated = ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(assignments)), node);
89555                 }
89556                 else {
89557                     // none of declarations has initializer - the entire variable statement can be deleted
89558                     updated = undefined;
89559                 }
89560             }
89561             else {
89562                 updated = ts.visitEachChild(node, visitor, context);
89563             }
89564             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89565             return updated;
89566         }
89567         /**
89568          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
89569          *
89570          * @param node A VariableDeclarationList node.
89571          */
89572         function visitVariableDeclarationList(node) {
89573             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
89574                 if (node.flags & 3 /* BlockScoped */) {
89575                     enableSubstitutionsForBlockScopedBindings();
89576                 }
89577                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
89578                     ? visitVariableDeclarationInLetDeclarationList
89579                     : visitVariableDeclaration);
89580                 var declarationList = factory.createVariableDeclarationList(declarations);
89581                 ts.setOriginalNode(declarationList, node);
89582                 ts.setTextRange(declarationList, node);
89583                 ts.setCommentRange(declarationList, node);
89584                 // If the first or last declaration is a binding pattern, we need to modify
89585                 // the source map range for the declaration list.
89586                 if (node.transformFlags & 131072 /* ContainsBindingPattern */
89587                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
89588                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
89589                 }
89590                 return declarationList;
89591             }
89592             return ts.visitEachChild(node, visitor, context);
89593         }
89594         function getRangeUnion(declarations) {
89595             // declarations may not be sorted by position.
89596             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
89597             var pos = -1, end = -1;
89598             for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
89599                 var node = declarations_10[_i];
89600                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
89601                 end = Math.max(end, node.end);
89602             }
89603             return ts.createRange(pos, end);
89604         }
89605         /**
89606          * Gets a value indicating whether we should emit an explicit initializer for a variable
89607          * declaration in a `let` declaration list.
89608          *
89609          * @param node A VariableDeclaration node.
89610          */
89611         function shouldEmitExplicitInitializerForLetDeclaration(node) {
89612             // Nested let bindings might need to be initialized explicitly to preserve
89613             // ES6 semantic:
89614             //
89615             //  { let x = 1; }
89616             //  { let x; } // x here should be undefined. not 1
89617             //
89618             // Top level bindings never collide with anything and thus don't require
89619             // explicit initialization. As for nested let bindings there are two cases:
89620             //
89621             // - Nested let bindings that were not renamed definitely should be
89622             //   initialized explicitly:
89623             //
89624             //    { let x = 1; }
89625             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
89626             //
89627             //   Without explicit initialization code in /*1*/ can be executed even if
89628             //   some-condition is evaluated to false.
89629             //
89630             // - Renaming introduces fresh name that should not collide with any
89631             //   existing names, however renamed bindings sometimes also should be
89632             //   explicitly initialized. One particular case: non-captured binding
89633             //   declared inside loop body (but not in loop initializer):
89634             //
89635             //    let x;
89636             //    for (;;) {
89637             //        let x;
89638             //    }
89639             //
89640             //   In downlevel codegen inner 'x' will be renamed so it won't collide
89641             //   with outer 'x' however it will should be reset on every iteration as
89642             //   if it was declared anew.
89643             //
89644             //   * Why non-captured binding?
89645             //     - Because if loop contains block scoped binding captured in some
89646             //       function then loop body will be rewritten to have a fresh scope
89647             //       on every iteration so everything will just work.
89648             //
89649             //   * Why loop initializer is excluded?
89650             //     - Since we've introduced a fresh name it already will be undefined.
89651             var flags = resolver.getNodeCheckFlags(node);
89652             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
89653             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
89654             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
89655                 || (isCapturedInFunction
89656                     && isDeclaredInLoop
89657                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
89658             var emitExplicitInitializer = !emittedAsTopLevel
89659                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
89660                 && (!resolver.isDeclarationWithCollidingName(node)
89661                     || (isDeclaredInLoop
89662                         && !isCapturedInFunction
89663                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
89664             return emitExplicitInitializer;
89665         }
89666         /**
89667          * Visits a VariableDeclaration in a `let` declaration list.
89668          *
89669          * @param node A VariableDeclaration node.
89670          */
89671         function visitVariableDeclarationInLetDeclarationList(node) {
89672             // For binding pattern names that lack initializers there is no point to emit
89673             // explicit initializer since downlevel codegen for destructuring will fail
89674             // in the absence of initializer so all binding elements will say uninitialized
89675             var name = node.name;
89676             if (ts.isBindingPattern(name)) {
89677                 return visitVariableDeclaration(node);
89678             }
89679             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
89680                 return factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createVoidZero());
89681             }
89682             return ts.visitEachChild(node, visitor, context);
89683         }
89684         /**
89685          * Visits a VariableDeclaration node with a binding pattern.
89686          *
89687          * @param node A VariableDeclaration node.
89688          */
89689         function visitVariableDeclaration(node) {
89690             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
89691             var updated;
89692             if (ts.isBindingPattern(node.name)) {
89693                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
89694                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
89695             }
89696             else {
89697                 updated = ts.visitEachChild(node, visitor, context);
89698             }
89699             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89700             return updated;
89701         }
89702         function recordLabel(node) {
89703             convertedLoopState.labels.set(ts.idText(node.label), true);
89704         }
89705         function resetLabel(node) {
89706             convertedLoopState.labels.set(ts.idText(node.label), false);
89707         }
89708         function visitLabeledStatement(node) {
89709             if (convertedLoopState && !convertedLoopState.labels) {
89710                 convertedLoopState.labels = new ts.Map();
89711             }
89712             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
89713             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
89714                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
89715                 : factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node, convertedLoopState && resetLabel);
89716         }
89717         function visitIterationStatement(node, outermostLabeledStatement) {
89718             switch (node.kind) {
89719                 case 235 /* DoStatement */:
89720                 case 236 /* WhileStatement */:
89721                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
89722                 case 237 /* ForStatement */:
89723                     return visitForStatement(node, outermostLabeledStatement);
89724                 case 238 /* ForInStatement */:
89725                     return visitForInStatement(node, outermostLabeledStatement);
89726                 case 239 /* ForOfStatement */:
89727                     return visitForOfStatement(node, outermostLabeledStatement);
89728             }
89729         }
89730         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
89731             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
89732             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
89733             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89734             return updated;
89735         }
89736         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
89737             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
89738         }
89739         function visitForStatement(node, outermostLabeledStatement) {
89740             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
89741         }
89742         function visitEachChildOfForStatement(node) {
89743             return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
89744         }
89745         function visitForInStatement(node, outermostLabeledStatement) {
89746             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
89747         }
89748         function visitForOfStatement(node, outermostLabeledStatement) {
89749             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
89750         }
89751         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
89752             var statements = [];
89753             var initializer = node.initializer;
89754             if (ts.isVariableDeclarationList(initializer)) {
89755                 if (node.initializer.flags & 3 /* BlockScoped */) {
89756                     enableSubstitutionsForBlockScopedBindings();
89757                 }
89758                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
89759                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
89760                     // This works whether the declaration is a var, let, or const.
89761                     // It will use rhsIterationValue _a[_i] as the initializer.
89762                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
89763                     var declarationList = ts.setTextRange(factory.createVariableDeclarationList(declarations), node.initializer);
89764                     ts.setOriginalNode(declarationList, node.initializer);
89765                     // Adjust the source map range for the first declaration to align with the old
89766                     // emitter.
89767                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
89768                     statements.push(factory.createVariableStatement(
89769                     /*modifiers*/ undefined, declarationList));
89770                 }
89771                 else {
89772                     // The following call does not include the initializer, so we have
89773                     // to emit it separately.
89774                     statements.push(ts.setTextRange(factory.createVariableStatement(
89775                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclarationList([
89776                         factory.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : factory.createTempVariable(/*recordTempVariable*/ undefined), 
89777                         /*exclamationToken*/ undefined, 
89778                         /*type*/ undefined, boundValue)
89779                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
89780                 }
89781             }
89782             else {
89783                 // Initializer is an expression. Emit the expression in the body, so that it's
89784                 // evaluated on every iteration.
89785                 var assignment = factory.createAssignment(initializer, boundValue);
89786                 if (ts.isDestructuringAssignment(assignment)) {
89787                     statements.push(factory.createExpressionStatement(visitBinaryExpression(assignment, /*expressionResultIsUnused*/ true)));
89788                 }
89789                 else {
89790                     ts.setTextRangeEnd(assignment, initializer.end);
89791                     statements.push(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
89792                 }
89793             }
89794             if (convertedLoopBodyStatements) {
89795                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
89796             }
89797             else {
89798                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
89799                 if (ts.isBlock(statement)) {
89800                     return factory.updateBlock(statement, ts.setTextRange(factory.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
89801                 }
89802                 else {
89803                     statements.push(statement);
89804                     return createSyntheticBlockForConvertedStatements(statements);
89805                 }
89806             }
89807         }
89808         function createSyntheticBlockForConvertedStatements(statements) {
89809             return ts.setEmitFlags(factory.createBlock(factory.createNodeArray(statements), 
89810             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
89811         }
89812         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
89813             // The following ES6 code:
89814             //
89815             //    for (let v of expr) { }
89816             //
89817             // should be emitted as
89818             //
89819             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
89820             //        var v = _a[_i];
89821             //    }
89822             //
89823             // where _a and _i are temps emitted to capture the RHS and the counter,
89824             // respectively.
89825             // When the left hand side is an expression instead of a let declaration,
89826             // the "let v" is not emitted.
89827             // When the left hand side is a let/const, the v is renamed if there is
89828             // another v in scope.
89829             // Note that all assignments to the LHS are emitted in the body, including
89830             // all destructuring.
89831             // Note also that because an extra statement is needed to assign to the LHS,
89832             // for-of bodies are always emitted as blocks.
89833             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
89834             // In the case where the user wrote an identifier as the RHS, like this:
89835             //
89836             //     for (let v of arr) { }
89837             //
89838             // we don't want to emit a temporary variable for the RHS, just use it directly.
89839             var counter = factory.createLoopVariable();
89840             var rhsReference = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
89841             // The old emitter does not emit source maps for the expression
89842             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
89843             var forStatement = ts.setTextRange(factory.createForStatement(
89844             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
89845                 ts.setTextRange(factory.createVariableDeclaration(counter, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(0)), ts.moveRangePos(node.expression, -1)),
89846                 ts.setTextRange(factory.createVariableDeclaration(rhsReference, /*exclamationToken*/ undefined, /*type*/ undefined, expression), node.expression)
89847             ]), node.expression), 2097152 /* NoHoisting */), 
89848             /*condition*/ ts.setTextRange(factory.createLessThan(counter, factory.createPropertyAccessExpression(rhsReference, "length")), node.expression), 
89849             /*incrementor*/ ts.setTextRange(factory.createPostfixIncrement(counter), node.expression), 
89850             /*statement*/ convertForOfStatementHead(node, factory.createElementAccessExpression(rhsReference, counter), convertedLoopBodyStatements)), 
89851             /*location*/ node);
89852             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
89853             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
89854             ts.setTextRange(forStatement, node);
89855             return factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
89856         }
89857         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
89858             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
89859             var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
89860             var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
89861             var errorRecord = factory.createUniqueName("e");
89862             var catchVariable = factory.getGeneratedNameForNode(errorRecord);
89863             var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
89864             var values = ts.setTextRange(emitHelpers().createValuesHelper(expression), node.expression);
89865             var next = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
89866             hoistVariableDeclaration(errorRecord);
89867             hoistVariableDeclaration(returnMethod);
89868             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
89869             var initializer = ancestorFacts & 1024 /* IterationContainer */
89870                 ? factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), values])
89871                 : values;
89872             var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
89873             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
89874                 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
89875                 factory.createVariableDeclaration(result, /*exclamationToken*/ undefined, /*type*/ undefined, next)
89876             ]), node.expression), 2097152 /* NoHoisting */), 
89877             /*condition*/ factory.createLogicalNot(factory.createPropertyAccessExpression(result, "done")), 
89878             /*incrementor*/ factory.createAssignment(result, next), 
89879             /*statement*/ convertForOfStatementHead(node, factory.createPropertyAccessExpression(result, "value"), convertedLoopBodyStatements)), 
89880             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
89881             return factory.createTryStatement(factory.createBlock([
89882                 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
89883             ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
89884                 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
89885                     factory.createPropertyAssignment("error", catchVariable)
89886                 ])))
89887             ]), 1 /* SingleLine */)), factory.createBlock([
89888                 factory.createTryStatement(
89889                 /*tryBlock*/ factory.createBlock([
89890                     ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(factory.createPropertyAccessExpression(result, "done"))), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(factory.createFunctionCallCall(returnMethod, iterator, []))), 1 /* SingleLine */),
89891                 ]), 
89892                 /*catchClause*/ undefined, 
89893                 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
89894                     ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
89895                 ]), 1 /* SingleLine */))
89896             ]));
89897         }
89898         /**
89899          * Visits an ObjectLiteralExpression with computed property names.
89900          *
89901          * @param node An ObjectLiteralExpression node.
89902          */
89903         function visitObjectLiteralExpression(node) {
89904             var properties = node.properties;
89905             // Find the first computed property.
89906             // Everything until that point can be emitted as part of the initial object literal.
89907             var numInitialProperties = -1, hasComputed = false;
89908             for (var i = 0; i < properties.length; i++) {
89909                 var property = properties[i];
89910                 if ((property.transformFlags & 262144 /* ContainsYield */ &&
89911                     hierarchyFacts & 4 /* AsyncFunctionBody */)
89912                     || (hasComputed = ts.Debug.checkDefined(property.name).kind === 158 /* ComputedPropertyName */)) {
89913                     numInitialProperties = i;
89914                     break;
89915                 }
89916             }
89917             if (numInitialProperties < 0) {
89918                 return ts.visitEachChild(node, visitor, context);
89919             }
89920             // For computed properties, we need to create a unique handle to the object
89921             // literal so we can modify it without risking internal assignments tainting the object.
89922             var temp = factory.createTempVariable(hoistVariableDeclaration);
89923             // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
89924             var expressions = [];
89925             var assignment = factory.createAssignment(temp, ts.setEmitFlags(factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), hasComputed ? 65536 /* Indented */ : 0));
89926             if (node.multiLine) {
89927                 ts.startOnNewLine(assignment);
89928             }
89929             expressions.push(assignment);
89930             addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
89931             // We need to clone the temporary identifier so that we can write it on a
89932             // new line
89933             expressions.push(node.multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
89934             return factory.inlineExpressions(expressions);
89935         }
89936         function shouldConvertPartOfIterationStatement(node) {
89937             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
89938         }
89939         function shouldConvertInitializerOfForStatement(node) {
89940             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
89941         }
89942         function shouldConvertConditionOfForStatement(node) {
89943             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
89944         }
89945         function shouldConvertIncrementorOfForStatement(node) {
89946             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
89947         }
89948         function shouldConvertIterationStatement(node) {
89949             return shouldConvertBodyOfIterationStatement(node)
89950                 || shouldConvertInitializerOfForStatement(node);
89951         }
89952         function shouldConvertBodyOfIterationStatement(node) {
89953             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
89954         }
89955         /**
89956          * Records constituents of name for the given variable to be hoisted in the outer scope.
89957          */
89958         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
89959             if (!state.hoistedLocalVariables) {
89960                 state.hoistedLocalVariables = [];
89961             }
89962             visit(node.name);
89963             function visit(node) {
89964                 if (node.kind === 78 /* Identifier */) {
89965                     state.hoistedLocalVariables.push(node);
89966                 }
89967                 else {
89968                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
89969                         var element = _a[_i];
89970                         if (!ts.isOmittedExpression(element)) {
89971                             visit(element.name);
89972                         }
89973                     }
89974                 }
89975             }
89976         }
89977         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
89978             if (!shouldConvertIterationStatement(node)) {
89979                 var saveAllowedNonLabeledJumps = void 0;
89980                 if (convertedLoopState) {
89981                     // we get here if we are trying to emit normal loop loop inside converted loop
89982                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
89983                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
89984                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
89985                 }
89986                 var result = convert
89987                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
89988                     : factory.restoreEnclosingLabel(ts.isForStatement(node) ? visitEachChildOfForStatement(node) : ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
89989                 if (convertedLoopState) {
89990                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
89991                 }
89992                 return result;
89993             }
89994             var currentState = createConvertedLoopState(node);
89995             var statements = [];
89996             var outerConvertedLoopState = convertedLoopState;
89997             convertedLoopState = currentState;
89998             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
89999             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
90000             convertedLoopState = outerConvertedLoopState;
90001             if (initializerFunction)
90002                 statements.push(initializerFunction.functionDeclaration);
90003             if (bodyFunction)
90004                 statements.push(bodyFunction.functionDeclaration);
90005             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
90006             if (initializerFunction) {
90007                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
90008             }
90009             var loop;
90010             if (bodyFunction) {
90011                 if (convert) {
90012                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
90013                 }
90014                 else {
90015                     var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true));
90016                     loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel);
90017                 }
90018             }
90019             else {
90020                 var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
90021                 loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
90022             }
90023             statements.push(loop);
90024             return statements;
90025         }
90026         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
90027             switch (node.kind) {
90028                 case 237 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
90029                 case 238 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
90030                 case 239 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
90031                 case 235 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
90032                 case 236 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
90033                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
90034             }
90035         }
90036         function convertForStatement(node, initializerFunction, convertedLoopBody) {
90037             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
90038             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
90039             return factory.updateForStatement(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), convertedLoopBody);
90040         }
90041         function convertForOfStatement(node, convertedLoopBody) {
90042             return factory.updateForOfStatement(node, 
90043             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
90044         }
90045         function convertForInStatement(node, convertedLoopBody) {
90046             return factory.updateForInStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
90047         }
90048         function convertDoStatement(node, convertedLoopBody) {
90049             return factory.updateDoStatement(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
90050         }
90051         function convertWhileStatement(node, convertedLoopBody) {
90052             return factory.updateWhileStatement(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
90053         }
90054         function createConvertedLoopState(node) {
90055             var loopInitializer;
90056             switch (node.kind) {
90057                 case 237 /* ForStatement */:
90058                 case 238 /* ForInStatement */:
90059                 case 239 /* ForOfStatement */:
90060                     var initializer = node.initializer;
90061                     if (initializer && initializer.kind === 250 /* VariableDeclarationList */) {
90062                         loopInitializer = initializer;
90063                     }
90064                     break;
90065             }
90066             // variables that will be passed to the loop as parameters
90067             var loopParameters = [];
90068             // variables declared in the loop initializer that will be changed inside the loop
90069             var loopOutParameters = [];
90070             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
90071                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
90072                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
90073                     var decl = _a[_i];
90074                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
90075                 }
90076             }
90077             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
90078             if (convertedLoopState) {
90079                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
90080                 // if outer converted loop has already accumulated some state - pass it through
90081                 if (convertedLoopState.argumentsName) {
90082                     // outer loop has already used 'arguments' so we've already have some name to alias it
90083                     // use the same name in all nested loops
90084                     currentState.argumentsName = convertedLoopState.argumentsName;
90085                 }
90086                 if (convertedLoopState.thisName) {
90087                     // outer loop has already used 'this' so we've already have some name to alias it
90088                     // use the same name in all nested loops
90089                     currentState.thisName = convertedLoopState.thisName;
90090                 }
90091                 if (convertedLoopState.hoistedLocalVariables) {
90092                     // we've already collected some non-block scoped variable declarations in enclosing loop
90093                     // use the same storage in nested loop
90094                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
90095                 }
90096             }
90097             return currentState;
90098         }
90099         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
90100             var extraVariableDeclarations;
90101             // propagate state from the inner loop to the outer loop if necessary
90102             if (state.argumentsName) {
90103                 // if alias for arguments is set
90104                 if (outerState) {
90105                     // pass it to outer converted loop
90106                     outerState.argumentsName = state.argumentsName;
90107                 }
90108                 else {
90109                     // this is top level converted loop and we need to create an alias for 'arguments' object
90110                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.argumentsName, 
90111                     /*exclamationToken*/ undefined, 
90112                     /*type*/ undefined, factory.createIdentifier("arguments")));
90113                 }
90114             }
90115             if (state.thisName) {
90116                 // if alias for this is set
90117                 if (outerState) {
90118                     // pass it to outer converted loop
90119                     outerState.thisName = state.thisName;
90120                 }
90121                 else {
90122                     // this is top level converted loop so we need to create an alias for 'this' here
90123                     // NOTE:
90124                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
90125                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
90126                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.thisName, 
90127                     /*exclamationToken*/ undefined, 
90128                     /*type*/ undefined, factory.createIdentifier("this")));
90129                 }
90130             }
90131             if (state.hoistedLocalVariables) {
90132                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
90133                 if (outerState) {
90134                     // pass them to outer converted loop
90135                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
90136                 }
90137                 else {
90138                     if (!extraVariableDeclarations) {
90139                         extraVariableDeclarations = [];
90140                     }
90141                     // hoist collected variable declarations
90142                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
90143                         var identifier = _a[_i];
90144                         extraVariableDeclarations.push(factory.createVariableDeclaration(identifier));
90145                     }
90146                 }
90147             }
90148             // add extra variables to hold out parameters if necessary
90149             if (state.loopOutParameters.length) {
90150                 if (!extraVariableDeclarations) {
90151                     extraVariableDeclarations = [];
90152                 }
90153                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
90154                     var outParam = _c[_b];
90155                     extraVariableDeclarations.push(factory.createVariableDeclaration(outParam.outParamName));
90156                 }
90157             }
90158             if (state.conditionVariable) {
90159                 if (!extraVariableDeclarations) {
90160                     extraVariableDeclarations = [];
90161                 }
90162                 extraVariableDeclarations.push(factory.createVariableDeclaration(state.conditionVariable, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createFalse()));
90163             }
90164             // create variable statement to hold all introduced variable declarations
90165             if (extraVariableDeclarations) {
90166                 statements.push(factory.createVariableStatement(
90167                 /*modifiers*/ undefined, factory.createVariableDeclarationList(extraVariableDeclarations)));
90168             }
90169         }
90170         function createOutVariable(p) {
90171             return factory.createVariableDeclaration(p.originalName, /*exclamationToken*/ undefined, /*type*/ undefined, p.outParamName);
90172         }
90173         /**
90174          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
90175          * that is captured in a closure inside of the initializer. The `_loop_init` function is
90176          * used to preserve the per-iteration environment semantics of
90177          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
90178          */
90179         function createFunctionForInitializerOfForStatement(node, currentState) {
90180             var functionName = factory.createUniqueName("_loop_init");
90181             var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
90182             var emitFlags = 0 /* None */;
90183             if (currentState.containsLexicalThis)
90184                 emitFlags |= 8 /* CapturesThis */;
90185             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
90186                 emitFlags |= 262144 /* AsyncFunctionBody */;
90187             var statements = [];
90188             statements.push(factory.createVariableStatement(/*modifiers*/ undefined, node.initializer));
90189             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
90190             // This transforms the following ES2015 syntax:
90191             //
90192             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
90193             //      // loop body
90194             //  }
90195             //
90196             // Into the following ES5 syntax:
90197             //
90198             //  var _loop_init_1 = function () {
90199             //      var i = (setImmediate(() => console.log(i)), 0);
90200             //      out_i_1 = i;
90201             //  };
90202             //  var out_i_1;
90203             //  _loop_init_1();
90204             //  for (var i = out_i_1; i < 2; i++) {
90205             //      // loop body
90206             //  }
90207             //
90208             // Which prevents mutations to `i` in the per-iteration environment of the body
90209             // from affecting the initial value for `i` outside of the per-iteration environment.
90210             var functionDeclaration = factory.createVariableStatement(
90211             /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
90212                 factory.createVariableDeclaration(functionName, 
90213                 /*exclamationToken*/ undefined, 
90214                 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
90215                 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined, 
90216                 /*name*/ undefined, 
90217                 /*typeParameters*/ undefined, 
90218                 /*parameters*/ undefined, 
90219                 /*type*/ undefined, ts.visitNode(factory.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
90220             ]), 2097152 /* NoHoisting */));
90221             var part = factory.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
90222             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
90223         }
90224         /**
90225          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
90226          * that is captured in a closure inside of the loop body. The `_loop` function is used to
90227          * preserve the per-iteration environment semantics of
90228          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
90229          */
90230         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
90231             var functionName = factory.createUniqueName("_loop");
90232             startLexicalEnvironment();
90233             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
90234             var lexicalEnvironment = endLexicalEnvironment();
90235             var statements = [];
90236             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
90237                 // If a block-scoped variable declared in the initializer of `node` is captured in
90238                 // the condition or incrementor, we must move the condition and incrementor into
90239                 // the body of the for loop.
90240                 //
90241                 // This transforms the following ES2015 syntax:
90242                 //
90243                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
90244                 //      // loop body
90245                 //  }
90246                 //
90247                 // Into the following ES5 syntax:
90248                 //
90249                 //  var _loop_1 = function (i) {
90250                 //      if (inc_1)
90251                 //          setImmediate(() => console.log(i)), i++;
90252                 //      else
90253                 //          inc_1 = true;
90254                 //      if (!(setImmediate(() => console.log(i)), i < 2))
90255                 //          return out_i_1 = i, "break";
90256                 //      // loop body
90257                 //      out_i_1 = i;
90258                 //  }
90259                 //  var out_i_1, inc_1 = false;
90260                 //  for (var i = 0;;) {
90261                 //      var state_1 = _loop_1(i);
90262                 //      i = out_i_1;
90263                 //      if (state_1 === "break")
90264                 //          break;
90265                 //  }
90266                 //
90267                 // Which prevents mutations to `i` in the per-iteration environment of the body
90268                 // from affecting the value of `i` in the previous per-iteration environment.
90269                 //
90270                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
90271                 // environment that is carried over to the next iteration of the loop. As a result,
90272                 // we must indicate whether this is the first evaluation of the loop body so that
90273                 // we only evaluate the incrementor on subsequent evaluations.
90274                 currentState.conditionVariable = factory.createUniqueName("inc");
90275                 if (node.incrementor) {
90276                     statements.push(factory.createIfStatement(currentState.conditionVariable, factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
90277                 }
90278                 else {
90279                     statements.push(factory.createIfStatement(factory.createLogicalNot(currentState.conditionVariable), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
90280                 }
90281                 if (shouldConvertConditionOfForStatement(node)) {
90282                     statements.push(factory.createIfStatement(factory.createPrefixUnaryExpression(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(factory.createBreakStatement(), visitor, ts.isStatement)));
90283                 }
90284             }
90285             if (ts.isBlock(statement)) {
90286                 ts.addRange(statements, statement.statements);
90287             }
90288             else {
90289                 statements.push(statement);
90290             }
90291             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
90292             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
90293             var loopBody = factory.createBlock(statements, /*multiLine*/ true);
90294             if (ts.isBlock(statement))
90295                 ts.setOriginalNode(loopBody, statement);
90296             var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
90297             var emitFlags = 0;
90298             if (currentState.containsLexicalThis)
90299                 emitFlags |= 8 /* CapturesThis */;
90300             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
90301                 emitFlags |= 262144 /* AsyncFunctionBody */;
90302             // This transforms the following ES2015 syntax (in addition to other variations):
90303             //
90304             //  for (let i = 0; i < 2; i++) {
90305             //      setImmediate(() => console.log(i));
90306             //  }
90307             //
90308             // Into the following ES5 syntax:
90309             //
90310             //  var _loop_1 = function (i) {
90311             //      setImmediate(() => console.log(i));
90312             //  };
90313             //  for (var i = 0; i < 2; i++) {
90314             //      _loop_1(i);
90315             //  }
90316             var functionDeclaration = factory.createVariableStatement(
90317             /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
90318                 factory.createVariableDeclaration(functionName, 
90319                 /*exclamationToken*/ undefined, 
90320                 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
90321                 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined, 
90322                 /*name*/ undefined, 
90323                 /*typeParameters*/ undefined, currentState.loopParameters, 
90324                 /*type*/ undefined, loopBody), emitFlags))
90325             ]), 2097152 /* NoHoisting */));
90326             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
90327             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
90328         }
90329         function copyOutParameter(outParam, copyDirection) {
90330             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
90331             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
90332             return factory.createBinaryExpression(target, 62 /* EqualsToken */, source);
90333         }
90334         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
90335             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
90336                 var outParam = outParams_1[_i];
90337                 if (outParam.flags & partFlags) {
90338                     statements.push(factory.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
90339                 }
90340             }
90341         }
90342         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
90343             var call = factory.createCallExpression(initFunctionExpressionName, /*typeArguments*/ undefined, []);
90344             var callResult = containsYield
90345                 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
90346                 : call;
90347             return factory.createExpressionStatement(callResult);
90348         }
90349         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
90350             var statements = [];
90351             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
90352             // simple loops are emitted as just 'loop()';
90353             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
90354             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
90355                 !state.labeledNonLocalBreaks &&
90356                 !state.labeledNonLocalContinues;
90357             var call = factory.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
90358             var callResult = containsYield
90359                 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
90360                 : call;
90361             if (isSimpleLoop) {
90362                 statements.push(factory.createExpressionStatement(callResult));
90363                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
90364             }
90365             else {
90366                 var loopResultName = factory.createUniqueName("state");
90367                 var stateVariable = factory.createVariableStatement(
90368                 /*modifiers*/ undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(loopResultName, /*exclamationToken*/ undefined, /*type*/ undefined, callResult)]));
90369                 statements.push(stateVariable);
90370                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
90371                 if (state.nonLocalJumps & 8 /* Return */) {
90372                     var returnStatement = void 0;
90373                     if (outerState) {
90374                         outerState.nonLocalJumps |= 8 /* Return */;
90375                         returnStatement = factory.createReturnStatement(loopResultName);
90376                     }
90377                     else {
90378                         returnStatement = factory.createReturnStatement(factory.createPropertyAccessExpression(loopResultName, "value"));
90379                     }
90380                     statements.push(factory.createIfStatement(factory.createTypeCheck(loopResultName, "object"), returnStatement));
90381                 }
90382                 if (state.nonLocalJumps & 2 /* Break */) {
90383                     statements.push(factory.createIfStatement(factory.createStrictEquality(loopResultName, factory.createStringLiteral("break")), factory.createBreakStatement()));
90384                 }
90385                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
90386                     var caseClauses = [];
90387                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
90388                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
90389                     statements.push(factory.createSwitchStatement(loopResultName, factory.createCaseBlock(caseClauses)));
90390                 }
90391             }
90392             return statements;
90393         }
90394         function setLabeledJump(state, isBreak, labelText, labelMarker) {
90395             if (isBreak) {
90396                 if (!state.labeledNonLocalBreaks) {
90397                     state.labeledNonLocalBreaks = new ts.Map();
90398                 }
90399                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
90400             }
90401             else {
90402                 if (!state.labeledNonLocalContinues) {
90403                     state.labeledNonLocalContinues = new ts.Map();
90404                 }
90405                 state.labeledNonLocalContinues.set(labelText, labelMarker);
90406             }
90407         }
90408         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
90409             if (!table) {
90410                 return;
90411             }
90412             table.forEach(function (labelMarker, labelText) {
90413                 var statements = [];
90414                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
90415                 // then emit labeled break\continue
90416                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
90417                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
90418                     var label = factory.createIdentifier(labelText);
90419                     statements.push(isBreak ? factory.createBreakStatement(label) : factory.createContinueStatement(label));
90420                 }
90421                 else {
90422                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
90423                     statements.push(factory.createReturnStatement(loopResultName));
90424                 }
90425                 caseClauses.push(factory.createCaseClause(factory.createStringLiteral(labelMarker), statements));
90426             });
90427         }
90428         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
90429             var name = decl.name;
90430             if (ts.isBindingPattern(name)) {
90431                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
90432                     var element = _a[_i];
90433                     if (!ts.isOmittedExpression(element)) {
90434                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
90435                     }
90436                 }
90437             }
90438             else {
90439                 loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
90440                 var checkFlags = resolver.getNodeCheckFlags(decl);
90441                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
90442                     var outParamName = factory.createUniqueName("out_" + ts.idText(name));
90443                     var flags = 0;
90444                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
90445                         flags |= 1 /* Body */;
90446                     }
90447                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
90448                         flags |= 2 /* Initializer */;
90449                     }
90450                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
90451                 }
90452             }
90453         }
90454         /**
90455          * Adds the members of an object literal to an array of expressions.
90456          *
90457          * @param expressions An array of expressions.
90458          * @param node An ObjectLiteralExpression node.
90459          * @param receiver The receiver for members of the ObjectLiteralExpression.
90460          * @param numInitialNonComputedProperties The number of initial properties without
90461          *                                        computed property names.
90462          */
90463         function addObjectLiteralMembers(expressions, node, receiver, start) {
90464             var properties = node.properties;
90465             var numProperties = properties.length;
90466             for (var i = start; i < numProperties; i++) {
90467                 var property = properties[i];
90468                 switch (property.kind) {
90469                     case 167 /* GetAccessor */:
90470                     case 168 /* SetAccessor */:
90471                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
90472                         if (property === accessors.firstAccessor) {
90473                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
90474                         }
90475                         break;
90476                     case 165 /* MethodDeclaration */:
90477                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
90478                         break;
90479                     case 288 /* PropertyAssignment */:
90480                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
90481                         break;
90482                     case 289 /* ShorthandPropertyAssignment */:
90483                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
90484                         break;
90485                     default:
90486                         ts.Debug.failBadSyntaxKind(node);
90487                         break;
90488                 }
90489             }
90490         }
90491         /**
90492          * Transforms a PropertyAssignment node into an expression.
90493          *
90494          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
90495          * @param property The PropertyAssignment node.
90496          * @param receiver The receiver for the assignment.
90497          */
90498         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
90499             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
90500             ts.setTextRange(expression, property);
90501             if (startsOnNewLine) {
90502                 ts.startOnNewLine(expression);
90503             }
90504             return expression;
90505         }
90506         /**
90507          * Transforms a ShorthandPropertyAssignment node into an expression.
90508          *
90509          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
90510          * @param property The ShorthandPropertyAssignment node.
90511          * @param receiver The receiver for the assignment.
90512          */
90513         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
90514             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), factory.cloneNode(property.name));
90515             ts.setTextRange(expression, property);
90516             if (startsOnNewLine) {
90517                 ts.startOnNewLine(expression);
90518             }
90519             return expression;
90520         }
90521         /**
90522          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
90523          *
90524          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
90525          * @param method The MethodDeclaration node.
90526          * @param receiver The receiver for the assignment.
90527          */
90528         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
90529             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
90530             ts.setTextRange(expression, method);
90531             if (startsOnNewLine) {
90532                 ts.startOnNewLine(expression);
90533             }
90534             return expression;
90535         }
90536         function visitCatchClause(node) {
90537             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
90538             var updated;
90539             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
90540             if (ts.isBindingPattern(node.variableDeclaration.name)) {
90541                 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
90542                 var newVariableDeclaration = factory.createVariableDeclaration(temp);
90543                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
90544                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
90545                 var list = factory.createVariableDeclarationList(vars);
90546                 ts.setTextRange(list, node.variableDeclaration);
90547                 var destructure = factory.createVariableStatement(/*modifiers*/ undefined, list);
90548                 updated = factory.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
90549             }
90550             else {
90551                 updated = ts.visitEachChild(node, visitor, context);
90552             }
90553             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
90554             return updated;
90555         }
90556         function addStatementToStartOfBlock(block, statement) {
90557             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
90558             return factory.updateBlock(block, __spreadArrays([statement], transformedStatements));
90559         }
90560         /**
90561          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
90562          * PropertyAssignment.
90563          *
90564          * @param node A MethodDeclaration node.
90565          */
90566         function visitMethodDeclaration(node) {
90567             // We should only get here for methods on an object literal with regular identifier names.
90568             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
90569             // Methods with computed property names are handled in visitObjectLiteralExpression.
90570             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
90571             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
90572             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
90573             return ts.setTextRange(factory.createPropertyAssignment(node.name, functionExpression), 
90574             /*location*/ node);
90575         }
90576         /**
90577          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
90578          *
90579          * @param node An AccessorDeclaration node.
90580          */
90581         function visitAccessorDeclaration(node) {
90582             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
90583             var savedConvertedLoopState = convertedLoopState;
90584             convertedLoopState = undefined;
90585             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
90586             var updated;
90587             var parameters = ts.visitParameterList(node.parameters, visitor, context);
90588             var body = transformFunctionBody(node);
90589             if (node.kind === 167 /* GetAccessor */) {
90590                 updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
90591             }
90592             else {
90593                 updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body);
90594             }
90595             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
90596             convertedLoopState = savedConvertedLoopState;
90597             return updated;
90598         }
90599         /**
90600          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
90601          *
90602          * @param node A ShorthandPropertyAssignment node.
90603          */
90604         function visitShorthandPropertyAssignment(node) {
90605             return ts.setTextRange(factory.createPropertyAssignment(node.name, visitIdentifier(factory.cloneNode(node.name))), 
90606             /*location*/ node);
90607         }
90608         function visitComputedPropertyName(node) {
90609             return ts.visitEachChild(node, visitor, context);
90610         }
90611         /**
90612          * Visits a YieldExpression node.
90613          *
90614          * @param node A YieldExpression node.
90615          */
90616         function visitYieldExpression(node) {
90617             // `yield` expressions are transformed using the generators transformer.
90618             return ts.visitEachChild(node, visitor, context);
90619         }
90620         /**
90621          * Visits an ArrayLiteralExpression that contains a spread element.
90622          *
90623          * @param node An ArrayLiteralExpression node.
90624          */
90625         function visitArrayLiteralExpression(node) {
90626             if (ts.some(node.elements, ts.isSpreadElement)) {
90627                 // We are here because we contain a SpreadElementExpression.
90628                 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
90629             }
90630             return ts.visitEachChild(node, visitor, context);
90631         }
90632         /**
90633          * Visits a CallExpression that contains either a spread element or `super`.
90634          *
90635          * @param node a CallExpression.
90636          */
90637         function visitCallExpression(node) {
90638             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
90639                 return visitTypeScriptClassWrapper(node);
90640             }
90641             var expression = ts.skipOuterExpressions(node.expression);
90642             if (expression.kind === 105 /* SuperKeyword */ ||
90643                 ts.isSuperProperty(expression) ||
90644                 ts.some(node.arguments, ts.isSpreadElement)) {
90645                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
90646             }
90647             return factory.updateCallExpression(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
90648             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
90649         }
90650         function visitTypeScriptClassWrapper(node) {
90651             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
90652             // The wrapper has a form similar to:
90653             //
90654             //  (function() {
90655             //      class C { // 1
90656             //      }
90657             //      C.x = 1; // 2
90658             //      return C;
90659             //  }())
90660             //
90661             // When we transform the class, we end up with something like this:
90662             //
90663             //  (function () {
90664             //      var C = (function () { // 3
90665             //          function C() {
90666             //          }
90667             //          return C; // 4
90668             //      }());
90669             //      C.x = 1;
90670             //      return C;
90671             //  }())
90672             //
90673             // We want to simplify the two nested IIFEs to end up with something like this:
90674             //
90675             //  (function () {
90676             //      function C() {
90677             //      }
90678             //      C.x = 1;
90679             //      return C;
90680             //  }())
90681             // We skip any outer expressions in a number of places to get to the innermost
90682             // expression, but we will restore them later to preserve comments and source maps.
90683             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
90684             // The class statements are the statements generated by visiting the first statement with initializer of the
90685             // body (1), while all other statements are added to remainingStatements (2)
90686             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
90687             // visit the class body statements outside of any converted loop body.
90688             var savedConvertedLoopState = convertedLoopState;
90689             convertedLoopState = undefined;
90690             var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
90691             convertedLoopState = savedConvertedLoopState;
90692             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
90693             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
90694             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
90695             // We know there is only one variable declaration here as we verified this in an
90696             // earlier call to isTypeScriptClassWrapper
90697             var variable = varStatement.declarationList.declarations[0];
90698             var initializer = ts.skipOuterExpressions(variable.initializer);
90699             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
90700             // we see as an assignment, for example:
90701             //
90702             //  (function () {
90703             //      var C_1;
90704             //      var C = C_1 = (function () {
90705             //          function C() {
90706             //          }
90707             //          C.x = function () { return C_1; }
90708             //          return C;
90709             //      }());
90710             //      C = C_1 = __decorate([dec], C);
90711             //      return C;
90712             //  }())
90713             //
90714             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
90715             // The underlying call (3) is another IIFE that may contain a '_super' argument.
90716             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
90717             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
90718             var funcStatements = func.body.statements;
90719             var classBodyStart = 0;
90720             var classBodyEnd = -1;
90721             var statements = [];
90722             if (aliasAssignment) {
90723                 // If we have a class alias assignment, we need to move it to the down-level constructor
90724                 // function we generated for the class.
90725                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
90726                 if (extendsCall) {
90727                     statements.push(extendsCall);
90728                     classBodyStart++;
90729                 }
90730                 // The next statement is the function declaration.
90731                 statements.push(funcStatements[classBodyStart]);
90732                 classBodyStart++;
90733                 // Add the class alias following the declaration.
90734                 statements.push(factory.createExpressionStatement(factory.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
90735             }
90736             // Find the trailing 'return' statement (4)
90737             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
90738                 classBodyEnd--;
90739             }
90740             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
90741             // as we already have one that has been introduced by the 'ts' transformer.
90742             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
90743             if (classBodyEnd < -1) {
90744                 // If there were any hoisted declarations following the return statement, we should
90745                 // append them.
90746                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
90747             }
90748             // Add the remaining statements of the outer wrapper.
90749             ts.addRange(statements, remainingStatements);
90750             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
90751             // after the remaining statements from the 'ts' transformer.
90752             ts.addRange(statements, classStatements, /*start*/ 1);
90753             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
90754             // and comment locations.
90755             return factory.restoreOuterExpressions(node.expression, factory.restoreOuterExpressions(variable.initializer, factory.restoreOuterExpressions(aliasAssignment && aliasAssignment.right, factory.updateCallExpression(call, factory.restoreOuterExpressions(call.expression, factory.updateFunctionExpression(func, 
90756             /*modifiers*/ undefined, 
90757             /*asteriskToken*/ undefined, 
90758             /*name*/ undefined, 
90759             /*typeParameters*/ undefined, func.parameters, 
90760             /*type*/ undefined, factory.updateBlock(func.body, statements))), 
90761             /*typeArguments*/ undefined, call.arguments))));
90762         }
90763         function visitImmediateSuperCallInBody(node) {
90764             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
90765         }
90766         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
90767             // We are here either because SuperKeyword was used somewhere in the expression, or
90768             // because we contain a SpreadElementExpression.
90769             if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
90770                 node.expression.kind === 105 /* SuperKeyword */ ||
90771                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
90772                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
90773                 if (node.expression.kind === 105 /* SuperKeyword */) {
90774                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
90775                 }
90776                 var resultingCall = void 0;
90777                 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
90778                     // [source]
90779                     //      f(...a, b)
90780                     //      x.m(...a, b)
90781                     //      super(...a, b)
90782                     //      super.m(...a, b) // in static
90783                     //      super.m(...a, b) // in instance
90784                     //
90785                     // [output]
90786                     //      f.apply(void 0, a.concat([b]))
90787                     //      (_a = x).m.apply(_a, a.concat([b]))
90788                     //      _super.apply(this, a.concat([b]))
90789                     //      _super.m.apply(this, a.concat([b]))
90790                     //      _super.prototype.m.apply(this, a.concat([b]))
90791                     resultingCall = factory.createFunctionApplyCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 105 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
90792                 }
90793                 else {
90794                     // [source]
90795                     //      super(a)
90796                     //      super.m(a) // in static
90797                     //      super.m(a) // in instance
90798                     //
90799                     // [output]
90800                     //      _super.call(this, a)
90801                     //      _super.m.call(this, a)
90802                     //      _super.prototype.m.call(this, a)
90803                     resultingCall = ts.setTextRange(factory.createFunctionCallCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 105 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression)), node);
90804                 }
90805                 if (node.expression.kind === 105 /* SuperKeyword */) {
90806                     var initializer = factory.createLogicalOr(resultingCall, createActualThis());
90807                     resultingCall = assignToCapturedThis
90808                         ? factory.createAssignment(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), initializer)
90809                         : initializer;
90810                 }
90811                 return ts.setOriginalNode(resultingCall, node);
90812             }
90813             return ts.visitEachChild(node, visitor, context);
90814         }
90815         /**
90816          * Visits a NewExpression that contains a spread element.
90817          *
90818          * @param node A NewExpression node.
90819          */
90820         function visitNewExpression(node) {
90821             if (ts.some(node.arguments, ts.isSpreadElement)) {
90822                 // We are here because we contain a SpreadElementExpression.
90823                 // [source]
90824                 //      new C(...a)
90825                 //
90826                 // [output]
90827                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
90828                 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
90829                 return factory.createNewExpression(factory.createFunctionApplyCall(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(factory.createNodeArray(__spreadArrays([factory.createVoidZero()], node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), 
90830                 /*typeArguments*/ undefined, []);
90831             }
90832             return ts.visitEachChild(node, visitor, context);
90833         }
90834         /**
90835          * Transforms an array of Expression nodes that contains a SpreadExpression.
90836          *
90837          * @param elements The array of Expression nodes.
90838          * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
90839          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
90840          */
90841         function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
90842             // [source]
90843             //      [a, ...b, c]
90844             //
90845             // [output (downlevelIteration)]
90846             //      __spread([a], b, [c])
90847             //
90848             // [output]
90849             //      __spreadArrays([a], b, [c])
90850             // Map spans of spread expressions into their expressions and spans of other
90851             // expressions into an array literal.
90852             var numElements = elements.length;
90853             var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
90854                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
90855             }));
90856             if (compilerOptions.downlevelIteration) {
90857                 if (segments.length === 1) {
90858                     var firstSegment = segments[0];
90859                     if (isCallToHelper(firstSegment, "___spread")) {
90860                         return segments[0];
90861                     }
90862                 }
90863                 return emitHelpers().createSpreadHelper(segments);
90864             }
90865             else {
90866                 if (segments.length === 1) {
90867                     var firstSegment = segments[0];
90868                     if (!needsUniqueCopy
90869                         || isPackedArrayLiteral(firstSegment)
90870                         || isCallToHelper(firstSegment, "___spreadArrays")) {
90871                         return segments[0];
90872                     }
90873                 }
90874                 return emitHelpers().createSpreadArraysHelper(segments);
90875             }
90876         }
90877         function isPackedElement(node) {
90878             return !ts.isOmittedExpression(node);
90879         }
90880         function isPackedArrayLiteral(node) {
90881             return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
90882         }
90883         function isCallToHelper(firstSegment, helperName) {
90884             return ts.isCallExpression(firstSegment)
90885                 && ts.isIdentifier(firstSegment.expression)
90886                 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
90887                 && firstSegment.expression.escapedText === helperName;
90888         }
90889         function partitionSpread(node) {
90890             return ts.isSpreadElement(node)
90891                 ? visitSpanOfSpreads
90892                 : visitSpanOfNonSpreads;
90893         }
90894         function visitSpanOfSpreads(chunk) {
90895             return ts.map(chunk, visitExpressionOfSpread);
90896         }
90897         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
90898             return factory.createArrayLiteralExpression(ts.visitNodes(factory.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
90899         }
90900         function visitSpreadElement(node) {
90901             return ts.visitNode(node.expression, visitor, ts.isExpression);
90902         }
90903         /**
90904          * Transforms the expression of a SpreadExpression node.
90905          *
90906          * @param node A SpreadExpression node.
90907          */
90908         function visitExpressionOfSpread(node) {
90909             return ts.visitNode(node.expression, visitor, ts.isExpression);
90910         }
90911         /**
90912          * Visits a template literal.
90913          *
90914          * @param node A template literal.
90915          */
90916         function visitTemplateLiteral(node) {
90917             return ts.setTextRange(factory.createStringLiteral(node.text), node);
90918         }
90919         /**
90920          * Visits a string literal with an extended unicode escape.
90921          *
90922          * @param node A string literal.
90923          */
90924         function visitStringLiteral(node) {
90925             if (node.hasExtendedUnicodeEscape) {
90926                 return ts.setTextRange(factory.createStringLiteral(node.text), node);
90927             }
90928             return node;
90929         }
90930         /**
90931          * Visits a binary or octal (ES6) numeric literal.
90932          *
90933          * @param node A string literal.
90934          */
90935         function visitNumericLiteral(node) {
90936             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
90937                 return ts.setTextRange(factory.createNumericLiteral(node.text), node);
90938             }
90939             return node;
90940         }
90941         /**
90942          * Visits a TaggedTemplateExpression node.
90943          *
90944          * @param node A TaggedTemplateExpression node.
90945          */
90946         function visitTaggedTemplateExpression(node) {
90947             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
90948         }
90949         /**
90950          * Visits a TemplateExpression node.
90951          *
90952          * @param node A TemplateExpression node.
90953          */
90954         function visitTemplateExpression(node) {
90955             var expressions = [];
90956             addTemplateHead(expressions, node);
90957             addTemplateSpans(expressions, node);
90958             // createAdd will check if each expression binds less closely than binary '+'.
90959             // If it does, it wraps the expression in parentheses. Otherwise, something like
90960             //    `abc${ 1 << 2 }`
90961             // becomes
90962             //    "abc" + 1 << 2 + ""
90963             // which is really
90964             //    ("abc" + 1) << (2 + "")
90965             // rather than
90966             //    "abc" + (1 << 2) + ""
90967             var expression = ts.reduceLeft(expressions, factory.createAdd);
90968             if (ts.nodeIsSynthesized(expression)) {
90969                 ts.setTextRange(expression, node);
90970             }
90971             return expression;
90972         }
90973         /**
90974          * Gets a value indicating whether we need to include the head of a TemplateExpression.
90975          *
90976          * @param node A TemplateExpression node.
90977          */
90978         function shouldAddTemplateHead(node) {
90979             // If this expression has an empty head literal and the first template span has a non-empty
90980             // literal, then emitting the empty head literal is not necessary.
90981             //     `${ foo } and ${ bar }`
90982             // can be emitted as
90983             //     foo + " and " + bar
90984             // This is because it is only required that one of the first two operands in the emit
90985             // output must be a string literal, so that the other operand and all following operands
90986             // are forced into strings.
90987             //
90988             // If the first template span has an empty literal, then the head must still be emitted.
90989             //     `${ foo }${ bar }`
90990             // must still be emitted as
90991             //     "" + foo + bar
90992             // There is always atleast one templateSpan in this code path, since
90993             // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
90994             ts.Debug.assert(node.templateSpans.length !== 0);
90995             return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
90996         }
90997         /**
90998          * Adds the head of a TemplateExpression to an array of expressions.
90999          *
91000          * @param expressions An array of expressions.
91001          * @param node A TemplateExpression node.
91002          */
91003         function addTemplateHead(expressions, node) {
91004             if (!shouldAddTemplateHead(node)) {
91005                 return;
91006             }
91007             expressions.push(factory.createStringLiteral(node.head.text));
91008         }
91009         /**
91010          * Visits and adds the template spans of a TemplateExpression to an array of expressions.
91011          *
91012          * @param expressions An array of expressions.
91013          * @param node A TemplateExpression node.
91014          */
91015         function addTemplateSpans(expressions, node) {
91016             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
91017                 var span = _a[_i];
91018                 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
91019                 // Only emit if the literal is non-empty.
91020                 // The binary '+' operator is left-associative, so the first string concatenation
91021                 // with the head will force the result up to this point to be a string.
91022                 // Emitting a '+ ""' has no semantic effect for middles and tails.
91023                 if (span.literal.text.length !== 0) {
91024                     expressions.push(factory.createStringLiteral(span.literal.text));
91025                 }
91026             }
91027         }
91028         /**
91029          * Visits the `super` keyword
91030          */
91031         function visitSuperKeyword(isExpressionOfCall) {
91032             return hierarchyFacts & 8 /* NonStaticClassElement */
91033                 && !isExpressionOfCall
91034                 ? factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), "prototype")
91035                 : factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */);
91036         }
91037         function visitMetaProperty(node) {
91038             if (node.keywordToken === 102 /* NewKeyword */ && node.name.escapedText === "target") {
91039                 hierarchyFacts |= 16384 /* NewTarget */;
91040                 return factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */);
91041             }
91042             return node;
91043         }
91044         /**
91045          * Called by the printer just before a node is printed.
91046          *
91047          * @param hint A hint as to the intended usage of the node.
91048          * @param node The node to be printed.
91049          * @param emitCallback The callback used to emit the node.
91050          */
91051         function onEmitNode(hint, node, emitCallback) {
91052             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
91053                 // If we are tracking a captured `this`, keep track of the enclosing function.
91054                 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
91055                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
91056                     : 65 /* FunctionIncludes */);
91057                 previousOnEmitNode(hint, node, emitCallback);
91058                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
91059                 return;
91060             }
91061             previousOnEmitNode(hint, node, emitCallback);
91062         }
91063         /**
91064          * Enables a more costly code path for substitutions when we determine a source file
91065          * contains block-scoped bindings (e.g. `let` or `const`).
91066          */
91067         function enableSubstitutionsForBlockScopedBindings() {
91068             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
91069                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
91070                 context.enableSubstitution(78 /* Identifier */);
91071             }
91072         }
91073         /**
91074          * Enables a more costly code path for substitutions when we determine a source file
91075          * contains a captured `this`.
91076          */
91077         function enableSubstitutionsForCapturedThis() {
91078             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
91079                 enabledSubstitutions |= 1 /* CapturedThis */;
91080                 context.enableSubstitution(107 /* ThisKeyword */);
91081                 context.enableEmitNotification(166 /* Constructor */);
91082                 context.enableEmitNotification(165 /* MethodDeclaration */);
91083                 context.enableEmitNotification(167 /* GetAccessor */);
91084                 context.enableEmitNotification(168 /* SetAccessor */);
91085                 context.enableEmitNotification(209 /* ArrowFunction */);
91086                 context.enableEmitNotification(208 /* FunctionExpression */);
91087                 context.enableEmitNotification(251 /* FunctionDeclaration */);
91088             }
91089         }
91090         /**
91091          * Hooks node substitutions.
91092          *
91093          * @param hint The context for the emitter.
91094          * @param node The node to substitute.
91095          */
91096         function onSubstituteNode(hint, node) {
91097             node = previousOnSubstituteNode(hint, node);
91098             if (hint === 1 /* Expression */) {
91099                 return substituteExpression(node);
91100             }
91101             if (ts.isIdentifier(node)) {
91102                 return substituteIdentifier(node);
91103             }
91104             return node;
91105         }
91106         /**
91107          * Hooks substitutions for non-expression identifiers.
91108          */
91109         function substituteIdentifier(node) {
91110             // Only substitute the identifier if we have enabled substitutions for block-scoped
91111             // bindings.
91112             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
91113                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
91114                 if (original && isNameOfDeclarationWithCollidingName(original)) {
91115                     return ts.setTextRange(factory.getGeneratedNameForNode(original), node);
91116                 }
91117             }
91118             return node;
91119         }
91120         /**
91121          * Determines whether a name is the name of a declaration with a colliding name.
91122          * NOTE: This function expects to be called with an original source tree node.
91123          *
91124          * @param node An original source tree node.
91125          */
91126         function isNameOfDeclarationWithCollidingName(node) {
91127             switch (node.parent.kind) {
91128                 case 198 /* BindingElement */:
91129                 case 252 /* ClassDeclaration */:
91130                 case 255 /* EnumDeclaration */:
91131                 case 249 /* VariableDeclaration */:
91132                     return node.parent.name === node
91133                         && resolver.isDeclarationWithCollidingName(node.parent);
91134             }
91135             return false;
91136         }
91137         /**
91138          * Substitutes an expression.
91139          *
91140          * @param node An Expression node.
91141          */
91142         function substituteExpression(node) {
91143             switch (node.kind) {
91144                 case 78 /* Identifier */:
91145                     return substituteExpressionIdentifier(node);
91146                 case 107 /* ThisKeyword */:
91147                     return substituteThisKeyword(node);
91148             }
91149             return node;
91150         }
91151         /**
91152          * Substitutes an expression identifier.
91153          *
91154          * @param node An Identifier node.
91155          */
91156         function substituteExpressionIdentifier(node) {
91157             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
91158                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
91159                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
91160                     return ts.setTextRange(factory.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
91161                 }
91162             }
91163             return node;
91164         }
91165         function isPartOfClassBody(declaration, node) {
91166             var currentNode = ts.getParseTreeNode(node);
91167             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
91168                 // if the node has no correlation to a parse tree node, its definitely not
91169                 // part of the body.
91170                 // if the node is outside of the document range of the declaration, its
91171                 // definitely not part of the body.
91172                 return false;
91173             }
91174             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
91175             while (currentNode) {
91176                 if (currentNode === blockScope || currentNode === declaration) {
91177                     // if we are in the enclosing block scope of the declaration, we are definitely
91178                     // not inside the class body.
91179                     return false;
91180                 }
91181                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
91182                     return true;
91183                 }
91184                 currentNode = currentNode.parent;
91185             }
91186             return false;
91187         }
91188         /**
91189          * Substitutes `this` when contained within an arrow function.
91190          *
91191          * @param node The ThisKeyword node.
91192          */
91193         function substituteThisKeyword(node) {
91194             if (enabledSubstitutions & 1 /* CapturedThis */
91195                 && hierarchyFacts & 16 /* CapturesThis */) {
91196                 return ts.setTextRange(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), node);
91197             }
91198             return node;
91199         }
91200         function getClassMemberPrefix(node, member) {
91201             return ts.hasSyntacticModifier(member, 32 /* Static */)
91202                 ? factory.getInternalName(node)
91203                 : factory.createPropertyAccessExpression(factory.getInternalName(node), "prototype");
91204         }
91205         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
91206             if (!constructor || !hasExtendsClause) {
91207                 return false;
91208             }
91209             if (ts.some(constructor.parameters)) {
91210                 return false;
91211             }
91212             var statement = ts.firstOrUndefined(constructor.body.statements);
91213             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 233 /* ExpressionStatement */) {
91214                 return false;
91215             }
91216             var statementExpression = statement.expression;
91217             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 203 /* CallExpression */) {
91218                 return false;
91219             }
91220             var callTarget = statementExpression.expression;
91221             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 105 /* SuperKeyword */) {
91222                 return false;
91223             }
91224             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
91225             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 220 /* SpreadElement */) {
91226                 return false;
91227             }
91228             var expression = callArgument.expression;
91229             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
91230         }
91231     }
91232     ts.transformES2015 = transformES2015;
91233 })(ts || (ts = {}));
91234 /*@internal*/
91235 var ts;
91236 (function (ts) {
91237     /**
91238      * Transforms ES5 syntax into ES3 syntax.
91239      *
91240      * @param context Context and state information for the transformation.
91241      */
91242     function transformES5(context) {
91243         var factory = context.factory;
91244         var compilerOptions = context.getCompilerOptions();
91245         // enable emit notification only if using --jsx preserve or react-native
91246         var previousOnEmitNode;
91247         var noSubstitution;
91248         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
91249             previousOnEmitNode = context.onEmitNode;
91250             context.onEmitNode = onEmitNode;
91251             context.enableEmitNotification(275 /* JsxOpeningElement */);
91252             context.enableEmitNotification(276 /* JsxClosingElement */);
91253             context.enableEmitNotification(274 /* JsxSelfClosingElement */);
91254             noSubstitution = [];
91255         }
91256         var previousOnSubstituteNode = context.onSubstituteNode;
91257         context.onSubstituteNode = onSubstituteNode;
91258         context.enableSubstitution(201 /* PropertyAccessExpression */);
91259         context.enableSubstitution(288 /* PropertyAssignment */);
91260         return ts.chainBundle(context, transformSourceFile);
91261         /**
91262          * Transforms an ES5 source file to ES3.
91263          *
91264          * @param node A SourceFile
91265          */
91266         function transformSourceFile(node) {
91267             return node;
91268         }
91269         /**
91270          * Called by the printer just before a node is printed.
91271          *
91272          * @param hint A hint as to the intended usage of the node.
91273          * @param node The node to emit.
91274          * @param emitCallback A callback used to emit the node.
91275          */
91276         function onEmitNode(hint, node, emitCallback) {
91277             switch (node.kind) {
91278                 case 275 /* JsxOpeningElement */:
91279                 case 276 /* JsxClosingElement */:
91280                 case 274 /* JsxSelfClosingElement */:
91281                     var tagName = node.tagName;
91282                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
91283                     break;
91284             }
91285             previousOnEmitNode(hint, node, emitCallback);
91286         }
91287         /**
91288          * Hooks node substitutions.
91289          *
91290          * @param hint A hint as to the intended usage of the node.
91291          * @param node The node to substitute.
91292          */
91293         function onSubstituteNode(hint, node) {
91294             if (node.id && noSubstitution && noSubstitution[node.id]) {
91295                 return previousOnSubstituteNode(hint, node);
91296             }
91297             node = previousOnSubstituteNode(hint, node);
91298             if (ts.isPropertyAccessExpression(node)) {
91299                 return substitutePropertyAccessExpression(node);
91300             }
91301             else if (ts.isPropertyAssignment(node)) {
91302                 return substitutePropertyAssignment(node);
91303             }
91304             return node;
91305         }
91306         /**
91307          * Substitutes a PropertyAccessExpression whose name is a reserved word.
91308          *
91309          * @param node A PropertyAccessExpression
91310          */
91311         function substitutePropertyAccessExpression(node) {
91312             if (ts.isPrivateIdentifier(node.name)) {
91313                 return node;
91314             }
91315             var literalName = trySubstituteReservedName(node.name);
91316             if (literalName) {
91317                 return ts.setTextRange(factory.createElementAccessExpression(node.expression, literalName), node);
91318             }
91319             return node;
91320         }
91321         /**
91322          * Substitutes a PropertyAssignment whose name is a reserved word.
91323          *
91324          * @param node A PropertyAssignment
91325          */
91326         function substitutePropertyAssignment(node) {
91327             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
91328             if (literalName) {
91329                 return factory.updatePropertyAssignment(node, literalName, node.initializer);
91330             }
91331             return node;
91332         }
91333         /**
91334          * If an identifier name is a reserved word, returns a string literal for the name.
91335          *
91336          * @param name An Identifier
91337          */
91338         function trySubstituteReservedName(name) {
91339             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
91340             if (token !== undefined && token >= 80 /* FirstReservedWord */ && token <= 115 /* LastReservedWord */) {
91341                 return ts.setTextRange(factory.createStringLiteralFromNode(name), name);
91342             }
91343             return undefined;
91344         }
91345     }
91346     ts.transformES5 = transformES5;
91347 })(ts || (ts = {}));
91348 // Transforms generator functions into a compatible ES5 representation with similar runtime
91349 // semantics. This is accomplished by first transforming the body of each generator
91350 // function into an intermediate representation that is the compiled into a JavaScript
91351 // switch statement.
91352 //
91353 // Many functions in this transformer will contain comments indicating the expected
91354 // intermediate representation. For illustrative purposes, the following intermediate
91355 // language is used to define this intermediate representation:
91356 //
91357 //  .nop                            - Performs no operation.
91358 //  .local NAME, ...                - Define local variable declarations.
91359 //  .mark LABEL                     - Mark the location of a label.
91360 //  .br LABEL                       - Jump to a label. If jumping out of a protected
91361 //                                    region, all .finally blocks are executed.
91362 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
91363 //                                    If jumping out of a protected region, all .finally
91364 //                                    blocks are executed.
91365 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
91366 //                                    If jumping out of a protected region, all .finally
91367 //                                    blocks are executed.
91368 //  .yield (x)                      - Yield the value of the optional expression `x`.
91369 //                                    Resume at the next label.
91370 //  .yieldstar (x)                  - Delegate yield to the value of the optional
91371 //                                    expression `x`. Resume at the next label.
91372 //                                    NOTE: `x` must be an Iterator, not an Iterable.
91373 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
91374 //                                    "break" abrupt completions jump to the CONTINUE or
91375 //                                    BREAK labels, respectively.
91376 //  .endloop                        - Marks the end of a loop.
91377 //  .with (x)                       - Marks the beginning of a WithStatement block, using
91378 //                                    the supplied expression.
91379 //  .endwith                        - Marks the end of a WithStatement.
91380 //  .switch                         - Marks the beginning of a SwitchStatement.
91381 //  .endswitch                      - Marks the end of a SwitchStatement.
91382 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
91383 //                                    supplied name.
91384 //  .endlabeled                     - Marks the end of a LabeledStatement.
91385 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
91386 //                                    labels for each block.
91387 //  .catch (x)                      - Marks the beginning of a catch block.
91388 //  .finally                        - Marks the beginning of a finally block.
91389 //  .endfinally                     - Marks the end of a finally block.
91390 //  .endtry                         - Marks the end of a protected region.
91391 //  .throw (x)                      - Throws the value of the expression `x`.
91392 //  .return (x)                     - Returns the value of the expression `x`.
91393 //
91394 // In addition, the illustrative intermediate representation introduces some special
91395 // variables:
91396 //
91397 //  %sent%                          - Either returns the next value sent to the generator,
91398 //                                    returns the result of a delegated yield, or throws
91399 //                                    the exception sent to the generator.
91400 //  %error%                         - Returns the value of the current exception in a
91401 //                                    catch block.
91402 //
91403 // This intermediate representation is then compiled into JavaScript syntax. The resulting
91404 // compilation output looks something like the following:
91405 //
91406 //  function f() {
91407 //      var /*locals*/;
91408 //      /*functions*/
91409 //      return __generator(function (state) {
91410 //          switch (state.label) {
91411 //              /*cases per label*/
91412 //          }
91413 //      });
91414 //  }
91415 //
91416 // Each of the above instructions corresponds to JavaScript emit similar to the following:
91417 //
91418 //  .local NAME                   | var NAME;
91419 // -------------------------------|----------------------------------------------
91420 //  .mark LABEL                   | case LABEL:
91421 // -------------------------------|----------------------------------------------
91422 //  .br LABEL                     |     return [3 /*break*/, LABEL];
91423 // -------------------------------|----------------------------------------------
91424 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
91425 // -------------------------------|----------------------------------------------
91426 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
91427 // -------------------------------|----------------------------------------------
91428 //  .yield (x)                    |     return [4 /*yield*/, x];
91429 //  .mark RESUME                  | case RESUME:
91430 //      a = %sent%;               |     a = state.sent();
91431 // -------------------------------|----------------------------------------------
91432 //  .yieldstar (x)                |     return [5 /*yield**/, x];
91433 //  .mark RESUME                  | case RESUME:
91434 //      a = %sent%;               |     a = state.sent();
91435 // -------------------------------|----------------------------------------------
91436 //  .with (_a)                    |     with (_a) {
91437 //      a();                      |         a();
91438 //                                |     }
91439 //                                |     state.label = LABEL;
91440 //  .mark LABEL                   | case LABEL:
91441 //                                |     with (_a) {
91442 //      b();                      |         b();
91443 //                                |     }
91444 //  .endwith                      |
91445 // -------------------------------|----------------------------------------------
91446 //                                | case 0:
91447 //                                |     state.trys = [];
91448 //                                | ...
91449 //  .try TRY, CATCH, FINALLY, END |
91450 //  .mark TRY                     | case TRY:
91451 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
91452 //  .nop                          |
91453 //      a();                      |     a();
91454 //  .br END                       |     return [3 /*break*/, END];
91455 //  .catch (e)                    |
91456 //  .mark CATCH                   | case CATCH:
91457 //                                |     e = state.sent();
91458 //      b();                      |     b();
91459 //  .br END                       |     return [3 /*break*/, END];
91460 //  .finally                      |
91461 //  .mark FINALLY                 | case FINALLY:
91462 //      c();                      |     c();
91463 //  .endfinally                   |     return [7 /*endfinally*/];
91464 //  .endtry                       |
91465 //  .mark END                     | case END:
91466 /*@internal*/
91467 var ts;
91468 (function (ts) {
91469     var OpCode;
91470     (function (OpCode) {
91471         OpCode[OpCode["Nop"] = 0] = "Nop";
91472         OpCode[OpCode["Statement"] = 1] = "Statement";
91473         OpCode[OpCode["Assign"] = 2] = "Assign";
91474         OpCode[OpCode["Break"] = 3] = "Break";
91475         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
91476         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
91477         OpCode[OpCode["Yield"] = 6] = "Yield";
91478         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
91479         OpCode[OpCode["Return"] = 8] = "Return";
91480         OpCode[OpCode["Throw"] = 9] = "Throw";
91481         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
91482     })(OpCode || (OpCode = {}));
91483     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
91484     var BlockAction;
91485     (function (BlockAction) {
91486         BlockAction[BlockAction["Open"] = 0] = "Open";
91487         BlockAction[BlockAction["Close"] = 1] = "Close";
91488     })(BlockAction || (BlockAction = {}));
91489     // the kind for a generated code block in a FunctionBuilder
91490     var CodeBlockKind;
91491     (function (CodeBlockKind) {
91492         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
91493         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
91494         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
91495         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
91496         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
91497     })(CodeBlockKind || (CodeBlockKind = {}));
91498     // the state for a generated code exception block
91499     var ExceptionBlockState;
91500     (function (ExceptionBlockState) {
91501         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
91502         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
91503         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
91504         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
91505     })(ExceptionBlockState || (ExceptionBlockState = {}));
91506     // NOTE: changes to this enum should be reflected in the __generator helper.
91507     var Instruction;
91508     (function (Instruction) {
91509         Instruction[Instruction["Next"] = 0] = "Next";
91510         Instruction[Instruction["Throw"] = 1] = "Throw";
91511         Instruction[Instruction["Return"] = 2] = "Return";
91512         Instruction[Instruction["Break"] = 3] = "Break";
91513         Instruction[Instruction["Yield"] = 4] = "Yield";
91514         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
91515         Instruction[Instruction["Catch"] = 6] = "Catch";
91516         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
91517     })(Instruction || (Instruction = {}));
91518     function getInstructionName(instruction) {
91519         switch (instruction) {
91520             case 2 /* Return */: return "return";
91521             case 3 /* Break */: return "break";
91522             case 4 /* Yield */: return "yield";
91523             case 5 /* YieldStar */: return "yield*";
91524             case 7 /* Endfinally */: return "endfinally";
91525             default: return undefined; // TODO: GH#18217
91526         }
91527     }
91528     function transformGenerators(context) {
91529         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
91530         var compilerOptions = context.getCompilerOptions();
91531         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
91532         var resolver = context.getEmitResolver();
91533         var previousOnSubstituteNode = context.onSubstituteNode;
91534         context.onSubstituteNode = onSubstituteNode;
91535         var renamedCatchVariables;
91536         var renamedCatchVariableDeclarations;
91537         var inGeneratorFunctionBody;
91538         var inStatementContainingYield;
91539         // The following three arrays store information about generated code blocks.
91540         // All three arrays are correlated by their index. This approach is used over allocating
91541         // objects to store the same information to avoid GC overhead.
91542         //
91543         var blocks; // Information about the code block
91544         var blockOffsets; // The operation offset at which a code block begins or ends
91545         var blockActions; // Whether the code block is opened or closed
91546         var blockStack; // A stack of currently open code blocks
91547         // Labels are used to mark locations in the code that can be the target of a Break (jump)
91548         // operation. These are translated into case clauses in a switch statement.
91549         // The following two arrays are correlated by their index. This approach is used over
91550         // allocating objects to store the same information to avoid GC overhead.
91551         //
91552         var labelOffsets; // The operation offset at which the label is defined.
91553         var labelExpressions; // The NumericLiteral nodes bound to each label.
91554         var nextLabelId = 1; // The next label id to use.
91555         // Operations store information about generated code for the function body. This
91556         // Includes things like statements, assignments, breaks (jumps), and yields.
91557         // The following three arrays are correlated by their index. This approach is used over
91558         // allocating objects to store the same information to avoid GC overhead.
91559         //
91560         var operations; // The operation to perform.
91561         var operationArguments; // The arguments to the operation.
91562         var operationLocations; // The source map location for the operation.
91563         var state; // The name of the state object used by the generator at runtime.
91564         // The following variables store information used by the `build` function:
91565         //
91566         var blockIndex = 0; // The index of the current block.
91567         var labelNumber = 0; // The current label number.
91568         var labelNumbers;
91569         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
91570         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
91571         var clauses; // The case clauses generated for labels.
91572         var statements; // The statements for the current label.
91573         var exceptionBlockStack; // A stack of containing exception blocks.
91574         var currentExceptionBlock; // The current exception block.
91575         var withBlockStack; // A stack containing `with` blocks.
91576         return ts.chainBundle(context, transformSourceFile);
91577         function transformSourceFile(node) {
91578             if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
91579                 return node;
91580             }
91581             var visited = ts.visitEachChild(node, visitor, context);
91582             ts.addEmitHelpers(visited, context.readEmitHelpers());
91583             return visited;
91584         }
91585         /**
91586          * Visits a node.
91587          *
91588          * @param node The node to visit.
91589          */
91590         function visitor(node) {
91591             var transformFlags = node.transformFlags;
91592             if (inStatementContainingYield) {
91593                 return visitJavaScriptInStatementContainingYield(node);
91594             }
91595             else if (inGeneratorFunctionBody) {
91596                 return visitJavaScriptInGeneratorFunctionBody(node);
91597             }
91598             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
91599                 return visitGenerator(node);
91600             }
91601             else if (transformFlags & 512 /* ContainsGenerator */) {
91602                 return ts.visitEachChild(node, visitor, context);
91603             }
91604             else {
91605                 return node;
91606             }
91607         }
91608         /**
91609          * Visits a node that is contained within a statement that contains yield.
91610          *
91611          * @param node The node to visit.
91612          */
91613         function visitJavaScriptInStatementContainingYield(node) {
91614             switch (node.kind) {
91615                 case 235 /* DoStatement */:
91616                     return visitDoStatement(node);
91617                 case 236 /* WhileStatement */:
91618                     return visitWhileStatement(node);
91619                 case 244 /* SwitchStatement */:
91620                     return visitSwitchStatement(node);
91621                 case 245 /* LabeledStatement */:
91622                     return visitLabeledStatement(node);
91623                 default:
91624                     return visitJavaScriptInGeneratorFunctionBody(node);
91625             }
91626         }
91627         /**
91628          * Visits a node that is contained within a generator function.
91629          *
91630          * @param node The node to visit.
91631          */
91632         function visitJavaScriptInGeneratorFunctionBody(node) {
91633             switch (node.kind) {
91634                 case 251 /* FunctionDeclaration */:
91635                     return visitFunctionDeclaration(node);
91636                 case 208 /* FunctionExpression */:
91637                     return visitFunctionExpression(node);
91638                 case 167 /* GetAccessor */:
91639                 case 168 /* SetAccessor */:
91640                     return visitAccessorDeclaration(node);
91641                 case 232 /* VariableStatement */:
91642                     return visitVariableStatement(node);
91643                 case 237 /* ForStatement */:
91644                     return visitForStatement(node);
91645                 case 238 /* ForInStatement */:
91646                     return visitForInStatement(node);
91647                 case 241 /* BreakStatement */:
91648                     return visitBreakStatement(node);
91649                 case 240 /* ContinueStatement */:
91650                     return visitContinueStatement(node);
91651                 case 242 /* ReturnStatement */:
91652                     return visitReturnStatement(node);
91653                 default:
91654                     if (node.transformFlags & 262144 /* ContainsYield */) {
91655                         return visitJavaScriptContainingYield(node);
91656                     }
91657                     else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
91658                         return ts.visitEachChild(node, visitor, context);
91659                     }
91660                     else {
91661                         return node;
91662                     }
91663             }
91664         }
91665         /**
91666          * Visits a node that contains a YieldExpression.
91667          *
91668          * @param node The node to visit.
91669          */
91670         function visitJavaScriptContainingYield(node) {
91671             switch (node.kind) {
91672                 case 216 /* BinaryExpression */:
91673                     return visitBinaryExpression(node);
91674                 case 337 /* CommaListExpression */:
91675                     return visitCommaListExpression(node);
91676                 case 217 /* ConditionalExpression */:
91677                     return visitConditionalExpression(node);
91678                 case 219 /* YieldExpression */:
91679                     return visitYieldExpression(node);
91680                 case 199 /* ArrayLiteralExpression */:
91681                     return visitArrayLiteralExpression(node);
91682                 case 200 /* ObjectLiteralExpression */:
91683                     return visitObjectLiteralExpression(node);
91684                 case 202 /* ElementAccessExpression */:
91685                     return visitElementAccessExpression(node);
91686                 case 203 /* CallExpression */:
91687                     return visitCallExpression(node);
91688                 case 204 /* NewExpression */:
91689                     return visitNewExpression(node);
91690                 default:
91691                     return ts.visitEachChild(node, visitor, context);
91692             }
91693         }
91694         /**
91695          * Visits a generator function.
91696          *
91697          * @param node The node to visit.
91698          */
91699         function visitGenerator(node) {
91700             switch (node.kind) {
91701                 case 251 /* FunctionDeclaration */:
91702                     return visitFunctionDeclaration(node);
91703                 case 208 /* FunctionExpression */:
91704                     return visitFunctionExpression(node);
91705                 default:
91706                     return ts.Debug.failBadSyntaxKind(node);
91707             }
91708         }
91709         /**
91710          * Visits a function declaration.
91711          *
91712          * This will be called when one of the following conditions are met:
91713          * - The function declaration is a generator function.
91714          * - The function declaration is contained within the body of a generator function.
91715          *
91716          * @param node The node to visit.
91717          */
91718         function visitFunctionDeclaration(node) {
91719             // Currently, we only support generators that were originally async functions.
91720             if (node.asteriskToken) {
91721                 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
91722                 /*decorators*/ undefined, node.modifiers, 
91723                 /*asteriskToken*/ undefined, node.name, 
91724                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
91725                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
91726                 /*location*/ node), node);
91727             }
91728             else {
91729                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
91730                 var savedInStatementContainingYield = inStatementContainingYield;
91731                 inGeneratorFunctionBody = false;
91732                 inStatementContainingYield = false;
91733                 node = ts.visitEachChild(node, visitor, context);
91734                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
91735                 inStatementContainingYield = savedInStatementContainingYield;
91736             }
91737             if (inGeneratorFunctionBody) {
91738                 // Function declarations in a generator function body are hoisted
91739                 // to the top of the lexical scope and elided from the current statement.
91740                 hoistFunctionDeclaration(node);
91741                 return undefined;
91742             }
91743             else {
91744                 return node;
91745             }
91746         }
91747         /**
91748          * Visits a function expression.
91749          *
91750          * This will be called when one of the following conditions are met:
91751          * - The function expression is a generator function.
91752          * - The function expression is contained within the body of a generator function.
91753          *
91754          * @param node The node to visit.
91755          */
91756         function visitFunctionExpression(node) {
91757             // Currently, we only support generators that were originally async functions.
91758             if (node.asteriskToken) {
91759                 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
91760                 /*modifiers*/ undefined, 
91761                 /*asteriskToken*/ undefined, node.name, 
91762                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
91763                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
91764                 /*location*/ node), node);
91765             }
91766             else {
91767                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
91768                 var savedInStatementContainingYield = inStatementContainingYield;
91769                 inGeneratorFunctionBody = false;
91770                 inStatementContainingYield = false;
91771                 node = ts.visitEachChild(node, visitor, context);
91772                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
91773                 inStatementContainingYield = savedInStatementContainingYield;
91774             }
91775             return node;
91776         }
91777         /**
91778          * Visits a get or set accessor declaration.
91779          *
91780          * This will be called when one of the following conditions are met:
91781          * - The accessor is contained within the body of a generator function.
91782          *
91783          * @param node The node to visit.
91784          */
91785         function visitAccessorDeclaration(node) {
91786             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
91787             var savedInStatementContainingYield = inStatementContainingYield;
91788             inGeneratorFunctionBody = false;
91789             inStatementContainingYield = false;
91790             node = ts.visitEachChild(node, visitor, context);
91791             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
91792             inStatementContainingYield = savedInStatementContainingYield;
91793             return node;
91794         }
91795         /**
91796          * Transforms the body of a generator function declaration.
91797          *
91798          * @param node The function body to transform.
91799          */
91800         function transformGeneratorFunctionBody(body) {
91801             // Save existing generator state
91802             var statements = [];
91803             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
91804             var savedInStatementContainingYield = inStatementContainingYield;
91805             var savedBlocks = blocks;
91806             var savedBlockOffsets = blockOffsets;
91807             var savedBlockActions = blockActions;
91808             var savedBlockStack = blockStack;
91809             var savedLabelOffsets = labelOffsets;
91810             var savedLabelExpressions = labelExpressions;
91811             var savedNextLabelId = nextLabelId;
91812             var savedOperations = operations;
91813             var savedOperationArguments = operationArguments;
91814             var savedOperationLocations = operationLocations;
91815             var savedState = state;
91816             // Initialize generator state
91817             inGeneratorFunctionBody = true;
91818             inStatementContainingYield = false;
91819             blocks = undefined;
91820             blockOffsets = undefined;
91821             blockActions = undefined;
91822             blockStack = undefined;
91823             labelOffsets = undefined;
91824             labelExpressions = undefined;
91825             nextLabelId = 1;
91826             operations = undefined;
91827             operationArguments = undefined;
91828             operationLocations = undefined;
91829             state = factory.createTempVariable(/*recordTempVariable*/ undefined);
91830             // Build the generator
91831             resumeLexicalEnvironment();
91832             var statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
91833             transformAndEmitStatements(body.statements, statementOffset);
91834             var buildResult = build();
91835             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
91836             statements.push(factory.createReturnStatement(buildResult));
91837             // Restore previous generator state
91838             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
91839             inStatementContainingYield = savedInStatementContainingYield;
91840             blocks = savedBlocks;
91841             blockOffsets = savedBlockOffsets;
91842             blockActions = savedBlockActions;
91843             blockStack = savedBlockStack;
91844             labelOffsets = savedLabelOffsets;
91845             labelExpressions = savedLabelExpressions;
91846             nextLabelId = savedNextLabelId;
91847             operations = savedOperations;
91848             operationArguments = savedOperationArguments;
91849             operationLocations = savedOperationLocations;
91850             state = savedState;
91851             return ts.setTextRange(factory.createBlock(statements, body.multiLine), body);
91852         }
91853         /**
91854          * Visits a variable statement.
91855          *
91856          * This will be called when one of the following conditions are met:
91857          * - The variable statement is contained within the body of a generator function.
91858          *
91859          * @param node The node to visit.
91860          */
91861         function visitVariableStatement(node) {
91862             if (node.transformFlags & 262144 /* ContainsYield */) {
91863                 transformAndEmitVariableDeclarationList(node.declarationList);
91864                 return undefined;
91865             }
91866             else {
91867                 // Do not hoist custom prologues.
91868                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
91869                     return node;
91870                 }
91871                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
91872                     var variable = _a[_i];
91873                     hoistVariableDeclaration(variable.name);
91874                 }
91875                 var variables = ts.getInitializedVariables(node.declarationList);
91876                 if (variables.length === 0) {
91877                     return undefined;
91878                 }
91879                 return ts.setSourceMapRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
91880             }
91881         }
91882         /**
91883          * Visits a binary expression.
91884          *
91885          * This will be called when one of the following conditions are met:
91886          * - The node contains a YieldExpression.
91887          *
91888          * @param node The node to visit.
91889          */
91890         function visitBinaryExpression(node) {
91891             var assoc = ts.getExpressionAssociativity(node);
91892             switch (assoc) {
91893                 case 0 /* Left */:
91894                     return visitLeftAssociativeBinaryExpression(node);
91895                 case 1 /* Right */:
91896                     return visitRightAssociativeBinaryExpression(node);
91897                 default:
91898                     return ts.Debug.assertNever(assoc);
91899             }
91900         }
91901         /**
91902          * Visits a right-associative binary expression containing `yield`.
91903          *
91904          * @param node The node to visit.
91905          */
91906         function visitRightAssociativeBinaryExpression(node) {
91907             var left = node.left, right = node.right;
91908             if (containsYield(right)) {
91909                 var target = void 0;
91910                 switch (left.kind) {
91911                     case 201 /* PropertyAccessExpression */:
91912                         // [source]
91913                         //      a.b = yield;
91914                         //
91915                         // [intermediate]
91916                         //  .local _a
91917                         //      _a = a;
91918                         //  .yield resumeLabel
91919                         //  .mark resumeLabel
91920                         //      _a.b = %sent%;
91921                         target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
91922                         break;
91923                     case 202 /* ElementAccessExpression */:
91924                         // [source]
91925                         //      a[b] = yield;
91926                         //
91927                         // [intermediate]
91928                         //  .local _a, _b
91929                         //      _a = a;
91930                         //      _b = b;
91931                         //  .yield resumeLabel
91932                         //  .mark resumeLabel
91933                         //      _a[_b] = %sent%;
91934                         target = factory.updateElementAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
91935                         break;
91936                     default:
91937                         target = ts.visitNode(left, visitor, ts.isExpression);
91938                         break;
91939                 }
91940                 var operator = node.operatorToken.kind;
91941                 if (ts.isCompoundAssignment(operator)) {
91942                     return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createBinaryExpression(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
91943                 }
91944                 else {
91945                     return factory.updateBinaryExpression(node, target, node.operatorToken, ts.visitNode(right, visitor, ts.isExpression));
91946                 }
91947             }
91948             return ts.visitEachChild(node, visitor, context);
91949         }
91950         function visitLeftAssociativeBinaryExpression(node) {
91951             if (containsYield(node.right)) {
91952                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
91953                     return visitLogicalBinaryExpression(node);
91954                 }
91955                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
91956                     return visitCommaExpression(node);
91957                 }
91958                 // [source]
91959                 //      a() + (yield) + c()
91960                 //
91961                 // [intermediate]
91962                 //  .local _a
91963                 //      _a = a();
91964                 //  .yield resumeLabel
91965                 //      _a + %sent% + c()
91966                 return factory.updateBinaryExpression(node, cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)), node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
91967             }
91968             return ts.visitEachChild(node, visitor, context);
91969         }
91970         /**
91971          * Visits a comma expression containing `yield`.
91972          *
91973          * @param node The node to visit.
91974          */
91975         function visitCommaExpression(node) {
91976             // [source]
91977             //      x = a(), yield, b();
91978             //
91979             // [intermediate]
91980             //      a();
91981             //  .yield resumeLabel
91982             //  .mark resumeLabel
91983             //      x = %sent%, b();
91984             var pendingExpressions = [];
91985             visit(node.left);
91986             visit(node.right);
91987             return factory.inlineExpressions(pendingExpressions);
91988             function visit(node) {
91989                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
91990                     visit(node.left);
91991                     visit(node.right);
91992                 }
91993                 else {
91994                     if (containsYield(node) && pendingExpressions.length > 0) {
91995                         emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
91996                         pendingExpressions = [];
91997                     }
91998                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
91999                 }
92000             }
92001         }
92002         /**
92003          * Visits a comma-list expression.
92004          *
92005          * @param node The node to visit.
92006          */
92007         function visitCommaListExpression(node) {
92008             // flattened version of `visitCommaExpression`
92009             var pendingExpressions = [];
92010             for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
92011                 var elem = _a[_i];
92012                 if (ts.isBinaryExpression(elem) && elem.operatorToken.kind === 27 /* CommaToken */) {
92013                     pendingExpressions.push(visitCommaExpression(elem));
92014                 }
92015                 else {
92016                     if (containsYield(elem) && pendingExpressions.length > 0) {
92017                         emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
92018                         pendingExpressions = [];
92019                     }
92020                     pendingExpressions.push(ts.visitNode(elem, visitor, ts.isExpression));
92021                 }
92022             }
92023             return factory.inlineExpressions(pendingExpressions);
92024         }
92025         /**
92026          * Visits a logical binary expression containing `yield`.
92027          *
92028          * @param node A node to visit.
92029          */
92030         function visitLogicalBinaryExpression(node) {
92031             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
92032             // to be transformed as such:
92033             //
92034             // [source]
92035             //      x = a() && yield;
92036             //
92037             // [intermediate]
92038             //  .local _a
92039             //      _a = a();
92040             //  .brfalse resultLabel, (_a)
92041             //  .yield resumeLabel
92042             //  .mark resumeLabel
92043             //      _a = %sent%;
92044             //  .mark resultLabel
92045             //      x = _a;
92046             //
92047             // [source]
92048             //      x = a() || yield;
92049             //
92050             // [intermediate]
92051             //  .local _a
92052             //      _a = a();
92053             //  .brtrue resultLabel, (_a)
92054             //  .yield resumeLabel
92055             //  .mark resumeLabel
92056             //      _a = %sent%;
92057             //  .mark resultLabel
92058             //      x = _a;
92059             var resultLabel = defineLabel();
92060             var resultLocal = declareLocal();
92061             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
92062             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
92063                 // Logical `&&` shortcuts when the left-hand operand is falsey.
92064                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
92065             }
92066             else {
92067                 // Logical `||` shortcuts when the left-hand operand is truthy.
92068                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
92069             }
92070             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
92071             markLabel(resultLabel);
92072             return resultLocal;
92073         }
92074         /**
92075          * Visits a conditional expression containing `yield`.
92076          *
92077          * @param node The node to visit.
92078          */
92079         function visitConditionalExpression(node) {
92080             // [source]
92081             //      x = a() ? yield : b();
92082             //
92083             // [intermediate]
92084             //  .local _a
92085             //  .brfalse whenFalseLabel, (a())
92086             //  .yield resumeLabel
92087             //  .mark resumeLabel
92088             //      _a = %sent%;
92089             //  .br resultLabel
92090             //  .mark whenFalseLabel
92091             //      _a = b();
92092             //  .mark resultLabel
92093             //      x = _a;
92094             // We only need to perform a specific transformation if a `yield` expression exists
92095             // in either the `whenTrue` or `whenFalse` branches.
92096             // A `yield` in the condition will be handled by the normal visitor.
92097             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
92098                 var whenFalseLabel = defineLabel();
92099                 var resultLabel = defineLabel();
92100                 var resultLocal = declareLocal();
92101                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
92102                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
92103                 emitBreak(resultLabel);
92104                 markLabel(whenFalseLabel);
92105                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
92106                 markLabel(resultLabel);
92107                 return resultLocal;
92108             }
92109             return ts.visitEachChild(node, visitor, context);
92110         }
92111         /**
92112          * Visits a `yield` expression.
92113          *
92114          * @param node The node to visit.
92115          */
92116         function visitYieldExpression(node) {
92117             // [source]
92118             //      x = yield a();
92119             //
92120             // [intermediate]
92121             //  .yield resumeLabel, (a())
92122             //  .mark resumeLabel
92123             //      x = %sent%;
92124             var resumeLabel = defineLabel();
92125             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
92126             if (node.asteriskToken) {
92127                 // NOTE: `expression` must be defined for `yield*`.
92128                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
92129                     ? ts.setTextRange(emitHelpers().createValuesHelper(expression), node)
92130                     : expression;
92131                 emitYieldStar(iterator, /*location*/ node);
92132             }
92133             else {
92134                 emitYield(expression, /*location*/ node);
92135             }
92136             markLabel(resumeLabel);
92137             return createGeneratorResume(/*location*/ node);
92138         }
92139         /**
92140          * Visits an ArrayLiteralExpression that contains a YieldExpression.
92141          *
92142          * @param node The node to visit.
92143          */
92144         function visitArrayLiteralExpression(node) {
92145             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
92146         }
92147         /**
92148          * Visits an array of expressions containing one or more YieldExpression nodes
92149          * and returns an expression for the resulting value.
92150          *
92151          * @param elements The elements to visit.
92152          * @param multiLine Whether array literals created should be emitted on multiple lines.
92153          */
92154         function visitElements(elements, leadingElement, location, multiLine) {
92155             // [source]
92156             //      ar = [1, yield, 2];
92157             //
92158             // [intermediate]
92159             //  .local _a
92160             //      _a = [1];
92161             //  .yield resumeLabel
92162             //  .mark resumeLabel
92163             //      ar = _a.concat([%sent%, 2]);
92164             var numInitialElements = countInitialNodesWithoutYield(elements);
92165             var temp;
92166             if (numInitialElements > 0) {
92167                 temp = declareLocal();
92168                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
92169                 emitAssignment(temp, factory.createArrayLiteralExpression(leadingElement
92170                     ? __spreadArrays([leadingElement], initialElements) : initialElements));
92171                 leadingElement = undefined;
92172             }
92173             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
92174             return temp
92175                 ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
92176                 : ts.setTextRange(factory.createArrayLiteralExpression(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
92177             function reduceElement(expressions, element) {
92178                 if (containsYield(element) && expressions.length > 0) {
92179                     var hasAssignedTemp = temp !== undefined;
92180                     if (!temp) {
92181                         temp = declareLocal();
92182                     }
92183                     emitAssignment(temp, hasAssignedTemp
92184                         ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
92185                         : factory.createArrayLiteralExpression(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
92186                     leadingElement = undefined;
92187                     expressions = [];
92188                 }
92189                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
92190                 return expressions;
92191             }
92192         }
92193         function visitObjectLiteralExpression(node) {
92194             // [source]
92195             //      o = {
92196             //          a: 1,
92197             //          b: yield,
92198             //          c: 2
92199             //      };
92200             //
92201             // [intermediate]
92202             //  .local _a
92203             //      _a = {
92204             //          a: 1
92205             //      };
92206             //  .yield resumeLabel
92207             //  .mark resumeLabel
92208             //      o = (_a.b = %sent%,
92209             //          _a.c = 2,
92210             //          _a);
92211             var properties = node.properties;
92212             var multiLine = node.multiLine;
92213             var numInitialProperties = countInitialNodesWithoutYield(properties);
92214             var temp = declareLocal();
92215             emitAssignment(temp, factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
92216             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
92217             // TODO(rbuckton): Does this need to be parented?
92218             expressions.push(multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
92219             return factory.inlineExpressions(expressions);
92220             function reduceProperty(expressions, property) {
92221                 if (containsYield(property) && expressions.length > 0) {
92222                     emitStatement(factory.createExpressionStatement(factory.inlineExpressions(expressions)));
92223                     expressions = [];
92224                 }
92225                 var expression = ts.createExpressionForObjectLiteralElementLike(factory, node, property, temp);
92226                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
92227                 if (visited) {
92228                     if (multiLine) {
92229                         ts.startOnNewLine(visited);
92230                     }
92231                     expressions.push(visited);
92232                 }
92233                 return expressions;
92234             }
92235         }
92236         /**
92237          * Visits an ElementAccessExpression that contains a YieldExpression.
92238          *
92239          * @param node The node to visit.
92240          */
92241         function visitElementAccessExpression(node) {
92242             if (containsYield(node.argumentExpression)) {
92243                 // [source]
92244                 //      a = x[yield];
92245                 //
92246                 // [intermediate]
92247                 //  .local _a
92248                 //      _a = x;
92249                 //  .yield resumeLabel
92250                 //  .mark resumeLabel
92251                 //      a = _a[%sent%]
92252                 return factory.updateElementAccessExpression(node, cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)), ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
92253             }
92254             return ts.visitEachChild(node, visitor, context);
92255         }
92256         function visitCallExpression(node) {
92257             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
92258                 // [source]
92259                 //      a.b(1, yield, 2);
92260                 //
92261                 // [intermediate]
92262                 //  .local _a, _b, _c
92263                 //      _b = (_a = a).b;
92264                 //      _c = [1];
92265                 //  .yield resumeLabel
92266                 //  .mark resumeLabel
92267                 //      _b.apply(_a, _c.concat([%sent%, 2]));
92268                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
92269                 return ts.setOriginalNode(ts.setTextRange(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments)), node), node);
92270             }
92271             return ts.visitEachChild(node, visitor, context);
92272         }
92273         function visitNewExpression(node) {
92274             if (ts.forEach(node.arguments, containsYield)) {
92275                 // [source]
92276                 //      new a.b(1, yield, 2);
92277                 //
92278                 // [intermediate]
92279                 //  .local _a, _b, _c
92280                 //      _b = (_a = a.b).bind;
92281                 //      _c = [1];
92282                 //  .yield resumeLabel
92283                 //  .mark resumeLabel
92284                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
92285                 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
92286                 return ts.setOriginalNode(ts.setTextRange(factory.createNewExpression(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
92287                 /*leadingElement*/ factory.createVoidZero())), 
92288                 /*typeArguments*/ undefined, []), node), node);
92289             }
92290             return ts.visitEachChild(node, visitor, context);
92291         }
92292         function transformAndEmitStatements(statements, start) {
92293             if (start === void 0) { start = 0; }
92294             var numStatements = statements.length;
92295             for (var i = start; i < numStatements; i++) {
92296                 transformAndEmitStatement(statements[i]);
92297             }
92298         }
92299         function transformAndEmitEmbeddedStatement(node) {
92300             if (ts.isBlock(node)) {
92301                 transformAndEmitStatements(node.statements);
92302             }
92303             else {
92304                 transformAndEmitStatement(node);
92305             }
92306         }
92307         function transformAndEmitStatement(node) {
92308             var savedInStatementContainingYield = inStatementContainingYield;
92309             if (!inStatementContainingYield) {
92310                 inStatementContainingYield = containsYield(node);
92311             }
92312             transformAndEmitStatementWorker(node);
92313             inStatementContainingYield = savedInStatementContainingYield;
92314         }
92315         function transformAndEmitStatementWorker(node) {
92316             switch (node.kind) {
92317                 case 230 /* Block */:
92318                     return transformAndEmitBlock(node);
92319                 case 233 /* ExpressionStatement */:
92320                     return transformAndEmitExpressionStatement(node);
92321                 case 234 /* IfStatement */:
92322                     return transformAndEmitIfStatement(node);
92323                 case 235 /* DoStatement */:
92324                     return transformAndEmitDoStatement(node);
92325                 case 236 /* WhileStatement */:
92326                     return transformAndEmitWhileStatement(node);
92327                 case 237 /* ForStatement */:
92328                     return transformAndEmitForStatement(node);
92329                 case 238 /* ForInStatement */:
92330                     return transformAndEmitForInStatement(node);
92331                 case 240 /* ContinueStatement */:
92332                     return transformAndEmitContinueStatement(node);
92333                 case 241 /* BreakStatement */:
92334                     return transformAndEmitBreakStatement(node);
92335                 case 242 /* ReturnStatement */:
92336                     return transformAndEmitReturnStatement(node);
92337                 case 243 /* WithStatement */:
92338                     return transformAndEmitWithStatement(node);
92339                 case 244 /* SwitchStatement */:
92340                     return transformAndEmitSwitchStatement(node);
92341                 case 245 /* LabeledStatement */:
92342                     return transformAndEmitLabeledStatement(node);
92343                 case 246 /* ThrowStatement */:
92344                     return transformAndEmitThrowStatement(node);
92345                 case 247 /* TryStatement */:
92346                     return transformAndEmitTryStatement(node);
92347                 default:
92348                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92349             }
92350         }
92351         function transformAndEmitBlock(node) {
92352             if (containsYield(node)) {
92353                 transformAndEmitStatements(node.statements);
92354             }
92355             else {
92356                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92357             }
92358         }
92359         function transformAndEmitExpressionStatement(node) {
92360             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92361         }
92362         function transformAndEmitVariableDeclarationList(node) {
92363             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
92364                 var variable = _a[_i];
92365                 var name = factory.cloneNode(variable.name);
92366                 ts.setCommentRange(name, variable.name);
92367                 hoistVariableDeclaration(name);
92368             }
92369             var variables = ts.getInitializedVariables(node);
92370             var numVariables = variables.length;
92371             var variablesWritten = 0;
92372             var pendingExpressions = [];
92373             while (variablesWritten < numVariables) {
92374                 for (var i = variablesWritten; i < numVariables; i++) {
92375                     var variable = variables[i];
92376                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
92377                         break;
92378                     }
92379                     pendingExpressions.push(transformInitializedVariable(variable));
92380                 }
92381                 if (pendingExpressions.length) {
92382                     emitStatement(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
92383                     variablesWritten += pendingExpressions.length;
92384                     pendingExpressions = [];
92385                 }
92386             }
92387             return undefined;
92388         }
92389         function transformInitializedVariable(node) {
92390             return ts.setSourceMapRange(factory.createAssignment(ts.setSourceMapRange(factory.cloneNode(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
92391         }
92392         function transformAndEmitIfStatement(node) {
92393             if (containsYield(node)) {
92394                 // [source]
92395                 //      if (x)
92396                 //          /*thenStatement*/
92397                 //      else
92398                 //          /*elseStatement*/
92399                 //
92400                 // [intermediate]
92401                 //  .brfalse elseLabel, (x)
92402                 //      /*thenStatement*/
92403                 //  .br endLabel
92404                 //  .mark elseLabel
92405                 //      /*elseStatement*/
92406                 //  .mark endLabel
92407                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
92408                     var endLabel = defineLabel();
92409                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
92410                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
92411                     transformAndEmitEmbeddedStatement(node.thenStatement);
92412                     if (node.elseStatement) {
92413                         emitBreak(endLabel);
92414                         markLabel(elseLabel);
92415                         transformAndEmitEmbeddedStatement(node.elseStatement);
92416                     }
92417                     markLabel(endLabel);
92418                 }
92419                 else {
92420                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92421                 }
92422             }
92423             else {
92424                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92425             }
92426         }
92427         function transformAndEmitDoStatement(node) {
92428             if (containsYield(node)) {
92429                 // [source]
92430                 //      do {
92431                 //          /*body*/
92432                 //      }
92433                 //      while (i < 10);
92434                 //
92435                 // [intermediate]
92436                 //  .loop conditionLabel, endLabel
92437                 //  .mark loopLabel
92438                 //      /*body*/
92439                 //  .mark conditionLabel
92440                 //  .brtrue loopLabel, (i < 10)
92441                 //  .endloop
92442                 //  .mark endLabel
92443                 var conditionLabel = defineLabel();
92444                 var loopLabel = defineLabel();
92445                 beginLoopBlock(/*continueLabel*/ conditionLabel);
92446                 markLabel(loopLabel);
92447                 transformAndEmitEmbeddedStatement(node.statement);
92448                 markLabel(conditionLabel);
92449                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
92450                 endLoopBlock();
92451             }
92452             else {
92453                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92454             }
92455         }
92456         function visitDoStatement(node) {
92457             if (inStatementContainingYield) {
92458                 beginScriptLoopBlock();
92459                 node = ts.visitEachChild(node, visitor, context);
92460                 endLoopBlock();
92461                 return node;
92462             }
92463             else {
92464                 return ts.visitEachChild(node, visitor, context);
92465             }
92466         }
92467         function transformAndEmitWhileStatement(node) {
92468             if (containsYield(node)) {
92469                 // [source]
92470                 //      while (i < 10) {
92471                 //          /*body*/
92472                 //      }
92473                 //
92474                 // [intermediate]
92475                 //  .loop loopLabel, endLabel
92476                 //  .mark loopLabel
92477                 //  .brfalse endLabel, (i < 10)
92478                 //      /*body*/
92479                 //  .br loopLabel
92480                 //  .endloop
92481                 //  .mark endLabel
92482                 var loopLabel = defineLabel();
92483                 var endLabel = beginLoopBlock(loopLabel);
92484                 markLabel(loopLabel);
92485                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
92486                 transformAndEmitEmbeddedStatement(node.statement);
92487                 emitBreak(loopLabel);
92488                 endLoopBlock();
92489             }
92490             else {
92491                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92492             }
92493         }
92494         function visitWhileStatement(node) {
92495             if (inStatementContainingYield) {
92496                 beginScriptLoopBlock();
92497                 node = ts.visitEachChild(node, visitor, context);
92498                 endLoopBlock();
92499                 return node;
92500             }
92501             else {
92502                 return ts.visitEachChild(node, visitor, context);
92503             }
92504         }
92505         function transformAndEmitForStatement(node) {
92506             if (containsYield(node)) {
92507                 // [source]
92508                 //      for (var i = 0; i < 10; i++) {
92509                 //          /*body*/
92510                 //      }
92511                 //
92512                 // [intermediate]
92513                 //  .local i
92514                 //      i = 0;
92515                 //  .loop incrementLabel, endLoopLabel
92516                 //  .mark conditionLabel
92517                 //  .brfalse endLoopLabel, (i < 10)
92518                 //      /*body*/
92519                 //  .mark incrementLabel
92520                 //      i++;
92521                 //  .br conditionLabel
92522                 //  .endloop
92523                 //  .mark endLoopLabel
92524                 var conditionLabel = defineLabel();
92525                 var incrementLabel = defineLabel();
92526                 var endLabel = beginLoopBlock(incrementLabel);
92527                 if (node.initializer) {
92528                     var initializer = node.initializer;
92529                     if (ts.isVariableDeclarationList(initializer)) {
92530                         transformAndEmitVariableDeclarationList(initializer);
92531                     }
92532                     else {
92533                         emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
92534                     }
92535                 }
92536                 markLabel(conditionLabel);
92537                 if (node.condition) {
92538                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
92539                 }
92540                 transformAndEmitEmbeddedStatement(node.statement);
92541                 markLabel(incrementLabel);
92542                 if (node.incrementor) {
92543                     emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
92544                 }
92545                 emitBreak(conditionLabel);
92546                 endLoopBlock();
92547             }
92548             else {
92549                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92550             }
92551         }
92552         function visitForStatement(node) {
92553             if (inStatementContainingYield) {
92554                 beginScriptLoopBlock();
92555             }
92556             var initializer = node.initializer;
92557             if (initializer && ts.isVariableDeclarationList(initializer)) {
92558                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
92559                     var variable = _a[_i];
92560                     hoistVariableDeclaration(variable.name);
92561                 }
92562                 var variables = ts.getInitializedVariables(initializer);
92563                 node = factory.updateForStatement(node, variables.length > 0
92564                     ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable))
92565                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
92566             }
92567             else {
92568                 node = ts.visitEachChild(node, visitor, context);
92569             }
92570             if (inStatementContainingYield) {
92571                 endLoopBlock();
92572             }
92573             return node;
92574         }
92575         function transformAndEmitForInStatement(node) {
92576             // TODO(rbuckton): Source map locations
92577             if (containsYield(node)) {
92578                 // [source]
92579                 //      for (var p in o) {
92580                 //          /*body*/
92581                 //      }
92582                 //
92583                 // [intermediate]
92584                 //  .local _a, _b, _i
92585                 //      _a = [];
92586                 //      for (_b in o) _a.push(_b);
92587                 //      _i = 0;
92588                 //  .loop incrementLabel, endLoopLabel
92589                 //  .mark conditionLabel
92590                 //  .brfalse endLoopLabel, (_i < _a.length)
92591                 //      p = _a[_i];
92592                 //      /*body*/
92593                 //  .mark incrementLabel
92594                 //      _b++;
92595                 //  .br conditionLabel
92596                 //  .endloop
92597                 //  .mark endLoopLabel
92598                 var keysArray = declareLocal(); // _a
92599                 var key = declareLocal(); // _b
92600                 var keysIndex = factory.createLoopVariable(); // _i
92601                 var initializer = node.initializer;
92602                 hoistVariableDeclaration(keysIndex);
92603                 emitAssignment(keysArray, factory.createArrayLiteralExpression());
92604                 emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), 
92605                 /*typeArguments*/ undefined, [key]))));
92606                 emitAssignment(keysIndex, factory.createNumericLiteral(0));
92607                 var conditionLabel = defineLabel();
92608                 var incrementLabel = defineLabel();
92609                 var endLabel = beginLoopBlock(incrementLabel);
92610                 markLabel(conditionLabel);
92611                 emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length")));
92612                 var variable = void 0;
92613                 if (ts.isVariableDeclarationList(initializer)) {
92614                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
92615                         var variable_1 = _a[_i];
92616                         hoistVariableDeclaration(variable_1.name);
92617                     }
92618                     variable = factory.cloneNode(initializer.declarations[0].name);
92619                 }
92620                 else {
92621                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
92622                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
92623                 }
92624                 emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex));
92625                 transformAndEmitEmbeddedStatement(node.statement);
92626                 markLabel(incrementLabel);
92627                 emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex)));
92628                 emitBreak(conditionLabel);
92629                 endLoopBlock();
92630             }
92631             else {
92632                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92633             }
92634         }
92635         function visitForInStatement(node) {
92636             // [source]
92637             //      for (var x in a) {
92638             //          /*body*/
92639             //      }
92640             //
92641             // [intermediate]
92642             //  .local x
92643             //  .loop
92644             //      for (x in a) {
92645             //          /*body*/
92646             //      }
92647             //  .endloop
92648             if (inStatementContainingYield) {
92649                 beginScriptLoopBlock();
92650             }
92651             var initializer = node.initializer;
92652             if (ts.isVariableDeclarationList(initializer)) {
92653                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
92654                     var variable = _a[_i];
92655                     hoistVariableDeclaration(variable.name);
92656                 }
92657                 node = factory.updateForInStatement(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
92658             }
92659             else {
92660                 node = ts.visitEachChild(node, visitor, context);
92661             }
92662             if (inStatementContainingYield) {
92663                 endLoopBlock();
92664             }
92665             return node;
92666         }
92667         function transformAndEmitContinueStatement(node) {
92668             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
92669             if (label > 0) {
92670                 emitBreak(label, /*location*/ node);
92671             }
92672             else {
92673                 // invalid continue without a containing loop. Leave the node as is, per #17875.
92674                 emitStatement(node);
92675             }
92676         }
92677         function visitContinueStatement(node) {
92678             if (inStatementContainingYield) {
92679                 var label = findContinueTarget(node.label && ts.idText(node.label));
92680                 if (label > 0) {
92681                     return createInlineBreak(label, /*location*/ node);
92682                 }
92683             }
92684             return ts.visitEachChild(node, visitor, context);
92685         }
92686         function transformAndEmitBreakStatement(node) {
92687             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
92688             if (label > 0) {
92689                 emitBreak(label, /*location*/ node);
92690             }
92691             else {
92692                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
92693                 emitStatement(node);
92694             }
92695         }
92696         function visitBreakStatement(node) {
92697             if (inStatementContainingYield) {
92698                 var label = findBreakTarget(node.label && ts.idText(node.label));
92699                 if (label > 0) {
92700                     return createInlineBreak(label, /*location*/ node);
92701                 }
92702             }
92703             return ts.visitEachChild(node, visitor, context);
92704         }
92705         function transformAndEmitReturnStatement(node) {
92706             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
92707             /*location*/ node);
92708         }
92709         function visitReturnStatement(node) {
92710             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
92711             /*location*/ node);
92712         }
92713         function transformAndEmitWithStatement(node) {
92714             if (containsYield(node)) {
92715                 // [source]
92716                 //      with (x) {
92717                 //          /*body*/
92718                 //      }
92719                 //
92720                 // [intermediate]
92721                 //  .with (x)
92722                 //      /*body*/
92723                 //  .endwith
92724                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
92725                 transformAndEmitEmbeddedStatement(node.statement);
92726                 endWithBlock();
92727             }
92728             else {
92729                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92730             }
92731         }
92732         function transformAndEmitSwitchStatement(node) {
92733             if (containsYield(node.caseBlock)) {
92734                 // [source]
92735                 //      switch (x) {
92736                 //          case a:
92737                 //              /*caseStatements*/
92738                 //          case b:
92739                 //              /*caseStatements*/
92740                 //          default:
92741                 //              /*defaultStatements*/
92742                 //      }
92743                 //
92744                 // [intermediate]
92745                 //  .local _a
92746                 //  .switch endLabel
92747                 //      _a = x;
92748                 //      switch (_a) {
92749                 //          case a:
92750                 //  .br clauseLabels[0]
92751                 //      }
92752                 //      switch (_a) {
92753                 //          case b:
92754                 //  .br clauseLabels[1]
92755                 //      }
92756                 //  .br clauseLabels[2]
92757                 //  .mark clauseLabels[0]
92758                 //      /*caseStatements*/
92759                 //  .mark clauseLabels[1]
92760                 //      /*caseStatements*/
92761                 //  .mark clauseLabels[2]
92762                 //      /*caseStatements*/
92763                 //  .endswitch
92764                 //  .mark endLabel
92765                 var caseBlock = node.caseBlock;
92766                 var numClauses = caseBlock.clauses.length;
92767                 var endLabel = beginSwitchBlock();
92768                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
92769                 // Create labels for each clause and find the index of the first default clause.
92770                 var clauseLabels = [];
92771                 var defaultClauseIndex = -1;
92772                 for (var i = 0; i < numClauses; i++) {
92773                     var clause = caseBlock.clauses[i];
92774                     clauseLabels.push(defineLabel());
92775                     if (clause.kind === 285 /* DefaultClause */ && defaultClauseIndex === -1) {
92776                         defaultClauseIndex = i;
92777                     }
92778                 }
92779                 // Emit switch statements for each run of case clauses either from the first case
92780                 // clause or the next case clause with a `yield` in its expression, up to the next
92781                 // case clause with a `yield` in its expression.
92782                 var clausesWritten = 0;
92783                 var pendingClauses = [];
92784                 while (clausesWritten < numClauses) {
92785                     var defaultClausesSkipped = 0;
92786                     for (var i = clausesWritten; i < numClauses; i++) {
92787                         var clause = caseBlock.clauses[i];
92788                         if (clause.kind === 284 /* CaseClause */) {
92789                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
92790                                 break;
92791                             }
92792                             pendingClauses.push(factory.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
92793                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
92794                             ]));
92795                         }
92796                         else {
92797                             defaultClausesSkipped++;
92798                         }
92799                     }
92800                     if (pendingClauses.length) {
92801                         emitStatement(factory.createSwitchStatement(expression, factory.createCaseBlock(pendingClauses)));
92802                         clausesWritten += pendingClauses.length;
92803                         pendingClauses = [];
92804                     }
92805                     if (defaultClausesSkipped > 0) {
92806                         clausesWritten += defaultClausesSkipped;
92807                         defaultClausesSkipped = 0;
92808                     }
92809                 }
92810                 if (defaultClauseIndex >= 0) {
92811                     emitBreak(clauseLabels[defaultClauseIndex]);
92812                 }
92813                 else {
92814                     emitBreak(endLabel);
92815                 }
92816                 for (var i = 0; i < numClauses; i++) {
92817                     markLabel(clauseLabels[i]);
92818                     transformAndEmitStatements(caseBlock.clauses[i].statements);
92819                 }
92820                 endSwitchBlock();
92821             }
92822             else {
92823                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92824             }
92825         }
92826         function visitSwitchStatement(node) {
92827             if (inStatementContainingYield) {
92828                 beginScriptSwitchBlock();
92829             }
92830             node = ts.visitEachChild(node, visitor, context);
92831             if (inStatementContainingYield) {
92832                 endSwitchBlock();
92833             }
92834             return node;
92835         }
92836         function transformAndEmitLabeledStatement(node) {
92837             if (containsYield(node)) {
92838                 // [source]
92839                 //      x: {
92840                 //          /*body*/
92841                 //      }
92842                 //
92843                 // [intermediate]
92844                 //  .labeled "x", endLabel
92845                 //      /*body*/
92846                 //  .endlabeled
92847                 //  .mark endLabel
92848                 beginLabeledBlock(ts.idText(node.label));
92849                 transformAndEmitEmbeddedStatement(node.statement);
92850                 endLabeledBlock();
92851             }
92852             else {
92853                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92854             }
92855         }
92856         function visitLabeledStatement(node) {
92857             if (inStatementContainingYield) {
92858                 beginScriptLabeledBlock(ts.idText(node.label));
92859             }
92860             node = ts.visitEachChild(node, visitor, context);
92861             if (inStatementContainingYield) {
92862                 endLabeledBlock();
92863             }
92864             return node;
92865         }
92866         function transformAndEmitThrowStatement(node) {
92867             var _a;
92868             // TODO(rbuckton): `expression` should be required on `throw`.
92869             emitThrow(ts.visitNode((_a = node.expression) !== null && _a !== void 0 ? _a : factory.createVoidZero(), visitor, ts.isExpression), 
92870             /*location*/ node);
92871         }
92872         function transformAndEmitTryStatement(node) {
92873             if (containsYield(node)) {
92874                 // [source]
92875                 //      try {
92876                 //          /*tryBlock*/
92877                 //      }
92878                 //      catch (e) {
92879                 //          /*catchBlock*/
92880                 //      }
92881                 //      finally {
92882                 //          /*finallyBlock*/
92883                 //      }
92884                 //
92885                 // [intermediate]
92886                 //  .local _a
92887                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
92888                 //  .mark tryLabel
92889                 //  .nop
92890                 //      /*tryBlock*/
92891                 //  .br endLabel
92892                 //  .catch
92893                 //  .mark catchLabel
92894                 //      _a = %error%;
92895                 //      /*catchBlock*/
92896                 //  .br endLabel
92897                 //  .finally
92898                 //  .mark finallyLabel
92899                 //      /*finallyBlock*/
92900                 //  .endfinally
92901                 //  .endtry
92902                 //  .mark endLabel
92903                 beginExceptionBlock();
92904                 transformAndEmitEmbeddedStatement(node.tryBlock);
92905                 if (node.catchClause) {
92906                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
92907                     transformAndEmitEmbeddedStatement(node.catchClause.block);
92908                 }
92909                 if (node.finallyBlock) {
92910                     beginFinallyBlock();
92911                     transformAndEmitEmbeddedStatement(node.finallyBlock);
92912                 }
92913                 endExceptionBlock();
92914             }
92915             else {
92916                 emitStatement(ts.visitEachChild(node, visitor, context));
92917             }
92918         }
92919         function containsYield(node) {
92920             return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
92921         }
92922         function countInitialNodesWithoutYield(nodes) {
92923             var numNodes = nodes.length;
92924             for (var i = 0; i < numNodes; i++) {
92925                 if (containsYield(nodes[i])) {
92926                     return i;
92927                 }
92928             }
92929             return -1;
92930         }
92931         function onSubstituteNode(hint, node) {
92932             node = previousOnSubstituteNode(hint, node);
92933             if (hint === 1 /* Expression */) {
92934                 return substituteExpression(node);
92935             }
92936             return node;
92937         }
92938         function substituteExpression(node) {
92939             if (ts.isIdentifier(node)) {
92940                 return substituteExpressionIdentifier(node);
92941             }
92942             return node;
92943         }
92944         function substituteExpressionIdentifier(node) {
92945             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
92946                 var original = ts.getOriginalNode(node);
92947                 if (ts.isIdentifier(original) && original.parent) {
92948                     var declaration = resolver.getReferencedValueDeclaration(original);
92949                     if (declaration) {
92950                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
92951                         if (name) {
92952                             // TODO(rbuckton): Does this need to be parented?
92953                             var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
92954                             ts.setSourceMapRange(clone_5, node);
92955                             ts.setCommentRange(clone_5, node);
92956                             return clone_5;
92957                         }
92958                     }
92959                 }
92960             }
92961             return node;
92962         }
92963         function cacheExpression(node) {
92964             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
92965                 return node;
92966             }
92967             var temp = factory.createTempVariable(hoistVariableDeclaration);
92968             emitAssignment(temp, node, /*location*/ node);
92969             return temp;
92970         }
92971         function declareLocal(name) {
92972             var temp = name
92973                 ? factory.createUniqueName(name)
92974                 : factory.createTempVariable(/*recordTempVariable*/ undefined);
92975             hoistVariableDeclaration(temp);
92976             return temp;
92977         }
92978         /**
92979          * Defines a label, uses as the target of a Break operation.
92980          */
92981         function defineLabel() {
92982             if (!labelOffsets) {
92983                 labelOffsets = [];
92984             }
92985             var label = nextLabelId;
92986             nextLabelId++;
92987             labelOffsets[label] = -1;
92988             return label;
92989         }
92990         /**
92991          * Marks the current operation with the specified label.
92992          */
92993         function markLabel(label) {
92994             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
92995             labelOffsets[label] = operations ? operations.length : 0;
92996         }
92997         /**
92998          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
92999          *
93000          * @param block Information about the block.
93001          */
93002         function beginBlock(block) {
93003             if (!blocks) {
93004                 blocks = [];
93005                 blockActions = [];
93006                 blockOffsets = [];
93007                 blockStack = [];
93008             }
93009             var index = blockActions.length;
93010             blockActions[index] = 0 /* Open */;
93011             blockOffsets[index] = operations ? operations.length : 0;
93012             blocks[index] = block;
93013             blockStack.push(block);
93014             return index;
93015         }
93016         /**
93017          * Ends the current block operation.
93018          */
93019         function endBlock() {
93020             var block = peekBlock();
93021             if (block === undefined)
93022                 return ts.Debug.fail("beginBlock was never called.");
93023             var index = blockActions.length;
93024             blockActions[index] = 1 /* Close */;
93025             blockOffsets[index] = operations ? operations.length : 0;
93026             blocks[index] = block;
93027             blockStack.pop();
93028             return block;
93029         }
93030         /**
93031          * Gets the current open block.
93032          */
93033         function peekBlock() {
93034             return ts.lastOrUndefined(blockStack);
93035         }
93036         /**
93037          * Gets the kind of the current open block.
93038          */
93039         function peekBlockKind() {
93040             var block = peekBlock();
93041             return block && block.kind;
93042         }
93043         /**
93044          * Begins a code block for a generated `with` statement.
93045          *
93046          * @param expression An identifier representing expression for the `with` block.
93047          */
93048         function beginWithBlock(expression) {
93049             var startLabel = defineLabel();
93050             var endLabel = defineLabel();
93051             markLabel(startLabel);
93052             beginBlock({
93053                 kind: 1 /* With */,
93054                 expression: expression,
93055                 startLabel: startLabel,
93056                 endLabel: endLabel
93057             });
93058         }
93059         /**
93060          * Ends a code block for a generated `with` statement.
93061          */
93062         function endWithBlock() {
93063             ts.Debug.assert(peekBlockKind() === 1 /* With */);
93064             var block = endBlock();
93065             markLabel(block.endLabel);
93066         }
93067         /**
93068          * Begins a code block for a generated `try` statement.
93069          */
93070         function beginExceptionBlock() {
93071             var startLabel = defineLabel();
93072             var endLabel = defineLabel();
93073             markLabel(startLabel);
93074             beginBlock({
93075                 kind: 0 /* Exception */,
93076                 state: 0 /* Try */,
93077                 startLabel: startLabel,
93078                 endLabel: endLabel
93079             });
93080             emitNop();
93081             return endLabel;
93082         }
93083         /**
93084          * Enters the `catch` clause of a generated `try` statement.
93085          *
93086          * @param variable The catch variable.
93087          */
93088         function beginCatchBlock(variable) {
93089             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
93090             // generated identifiers should already be unique within a file
93091             var name;
93092             if (ts.isGeneratedIdentifier(variable.name)) {
93093                 name = variable.name;
93094                 hoistVariableDeclaration(variable.name);
93095             }
93096             else {
93097                 var text = ts.idText(variable.name);
93098                 name = declareLocal(text);
93099                 if (!renamedCatchVariables) {
93100                     renamedCatchVariables = new ts.Map();
93101                     renamedCatchVariableDeclarations = [];
93102                     context.enableSubstitution(78 /* Identifier */);
93103                 }
93104                 renamedCatchVariables.set(text, true);
93105                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
93106             }
93107             var exception = peekBlock();
93108             ts.Debug.assert(exception.state < 1 /* Catch */);
93109             var endLabel = exception.endLabel;
93110             emitBreak(endLabel);
93111             var catchLabel = defineLabel();
93112             markLabel(catchLabel);
93113             exception.state = 1 /* Catch */;
93114             exception.catchVariable = name;
93115             exception.catchLabel = catchLabel;
93116             emitAssignment(name, factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), /*typeArguments*/ undefined, []));
93117             emitNop();
93118         }
93119         /**
93120          * Enters the `finally` block of a generated `try` statement.
93121          */
93122         function beginFinallyBlock() {
93123             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
93124             var exception = peekBlock();
93125             ts.Debug.assert(exception.state < 2 /* Finally */);
93126             var endLabel = exception.endLabel;
93127             emitBreak(endLabel);
93128             var finallyLabel = defineLabel();
93129             markLabel(finallyLabel);
93130             exception.state = 2 /* Finally */;
93131             exception.finallyLabel = finallyLabel;
93132         }
93133         /**
93134          * Ends the code block for a generated `try` statement.
93135          */
93136         function endExceptionBlock() {
93137             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
93138             var exception = endBlock();
93139             var state = exception.state;
93140             if (state < 2 /* Finally */) {
93141                 emitBreak(exception.endLabel);
93142             }
93143             else {
93144                 emitEndfinally();
93145             }
93146             markLabel(exception.endLabel);
93147             emitNop();
93148             exception.state = 3 /* Done */;
93149         }
93150         /**
93151          * Begins a code block that supports `break` or `continue` statements that are defined in
93152          * the source tree and not from generated code.
93153          *
93154          * @param labelText Names from containing labeled statements.
93155          */
93156         function beginScriptLoopBlock() {
93157             beginBlock({
93158                 kind: 3 /* Loop */,
93159                 isScript: true,
93160                 breakLabel: -1,
93161                 continueLabel: -1
93162             });
93163         }
93164         /**
93165          * Begins a code block that supports `break` or `continue` statements that are defined in
93166          * generated code. Returns a label used to mark the operation to which to jump when a
93167          * `break` statement targets this block.
93168          *
93169          * @param continueLabel A Label used to mark the operation to which to jump when a
93170          *                      `continue` statement targets this block.
93171          */
93172         function beginLoopBlock(continueLabel) {
93173             var breakLabel = defineLabel();
93174             beginBlock({
93175                 kind: 3 /* Loop */,
93176                 isScript: false,
93177                 breakLabel: breakLabel,
93178                 continueLabel: continueLabel,
93179             });
93180             return breakLabel;
93181         }
93182         /**
93183          * Ends a code block that supports `break` or `continue` statements that are defined in
93184          * generated code or in the source tree.
93185          */
93186         function endLoopBlock() {
93187             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
93188             var block = endBlock();
93189             var breakLabel = block.breakLabel;
93190             if (!block.isScript) {
93191                 markLabel(breakLabel);
93192             }
93193         }
93194         /**
93195          * Begins a code block that supports `break` statements that are defined in the source
93196          * tree and not from generated code.
93197          *
93198          */
93199         function beginScriptSwitchBlock() {
93200             beginBlock({
93201                 kind: 2 /* Switch */,
93202                 isScript: true,
93203                 breakLabel: -1
93204             });
93205         }
93206         /**
93207          * Begins a code block that supports `break` statements that are defined in generated code.
93208          * Returns a label used to mark the operation to which to jump when a `break` statement
93209          * targets this block.
93210          */
93211         function beginSwitchBlock() {
93212             var breakLabel = defineLabel();
93213             beginBlock({
93214                 kind: 2 /* Switch */,
93215                 isScript: false,
93216                 breakLabel: breakLabel,
93217             });
93218             return breakLabel;
93219         }
93220         /**
93221          * Ends a code block that supports `break` statements that are defined in generated code.
93222          */
93223         function endSwitchBlock() {
93224             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
93225             var block = endBlock();
93226             var breakLabel = block.breakLabel;
93227             if (!block.isScript) {
93228                 markLabel(breakLabel);
93229             }
93230         }
93231         function beginScriptLabeledBlock(labelText) {
93232             beginBlock({
93233                 kind: 4 /* Labeled */,
93234                 isScript: true,
93235                 labelText: labelText,
93236                 breakLabel: -1
93237             });
93238         }
93239         function beginLabeledBlock(labelText) {
93240             var breakLabel = defineLabel();
93241             beginBlock({
93242                 kind: 4 /* Labeled */,
93243                 isScript: false,
93244                 labelText: labelText,
93245                 breakLabel: breakLabel
93246             });
93247         }
93248         function endLabeledBlock() {
93249             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
93250             var block = endBlock();
93251             if (!block.isScript) {
93252                 markLabel(block.breakLabel);
93253             }
93254         }
93255         /**
93256          * Indicates whether the provided block supports `break` statements.
93257          *
93258          * @param block A code block.
93259          */
93260         function supportsUnlabeledBreak(block) {
93261             return block.kind === 2 /* Switch */
93262                 || block.kind === 3 /* Loop */;
93263         }
93264         /**
93265          * Indicates whether the provided block supports `break` statements with labels.
93266          *
93267          * @param block A code block.
93268          */
93269         function supportsLabeledBreakOrContinue(block) {
93270             return block.kind === 4 /* Labeled */;
93271         }
93272         /**
93273          * Indicates whether the provided block supports `continue` statements.
93274          *
93275          * @param block A code block.
93276          */
93277         function supportsUnlabeledContinue(block) {
93278             return block.kind === 3 /* Loop */;
93279         }
93280         function hasImmediateContainingLabeledBlock(labelText, start) {
93281             for (var j = start; j >= 0; j--) {
93282                 var containingBlock = blockStack[j];
93283                 if (supportsLabeledBreakOrContinue(containingBlock)) {
93284                     if (containingBlock.labelText === labelText) {
93285                         return true;
93286                     }
93287                 }
93288                 else {
93289                     break;
93290                 }
93291             }
93292             return false;
93293         }
93294         /**
93295          * Finds the label that is the target for a `break` statement.
93296          *
93297          * @param labelText An optional name of a containing labeled statement.
93298          */
93299         function findBreakTarget(labelText) {
93300             if (blockStack) {
93301                 if (labelText) {
93302                     for (var i = blockStack.length - 1; i >= 0; i--) {
93303                         var block = blockStack[i];
93304                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
93305                             return block.breakLabel;
93306                         }
93307                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
93308                             return block.breakLabel;
93309                         }
93310                     }
93311                 }
93312                 else {
93313                     for (var i = blockStack.length - 1; i >= 0; i--) {
93314                         var block = blockStack[i];
93315                         if (supportsUnlabeledBreak(block)) {
93316                             return block.breakLabel;
93317                         }
93318                     }
93319                 }
93320             }
93321             return 0;
93322         }
93323         /**
93324          * Finds the label that is the target for a `continue` statement.
93325          *
93326          * @param labelText An optional name of a containing labeled statement.
93327          */
93328         function findContinueTarget(labelText) {
93329             if (blockStack) {
93330                 if (labelText) {
93331                     for (var i = blockStack.length - 1; i >= 0; i--) {
93332                         var block = blockStack[i];
93333                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
93334                             return block.continueLabel;
93335                         }
93336                     }
93337                 }
93338                 else {
93339                     for (var i = blockStack.length - 1; i >= 0; i--) {
93340                         var block = blockStack[i];
93341                         if (supportsUnlabeledContinue(block)) {
93342                             return block.continueLabel;
93343                         }
93344                     }
93345                 }
93346             }
93347             return 0;
93348         }
93349         /**
93350          * Creates an expression that can be used to indicate the value for a label.
93351          *
93352          * @param label A label.
93353          */
93354         function createLabel(label) {
93355             if (label !== undefined && label > 0) {
93356                 if (labelExpressions === undefined) {
93357                     labelExpressions = [];
93358                 }
93359                 var expression = factory.createNumericLiteral(-1);
93360                 if (labelExpressions[label] === undefined) {
93361                     labelExpressions[label] = [expression];
93362                 }
93363                 else {
93364                     labelExpressions[label].push(expression);
93365                 }
93366                 return expression;
93367             }
93368             return factory.createOmittedExpression();
93369         }
93370         /**
93371          * Creates a numeric literal for the provided instruction.
93372          */
93373         function createInstruction(instruction) {
93374             var literal = factory.createNumericLiteral(instruction);
93375             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
93376             return literal;
93377         }
93378         /**
93379          * Creates a statement that can be used indicate a Break operation to the provided label.
93380          *
93381          * @param label A label.
93382          * @param location An optional source map location for the statement.
93383          */
93384         function createInlineBreak(label, location) {
93385             ts.Debug.assertLessThan(0, label, "Invalid label");
93386             return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93387                 createInstruction(3 /* Break */),
93388                 createLabel(label)
93389             ])), location);
93390         }
93391         /**
93392          * Creates a statement that can be used indicate a Return operation.
93393          *
93394          * @param expression The expression for the return statement.
93395          * @param location An optional source map location for the statement.
93396          */
93397         function createInlineReturn(expression, location) {
93398             return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
93399                 ? [createInstruction(2 /* Return */), expression]
93400                 : [createInstruction(2 /* Return */)])), location);
93401         }
93402         /**
93403          * Creates an expression that can be used to resume from a Yield operation.
93404          */
93405         function createGeneratorResume(location) {
93406             return ts.setTextRange(factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), 
93407             /*typeArguments*/ undefined, []), location);
93408         }
93409         /**
93410          * Emits an empty instruction.
93411          */
93412         function emitNop() {
93413             emitWorker(0 /* Nop */);
93414         }
93415         /**
93416          * Emits a Statement.
93417          *
93418          * @param node A statement.
93419          */
93420         function emitStatement(node) {
93421             if (node) {
93422                 emitWorker(1 /* Statement */, [node]);
93423             }
93424             else {
93425                 emitNop();
93426             }
93427         }
93428         /**
93429          * Emits an Assignment operation.
93430          *
93431          * @param left The left-hand side of the assignment.
93432          * @param right The right-hand side of the assignment.
93433          * @param location An optional source map location for the assignment.
93434          */
93435         function emitAssignment(left, right, location) {
93436             emitWorker(2 /* Assign */, [left, right], location);
93437         }
93438         /**
93439          * Emits a Break operation to the specified label.
93440          *
93441          * @param label A label.
93442          * @param location An optional source map location for the assignment.
93443          */
93444         function emitBreak(label, location) {
93445             emitWorker(3 /* Break */, [label], location);
93446         }
93447         /**
93448          * Emits a Break operation to the specified label when a condition evaluates to a truthy
93449          * value at runtime.
93450          *
93451          * @param label A label.
93452          * @param condition The condition.
93453          * @param location An optional source map location for the assignment.
93454          */
93455         function emitBreakWhenTrue(label, condition, location) {
93456             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
93457         }
93458         /**
93459          * Emits a Break to the specified label when a condition evaluates to a falsey value at
93460          * runtime.
93461          *
93462          * @param label A label.
93463          * @param condition The condition.
93464          * @param location An optional source map location for the assignment.
93465          */
93466         function emitBreakWhenFalse(label, condition, location) {
93467             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
93468         }
93469         /**
93470          * Emits a YieldStar operation for the provided expression.
93471          *
93472          * @param expression An optional value for the yield operation.
93473          * @param location An optional source map location for the assignment.
93474          */
93475         function emitYieldStar(expression, location) {
93476             emitWorker(7 /* YieldStar */, [expression], location);
93477         }
93478         /**
93479          * Emits a Yield operation for the provided expression.
93480          *
93481          * @param expression An optional value for the yield operation.
93482          * @param location An optional source map location for the assignment.
93483          */
93484         function emitYield(expression, location) {
93485             emitWorker(6 /* Yield */, [expression], location);
93486         }
93487         /**
93488          * Emits a Return operation for the provided expression.
93489          *
93490          * @param expression An optional value for the operation.
93491          * @param location An optional source map location for the assignment.
93492          */
93493         function emitReturn(expression, location) {
93494             emitWorker(8 /* Return */, [expression], location);
93495         }
93496         /**
93497          * Emits a Throw operation for the provided expression.
93498          *
93499          * @param expression A value for the operation.
93500          * @param location An optional source map location for the assignment.
93501          */
93502         function emitThrow(expression, location) {
93503             emitWorker(9 /* Throw */, [expression], location);
93504         }
93505         /**
93506          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
93507          */
93508         function emitEndfinally() {
93509             emitWorker(10 /* Endfinally */);
93510         }
93511         /**
93512          * Emits an operation.
93513          *
93514          * @param code The OpCode for the operation.
93515          * @param args The optional arguments for the operation.
93516          */
93517         function emitWorker(code, args, location) {
93518             if (operations === undefined) {
93519                 operations = [];
93520                 operationArguments = [];
93521                 operationLocations = [];
93522             }
93523             if (labelOffsets === undefined) {
93524                 // mark entry point
93525                 markLabel(defineLabel());
93526             }
93527             var operationIndex = operations.length;
93528             operations[operationIndex] = code;
93529             operationArguments[operationIndex] = args;
93530             operationLocations[operationIndex] = location;
93531         }
93532         /**
93533          * Builds the generator function body.
93534          */
93535         function build() {
93536             blockIndex = 0;
93537             labelNumber = 0;
93538             labelNumbers = undefined;
93539             lastOperationWasAbrupt = false;
93540             lastOperationWasCompletion = false;
93541             clauses = undefined;
93542             statements = undefined;
93543             exceptionBlockStack = undefined;
93544             currentExceptionBlock = undefined;
93545             withBlockStack = undefined;
93546             var buildResult = buildStatements();
93547             return emitHelpers().createGeneratorHelper(ts.setEmitFlags(factory.createFunctionExpression(
93548             /*modifiers*/ undefined, 
93549             /*asteriskToken*/ undefined, 
93550             /*name*/ undefined, 
93551             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
93552             /*type*/ undefined, factory.createBlock(buildResult, 
93553             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
93554         }
93555         /**
93556          * Builds the statements for the generator function body.
93557          */
93558         function buildStatements() {
93559             if (operations) {
93560                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
93561                     writeOperation(operationIndex);
93562                 }
93563                 flushFinalLabel(operations.length);
93564             }
93565             else {
93566                 flushFinalLabel(0);
93567             }
93568             if (clauses) {
93569                 var labelExpression = factory.createPropertyAccessExpression(state, "label");
93570                 var switchStatement = factory.createSwitchStatement(labelExpression, factory.createCaseBlock(clauses));
93571                 return [ts.startOnNewLine(switchStatement)];
93572             }
93573             if (statements) {
93574                 return statements;
93575             }
93576             return [];
93577         }
93578         /**
93579          * Flush the current label and advance to a new label.
93580          */
93581         function flushLabel() {
93582             if (!statements) {
93583                 return;
93584             }
93585             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
93586             lastOperationWasAbrupt = false;
93587             lastOperationWasCompletion = false;
93588             labelNumber++;
93589         }
93590         /**
93591          * Flush the final label of the generator function body.
93592          */
93593         function flushFinalLabel(operationIndex) {
93594             if (isFinalLabelReachable(operationIndex)) {
93595                 tryEnterLabel(operationIndex);
93596                 withBlockStack = undefined;
93597                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
93598             }
93599             if (statements && clauses) {
93600                 appendLabel(/*markLabelEnd*/ false);
93601             }
93602             updateLabelExpressions();
93603         }
93604         /**
93605          * Tests whether the final label of the generator function body
93606          * is reachable by user code.
93607          */
93608         function isFinalLabelReachable(operationIndex) {
93609             // if the last operation was *not* a completion (return/throw) then
93610             // the final label is reachable.
93611             if (!lastOperationWasCompletion) {
93612                 return true;
93613             }
93614             // if there are no labels defined or referenced, then the final label is
93615             // not reachable.
93616             if (!labelOffsets || !labelExpressions) {
93617                 return false;
93618             }
93619             // if the label for this offset is referenced, then the final label
93620             // is reachable.
93621             for (var label = 0; label < labelOffsets.length; label++) {
93622                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
93623                     return true;
93624                 }
93625             }
93626             return false;
93627         }
93628         /**
93629          * Appends a case clause for the last label and sets the new label.
93630          *
93631          * @param markLabelEnd Indicates that the transition between labels was a fall-through
93632          *                     from a previous case clause and the change in labels should be
93633          *                     reflected on the `state` object.
93634          */
93635         function appendLabel(markLabelEnd) {
93636             if (!clauses) {
93637                 clauses = [];
93638             }
93639             if (statements) {
93640                 if (withBlockStack) {
93641                     // The previous label was nested inside one or more `with` blocks, so we
93642                     // surround the statements in generated `with` blocks to create the same environment.
93643                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
93644                         var withBlock = withBlockStack[i];
93645                         statements = [factory.createWithStatement(withBlock.expression, factory.createBlock(statements))];
93646                     }
93647                 }
93648                 if (currentExceptionBlock) {
93649                     // The previous label was nested inside of an exception block, so we must
93650                     // indicate entry into a protected region by pushing the label numbers
93651                     // for each block in the protected region.
93652                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
93653                     statements.unshift(factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(state, "trys"), "push"), 
93654                     /*typeArguments*/ undefined, [
93655                         factory.createArrayLiteralExpression([
93656                             createLabel(startLabel),
93657                             createLabel(catchLabel),
93658                             createLabel(finallyLabel),
93659                             createLabel(endLabel)
93660                         ])
93661                     ])));
93662                     currentExceptionBlock = undefined;
93663                 }
93664                 if (markLabelEnd) {
93665                     // The case clause for the last label falls through to this label, so we
93666                     // add an assignment statement to reflect the change in labels.
93667                     statements.push(factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(state, "label"), factory.createNumericLiteral(labelNumber + 1))));
93668                 }
93669             }
93670             clauses.push(factory.createCaseClause(factory.createNumericLiteral(labelNumber), statements || []));
93671             statements = undefined;
93672         }
93673         /**
93674          * Tries to enter into a new label at the current operation index.
93675          */
93676         function tryEnterLabel(operationIndex) {
93677             if (!labelOffsets) {
93678                 return;
93679             }
93680             for (var label = 0; label < labelOffsets.length; label++) {
93681                 if (labelOffsets[label] === operationIndex) {
93682                     flushLabel();
93683                     if (labelNumbers === undefined) {
93684                         labelNumbers = [];
93685                     }
93686                     if (labelNumbers[labelNumber] === undefined) {
93687                         labelNumbers[labelNumber] = [label];
93688                     }
93689                     else {
93690                         labelNumbers[labelNumber].push(label);
93691                     }
93692                 }
93693             }
93694         }
93695         /**
93696          * Updates literal expressions for labels with actual label numbers.
93697          */
93698         function updateLabelExpressions() {
93699             if (labelExpressions !== undefined && labelNumbers !== undefined) {
93700                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
93701                     var labels = labelNumbers[labelNumber_1];
93702                     if (labels !== undefined) {
93703                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
93704                             var label = labels_1[_i];
93705                             var expressions = labelExpressions[label];
93706                             if (expressions !== undefined) {
93707                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
93708                                     var expression = expressions_1[_a];
93709                                     expression.text = String(labelNumber_1);
93710                                 }
93711                             }
93712                         }
93713                     }
93714                 }
93715             }
93716         }
93717         /**
93718          * Tries to enter or leave a code block.
93719          */
93720         function tryEnterOrLeaveBlock(operationIndex) {
93721             if (blocks) {
93722                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
93723                     var block = blocks[blockIndex];
93724                     var blockAction = blockActions[blockIndex];
93725                     switch (block.kind) {
93726                         case 0 /* Exception */:
93727                             if (blockAction === 0 /* Open */) {
93728                                 if (!exceptionBlockStack) {
93729                                     exceptionBlockStack = [];
93730                                 }
93731                                 if (!statements) {
93732                                     statements = [];
93733                                 }
93734                                 exceptionBlockStack.push(currentExceptionBlock);
93735                                 currentExceptionBlock = block;
93736                             }
93737                             else if (blockAction === 1 /* Close */) {
93738                                 currentExceptionBlock = exceptionBlockStack.pop();
93739                             }
93740                             break;
93741                         case 1 /* With */:
93742                             if (blockAction === 0 /* Open */) {
93743                                 if (!withBlockStack) {
93744                                     withBlockStack = [];
93745                                 }
93746                                 withBlockStack.push(block);
93747                             }
93748                             else if (blockAction === 1 /* Close */) {
93749                                 withBlockStack.pop();
93750                             }
93751                             break;
93752                         // default: do nothing
93753                     }
93754                 }
93755             }
93756         }
93757         /**
93758          * Writes an operation as a statement to the current label's statement list.
93759          *
93760          * @param operation The OpCode of the operation
93761          */
93762         function writeOperation(operationIndex) {
93763             tryEnterLabel(operationIndex);
93764             tryEnterOrLeaveBlock(operationIndex);
93765             // early termination, nothing else to process in this label
93766             if (lastOperationWasAbrupt) {
93767                 return;
93768             }
93769             lastOperationWasAbrupt = false;
93770             lastOperationWasCompletion = false;
93771             var opcode = operations[operationIndex];
93772             if (opcode === 0 /* Nop */) {
93773                 return;
93774             }
93775             else if (opcode === 10 /* Endfinally */) {
93776                 return writeEndfinally();
93777             }
93778             var args = operationArguments[operationIndex];
93779             if (opcode === 1 /* Statement */) {
93780                 return writeStatement(args[0]);
93781             }
93782             var location = operationLocations[operationIndex];
93783             switch (opcode) {
93784                 case 2 /* Assign */:
93785                     return writeAssign(args[0], args[1], location);
93786                 case 3 /* Break */:
93787                     return writeBreak(args[0], location);
93788                 case 4 /* BreakWhenTrue */:
93789                     return writeBreakWhenTrue(args[0], args[1], location);
93790                 case 5 /* BreakWhenFalse */:
93791                     return writeBreakWhenFalse(args[0], args[1], location);
93792                 case 6 /* Yield */:
93793                     return writeYield(args[0], location);
93794                 case 7 /* YieldStar */:
93795                     return writeYieldStar(args[0], location);
93796                 case 8 /* Return */:
93797                     return writeReturn(args[0], location);
93798                 case 9 /* Throw */:
93799                     return writeThrow(args[0], location);
93800             }
93801         }
93802         /**
93803          * Writes a statement to the current label's statement list.
93804          *
93805          * @param statement A statement to write.
93806          */
93807         function writeStatement(statement) {
93808             if (statement) {
93809                 if (!statements) {
93810                     statements = [statement];
93811                 }
93812                 else {
93813                     statements.push(statement);
93814                 }
93815             }
93816         }
93817         /**
93818          * Writes an Assign operation to the current label's statement list.
93819          *
93820          * @param left The left-hand side of the assignment.
93821          * @param right The right-hand side of the assignment.
93822          * @param operationLocation The source map location for the operation.
93823          */
93824         function writeAssign(left, right, operationLocation) {
93825             writeStatement(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(left, right)), operationLocation));
93826         }
93827         /**
93828          * Writes a Throw operation to the current label's statement list.
93829          *
93830          * @param expression The value to throw.
93831          * @param operationLocation The source map location for the operation.
93832          */
93833         function writeThrow(expression, operationLocation) {
93834             lastOperationWasAbrupt = true;
93835             lastOperationWasCompletion = true;
93836             writeStatement(ts.setTextRange(factory.createThrowStatement(expression), operationLocation));
93837         }
93838         /**
93839          * Writes a Return operation to the current label's statement list.
93840          *
93841          * @param expression The value to return.
93842          * @param operationLocation The source map location for the operation.
93843          */
93844         function writeReturn(expression, operationLocation) {
93845             lastOperationWasAbrupt = true;
93846             lastOperationWasCompletion = true;
93847             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
93848                 ? [createInstruction(2 /* Return */), expression]
93849                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
93850         }
93851         /**
93852          * Writes a Break operation to the current label's statement list.
93853          *
93854          * @param label The label for the Break.
93855          * @param operationLocation The source map location for the operation.
93856          */
93857         function writeBreak(label, operationLocation) {
93858             lastOperationWasAbrupt = true;
93859             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93860                 createInstruction(3 /* Break */),
93861                 createLabel(label)
93862             ])), operationLocation), 384 /* NoTokenSourceMaps */));
93863         }
93864         /**
93865          * Writes a BreakWhenTrue operation to the current label's statement list.
93866          *
93867          * @param label The label for the Break.
93868          * @param condition The condition for the Break.
93869          * @param operationLocation The source map location for the operation.
93870          */
93871         function writeBreakWhenTrue(label, condition, operationLocation) {
93872             writeStatement(ts.setEmitFlags(factory.createIfStatement(condition, ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93873                 createInstruction(3 /* Break */),
93874                 createLabel(label)
93875             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
93876         }
93877         /**
93878          * Writes a BreakWhenFalse operation to the current label's statement list.
93879          *
93880          * @param label The label for the Break.
93881          * @param condition The condition for the Break.
93882          * @param operationLocation The source map location for the operation.
93883          */
93884         function writeBreakWhenFalse(label, condition, operationLocation) {
93885             writeStatement(ts.setEmitFlags(factory.createIfStatement(factory.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93886                 createInstruction(3 /* Break */),
93887                 createLabel(label)
93888             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
93889         }
93890         /**
93891          * Writes a Yield operation to the current label's statement list.
93892          *
93893          * @param expression The expression to yield.
93894          * @param operationLocation The source map location for the operation.
93895          */
93896         function writeYield(expression, operationLocation) {
93897             lastOperationWasAbrupt = true;
93898             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
93899                 ? [createInstruction(4 /* Yield */), expression]
93900                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
93901         }
93902         /**
93903          * Writes a YieldStar instruction to the current label's statement list.
93904          *
93905          * @param expression The expression to yield.
93906          * @param operationLocation The source map location for the operation.
93907          */
93908         function writeYieldStar(expression, operationLocation) {
93909             lastOperationWasAbrupt = true;
93910             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93911                 createInstruction(5 /* YieldStar */),
93912                 expression
93913             ])), operationLocation), 384 /* NoTokenSourceMaps */));
93914         }
93915         /**
93916          * Writes an Endfinally instruction to the current label's statement list.
93917          */
93918         function writeEndfinally() {
93919             lastOperationWasAbrupt = true;
93920             writeStatement(factory.createReturnStatement(factory.createArrayLiteralExpression([
93921                 createInstruction(7 /* Endfinally */)
93922             ])));
93923         }
93924     }
93925     ts.transformGenerators = transformGenerators;
93926 })(ts || (ts = {}));
93927 /*@internal*/
93928 var ts;
93929 (function (ts) {
93930     function transformModule(context) {
93931         function getTransformModuleDelegate(moduleKind) {
93932             switch (moduleKind) {
93933                 case ts.ModuleKind.AMD: return transformAMDModule;
93934                 case ts.ModuleKind.UMD: return transformUMDModule;
93935                 default: return transformCommonJSModule;
93936             }
93937         }
93938         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
93939         var compilerOptions = context.getCompilerOptions();
93940         var resolver = context.getEmitResolver();
93941         var host = context.getEmitHost();
93942         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93943         var moduleKind = ts.getEmitModuleKind(compilerOptions);
93944         var previousOnSubstituteNode = context.onSubstituteNode;
93945         var previousOnEmitNode = context.onEmitNode;
93946         context.onSubstituteNode = onSubstituteNode;
93947         context.onEmitNode = onEmitNode;
93948         context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
93949         context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols.
93950         context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
93951         context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
93952         context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
93953         context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file.
93954         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
93955         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
93956         var currentSourceFile; // The current file.
93957         var currentModuleInfo; // The ExternalModuleInfo for the current file.
93958         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
93959         var needUMDDynamicImportHelper;
93960         return ts.chainBundle(context, transformSourceFile);
93961         /**
93962          * Transforms the module aspects of a SourceFile.
93963          *
93964          * @param node The SourceFile node.
93965          */
93966         function transformSourceFile(node) {
93967             if (node.isDeclarationFile ||
93968                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
93969                     node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
93970                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) {
93971                 return node;
93972             }
93973             currentSourceFile = node;
93974             currentModuleInfo = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
93975             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
93976             // Perform the transformation.
93977             var transformModule = getTransformModuleDelegate(moduleKind);
93978             var updated = transformModule(node);
93979             currentSourceFile = undefined;
93980             currentModuleInfo = undefined;
93981             needUMDDynamicImportHelper = false;
93982             return updated;
93983         }
93984         function shouldEmitUnderscoreUnderscoreESModule() {
93985             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
93986                 return true;
93987             }
93988             return false;
93989         }
93990         /**
93991          * Transforms a SourceFile into a CommonJS module.
93992          *
93993          * @param node The SourceFile node.
93994          */
93995         function transformCommonJSModule(node) {
93996             startLexicalEnvironment();
93997             var statements = [];
93998             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
93999             var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
94000             if (shouldEmitUnderscoreUnderscoreESModule()) {
94001                 ts.append(statements, createUnderscoreUnderscoreESModule());
94002             }
94003             if (ts.length(currentModuleInfo.exportedNames)) {
94004                 var chunkSize = 50;
94005                 for (var i = 0; i < currentModuleInfo.exportedNames.length; i += chunkSize) {
94006                     ts.append(statements, factory.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames.slice(i, i + chunkSize), function (prev, nextId) { return factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(ts.idText(nextId))), prev); }, factory.createVoidZero())));
94007                 }
94008             }
94009             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
94010             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
94011             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
94012             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
94013             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
94014             ts.addEmitHelpers(updated, context.readEmitHelpers());
94015             return updated;
94016         }
94017         /**
94018          * Transforms a SourceFile into an AMD module.
94019          *
94020          * @param node The SourceFile node.
94021          */
94022         function transformAMDModule(node) {
94023             var define = factory.createIdentifier("define");
94024             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
94025             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
94026             // An AMD define function has the following shape:
94027             //
94028             //     define(id?, dependencies?, factory);
94029             //
94030             // This has the shape of the following:
94031             //
94032             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
94033             //
94034             // The location of the alias in the parameter list in the factory function needs to
94035             // match the position of the module name in the dependency list.
94036             //
94037             // To ensure this is true in cases of modules with no aliases, e.g.:
94038             //
94039             //     import "module"
94040             //
94041             // or
94042             //
94043             //     /// <amd-dependency path= "a.css" />
94044             //
94045             // we need to add modules without alias names to the end of the dependencies list
94046             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
94047             // Create an updated SourceFile:
94048             //
94049             //     define(mofactory.updateSourceFile", "module2"], function ...
94050             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
94051                 factory.createExpressionStatement(factory.createCallExpression(define, 
94052                 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
94053                     // Add the dependency array argument:
94054                     //
94055                     //     ["require", "exports", module1", "module2", ...]
94056                     factory.createArrayLiteralExpression(jsonSourceFile ? ts.emptyArray : __spreadArrays([
94057                         factory.createStringLiteral("require"),
94058                         factory.createStringLiteral("exports")
94059                     ], aliasedModuleNames, unaliasedModuleNames)),
94060                     // Add the module body function argument:
94061                     //
94062                     //     function (require, exports, module1, module2) ...
94063                     jsonSourceFile ?
94064                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory.createObjectLiteralExpression() :
94065                         factory.createFunctionExpression(
94066                         /*modifiers*/ undefined, 
94067                         /*asteriskToken*/ undefined, 
94068                         /*name*/ undefined, 
94069                         /*typeParameters*/ undefined, __spreadArrays([
94070                             factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
94071                             factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
94072                         ], importAliasNames), 
94073                         /*type*/ undefined, transformAsynchronousModuleBody(node))
94074                 ])))
94075             ]), 
94076             /*location*/ node.statements));
94077             ts.addEmitHelpers(updated, context.readEmitHelpers());
94078             return updated;
94079         }
94080         /**
94081          * Transforms a SourceFile into a UMD module.
94082          *
94083          * @param node The SourceFile node.
94084          */
94085         function transformUMDModule(node) {
94086             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
94087             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
94088             var umdHeader = factory.createFunctionExpression(
94089             /*modifiers*/ undefined, 
94090             /*asteriskToken*/ undefined, 
94091             /*name*/ undefined, 
94092             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
94093             /*type*/ undefined, ts.setTextRange(factory.createBlock([
94094                 factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([
94095                     factory.createVariableStatement(
94096                     /*modifiers*/ undefined, [
94097                         factory.createVariableDeclaration("v", 
94098                         /*exclamationToken*/ undefined, 
94099                         /*type*/ undefined, factory.createCallExpression(factory.createIdentifier("factory"), 
94100                         /*typeArguments*/ undefined, [
94101                             factory.createIdentifier("require"),
94102                             factory.createIdentifier("exports")
94103                         ]))
94104                     ]),
94105                     ts.setEmitFlags(factory.createIfStatement(factory.createStrictInequality(factory.createIdentifier("v"), factory.createIdentifier("undefined")), factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), factory.createIdentifier("v")))), 1 /* SingleLine */)
94106                 ]), factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("define"), "function"), factory.createPropertyAccessExpression(factory.createIdentifier("define"), "amd")), factory.createBlock([
94107                     factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("define"), 
94108                     /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
94109                         factory.createArrayLiteralExpression(__spreadArrays([
94110                             factory.createStringLiteral("require"),
94111                             factory.createStringLiteral("exports")
94112                         ], aliasedModuleNames, unaliasedModuleNames)),
94113                         factory.createIdentifier("factory")
94114                     ])))
94115                 ])))
94116             ], 
94117             /*multiLine*/ true), 
94118             /*location*/ undefined));
94119             // Create an updated SourceFile:
94120             //
94121             //  (function (factory) {
94122             //      if (typeof module === "object" && typeof module.exports === "object") {
94123             //          var v = factory(require, exports);
94124             //          if (v !== undefined) module.exports = v;
94125             //      }
94126             //      else if (typeof define === 'function' && define.amd) {
94127             //          define(["require", "exports"], factory);
94128             //      }
94129             //  })(function ...)
94130             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
94131                 factory.createExpressionStatement(factory.createCallExpression(umdHeader, 
94132                 /*typeArguments*/ undefined, [
94133                     // Add the module body function argument:
94134                     //
94135                     //     function (require, exports) ...
94136                     factory.createFunctionExpression(
94137                     /*modifiers*/ undefined, 
94138                     /*asteriskToken*/ undefined, 
94139                     /*name*/ undefined, 
94140                     /*typeParameters*/ undefined, __spreadArrays([
94141                         factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
94142                         factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
94143                     ], importAliasNames), 
94144                     /*type*/ undefined, transformAsynchronousModuleBody(node))
94145                 ]))
94146             ]), 
94147             /*location*/ node.statements));
94148             ts.addEmitHelpers(updated, context.readEmitHelpers());
94149             return updated;
94150         }
94151         /**
94152          * Collect the additional asynchronous dependencies for the module.
94153          *
94154          * @param node The source file.
94155          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
94156          */
94157         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
94158             // names of modules with corresponding parameter in the factory function
94159             var aliasedModuleNames = [];
94160             // names of modules with no corresponding parameters in factory function
94161             var unaliasedModuleNames = [];
94162             // names of the parameters in the factory function; these
94163             // parameters need to match the indexes of the corresponding
94164             // module names in aliasedModuleNames.
94165             var importAliasNames = [];
94166             // Fill in amd-dependency tags
94167             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
94168                 var amdDependency = _a[_i];
94169                 if (amdDependency.name) {
94170                     aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
94171                     importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
94172                 }
94173                 else {
94174                     unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
94175                 }
94176             }
94177             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
94178                 var importNode = _c[_b];
94179                 // Find the name of the external module
94180                 var externalModuleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
94181                 // Find the name of the module alias, if there is one
94182                 var importAliasName = ts.getLocalNameForExternalImport(factory, importNode, currentSourceFile);
94183                 // It is possible that externalModuleName is undefined if it is not string literal.
94184                 // This can happen in the invalid import syntax.
94185                 // E.g : "import * from alias from 'someLib';"
94186                 if (externalModuleName) {
94187                     if (includeNonAmdDependencies && importAliasName) {
94188                         // Set emitFlags on the name of the classDeclaration
94189                         // This is so that when printer will not substitute the identifier
94190                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
94191                         aliasedModuleNames.push(externalModuleName);
94192                         importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
94193                     }
94194                     else {
94195                         unaliasedModuleNames.push(externalModuleName);
94196                     }
94197                 }
94198             }
94199             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
94200         }
94201         function getAMDImportExpressionForImport(node) {
94202             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions)) {
94203                 return undefined;
94204             }
94205             var name = ts.getLocalNameForExternalImport(factory, node, currentSourceFile); // TODO: GH#18217
94206             var expr = getHelperExpressionForImport(node, name);
94207             if (expr === name) {
94208                 return undefined;
94209             }
94210             return factory.createExpressionStatement(factory.createAssignment(name, expr));
94211         }
94212         /**
94213          * Transforms a SourceFile into an AMD or UMD module body.
94214          *
94215          * @param node The SourceFile node.
94216          */
94217         function transformAsynchronousModuleBody(node) {
94218             startLexicalEnvironment();
94219             var statements = [];
94220             var statementOffset = factory.copyPrologue(node.statements, statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
94221             if (shouldEmitUnderscoreUnderscoreESModule()) {
94222                 ts.append(statements, createUnderscoreUnderscoreESModule());
94223             }
94224             if (ts.length(currentModuleInfo.exportedNames)) {
94225                 ts.append(statements, factory.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames, function (prev, nextId) { return factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(ts.idText(nextId))), prev); }, factory.createVoidZero())));
94226             }
94227             // Visit each statement of the module body.
94228             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
94229             if (moduleKind === ts.ModuleKind.AMD) {
94230                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
94231             }
94232             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
94233             // Append the 'export =' statement if provided.
94234             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
94235             // End the lexical environment for the module body
94236             // and merge any new lexical declarations.
94237             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
94238             var body = factory.createBlock(statements, /*multiLine*/ true);
94239             if (needUMDDynamicImportHelper) {
94240                 ts.addEmitHelper(body, dynamicImportUMDHelper);
94241             }
94242             return body;
94243         }
94244         /**
94245          * Adds the down-level representation of `export=` to the statement list if one exists
94246          * in the source file.
94247          *
94248          * @param statements The Statement list to modify.
94249          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
94250          * return statement.
94251          */
94252         function addExportEqualsIfNeeded(statements, emitAsReturn) {
94253             if (currentModuleInfo.exportEquals) {
94254                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
94255                 if (expressionResult) {
94256                     if (emitAsReturn) {
94257                         var statement = factory.createReturnStatement(expressionResult);
94258                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
94259                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
94260                         statements.push(statement);
94261                     }
94262                     else {
94263                         var statement = factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), expressionResult));
94264                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
94265                         ts.setEmitFlags(statement, 1536 /* NoComments */);
94266                         statements.push(statement);
94267                     }
94268                 }
94269             }
94270         }
94271         //
94272         // Top-Level Source Element Visitors
94273         //
94274         /**
94275          * Visits a node at the top level of the source file.
94276          *
94277          * @param node The node to visit.
94278          */
94279         function sourceElementVisitor(node) {
94280             switch (node.kind) {
94281                 case 261 /* ImportDeclaration */:
94282                     return visitImportDeclaration(node);
94283                 case 260 /* ImportEqualsDeclaration */:
94284                     return visitImportEqualsDeclaration(node);
94285                 case 267 /* ExportDeclaration */:
94286                     return visitExportDeclaration(node);
94287                 case 266 /* ExportAssignment */:
94288                     return visitExportAssignment(node);
94289                 case 232 /* VariableStatement */:
94290                     return visitVariableStatement(node);
94291                 case 251 /* FunctionDeclaration */:
94292                     return visitFunctionDeclaration(node);
94293                 case 252 /* ClassDeclaration */:
94294                     return visitClassDeclaration(node);
94295                 case 338 /* MergeDeclarationMarker */:
94296                     return visitMergeDeclarationMarker(node);
94297                 case 339 /* EndOfDeclarationMarker */:
94298                     return visitEndOfDeclarationMarker(node);
94299                 default:
94300                     return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
94301             }
94302         }
94303         function moduleExpressionElementVisitor(node) {
94304             // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
94305             // as export/import statements are only transformed at the top level of a file.
94306             if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
94307                 return node;
94308             }
94309             if (ts.isImportCall(node)) {
94310                 return visitImportCallExpression(node);
94311             }
94312             else if (ts.isDestructuringAssignment(node)) {
94313                 return visitDestructuringAssignment(node);
94314             }
94315             else {
94316                 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
94317             }
94318         }
94319         function destructuringNeedsFlattening(node) {
94320             if (ts.isObjectLiteralExpression(node)) {
94321                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
94322                     var elem = _a[_i];
94323                     switch (elem.kind) {
94324                         case 288 /* PropertyAssignment */:
94325                             if (destructuringNeedsFlattening(elem.initializer)) {
94326                                 return true;
94327                             }
94328                             break;
94329                         case 289 /* ShorthandPropertyAssignment */:
94330                             if (destructuringNeedsFlattening(elem.name)) {
94331                                 return true;
94332                             }
94333                             break;
94334                         case 290 /* SpreadAssignment */:
94335                             if (destructuringNeedsFlattening(elem.expression)) {
94336                                 return true;
94337                             }
94338                             break;
94339                         case 165 /* MethodDeclaration */:
94340                         case 167 /* GetAccessor */:
94341                         case 168 /* SetAccessor */:
94342                             return false;
94343                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
94344                     }
94345                 }
94346             }
94347             else if (ts.isArrayLiteralExpression(node)) {
94348                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
94349                     var elem = _c[_b];
94350                     if (ts.isSpreadElement(elem)) {
94351                         if (destructuringNeedsFlattening(elem.expression)) {
94352                             return true;
94353                         }
94354                     }
94355                     else if (destructuringNeedsFlattening(elem)) {
94356                         return true;
94357                     }
94358                 }
94359             }
94360             else if (ts.isIdentifier(node)) {
94361                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
94362             }
94363             return false;
94364         }
94365         function visitDestructuringAssignment(node) {
94366             if (destructuringNeedsFlattening(node.left)) {
94367                 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
94368             }
94369             return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
94370         }
94371         function visitImportCallExpression(node) {
94372             var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
94373             var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
94374             switch (compilerOptions.module) {
94375                 case ts.ModuleKind.AMD:
94376                     return createImportCallExpressionAMD(argument, containsLexicalThis);
94377                 case ts.ModuleKind.UMD:
94378                     return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis);
94379                 case ts.ModuleKind.CommonJS:
94380                 default:
94381                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
94382             }
94383         }
94384         function createImportCallExpressionUMD(arg, containsLexicalThis) {
94385             // (function (factory) {
94386             //      ... (regular UMD)
94387             // }
94388             // })(function (require, exports, useSyncRequire) {
94389             //      "use strict";
94390             //      Object.defineProperty(exports, "__esModule", { value: true });
94391             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
94392             //      var __resolved = new Promise(function (resolve) { resolve(); });
94393             //      .....
94394             //      __syncRequire
94395             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
94396             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
94397             // });
94398             needUMDDynamicImportHelper = true;
94399             if (ts.isSimpleCopiableExpression(arg)) {
94400                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? factory.createStringLiteralFromNode(arg) : ts.setEmitFlags(ts.setTextRange(factory.cloneNode(arg), arg), 1536 /* NoComments */);
94401                 return factory.createConditionalExpression(
94402                 /*condition*/ factory.createIdentifier("__syncRequire"), 
94403                 /*questionToken*/ undefined, 
94404                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
94405                 /*colonToken*/ undefined, 
94406                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
94407             }
94408             else {
94409                 var temp = factory.createTempVariable(hoistVariableDeclaration);
94410                 return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression(
94411                 /*condition*/ factory.createIdentifier("__syncRequire"), 
94412                 /*questionToken*/ undefined, 
94413                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
94414                 /*colonToken*/ undefined, 
94415                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
94416             }
94417         }
94418         function createImportCallExpressionAMD(arg, containsLexicalThis) {
94419             // improt("./blah")
94420             // emit as
94421             // define(["require", "exports", "blah"], function (require, exports) {
94422             //     ...
94423             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
94424             // });
94425             var resolve = factory.createUniqueName("resolve");
94426             var reject = factory.createUniqueName("reject");
94427             var parameters = [
94428                 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
94429                 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
94430             ];
94431             var body = factory.createBlock([
94432                 factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), 
94433                 /*typeArguments*/ undefined, [factory.createArrayLiteralExpression([arg || factory.createOmittedExpression()]), resolve, reject]))
94434             ]);
94435             var func;
94436             if (languageVersion >= 2 /* ES2015 */) {
94437                 func = factory.createArrowFunction(
94438                 /*modifiers*/ undefined, 
94439                 /*typeParameters*/ undefined, parameters, 
94440                 /*type*/ undefined, 
94441                 /*equalsGreaterThanToken*/ undefined, body);
94442             }
94443             else {
94444                 func = factory.createFunctionExpression(
94445                 /*modifiers*/ undefined, 
94446                 /*asteriskToken*/ undefined, 
94447                 /*name*/ undefined, 
94448                 /*typeParameters*/ undefined, parameters, 
94449                 /*type*/ undefined, body);
94450                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
94451                 // that this new function expression indicates it captures 'this' so that the
94452                 // es2015 transformer will properly substitute 'this' with '_this'.
94453                 if (containsLexicalThis) {
94454                     ts.setEmitFlags(func, 8 /* CapturesThis */);
94455                 }
94456             }
94457             var promise = factory.createNewExpression(factory.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
94458             if (compilerOptions.esModuleInterop) {
94459                 return factory.createCallExpression(factory.createPropertyAccessExpression(promise, factory.createIdentifier("then")), /*typeArguments*/ undefined, [emitHelpers().createImportStarCallbackHelper()]);
94460             }
94461             return promise;
94462         }
94463         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
94464             // import("./blah")
94465             // emit as
94466             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
94467             // We have to wrap require in then callback so that require is done in asynchronously
94468             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
94469             var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
94470             var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
94471             if (compilerOptions.esModuleInterop) {
94472                 requireCall = emitHelpers().createImportStarHelper(requireCall);
94473             }
94474             var func;
94475             if (languageVersion >= 2 /* ES2015 */) {
94476                 func = factory.createArrowFunction(
94477                 /*modifiers*/ undefined, 
94478                 /*typeParameters*/ undefined, 
94479                 /*parameters*/ [], 
94480                 /*type*/ undefined, 
94481                 /*equalsGreaterThanToken*/ undefined, requireCall);
94482             }
94483             else {
94484                 func = factory.createFunctionExpression(
94485                 /*modifiers*/ undefined, 
94486                 /*asteriskToken*/ undefined, 
94487                 /*name*/ undefined, 
94488                 /*typeParameters*/ undefined, 
94489                 /*parameters*/ [], 
94490                 /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)]));
94491                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
94492                 // that this new function expression indicates it captures 'this' so that the
94493                 // es2015 transformer will properly substitute 'this' with '_this'.
94494                 if (containsLexicalThis) {
94495                     ts.setEmitFlags(func, 8 /* CapturesThis */);
94496                 }
94497             }
94498             return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
94499         }
94500         function getHelperExpressionForExport(node, innerExpr) {
94501             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
94502                 return innerExpr;
94503             }
94504             if (ts.getExportNeedsImportStarHelper(node)) {
94505                 return emitHelpers().createImportStarHelper(innerExpr);
94506             }
94507             return innerExpr;
94508         }
94509         function getHelperExpressionForImport(node, innerExpr) {
94510             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
94511                 return innerExpr;
94512             }
94513             if (ts.getImportNeedsImportStarHelper(node)) {
94514                 return emitHelpers().createImportStarHelper(innerExpr);
94515             }
94516             if (ts.getImportNeedsImportDefaultHelper(node)) {
94517                 return emitHelpers().createImportDefaultHelper(innerExpr);
94518             }
94519             return innerExpr;
94520         }
94521         /**
94522          * Visits an ImportDeclaration node.
94523          *
94524          * @param node The node to visit.
94525          */
94526         function visitImportDeclaration(node) {
94527             var statements;
94528             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
94529             if (moduleKind !== ts.ModuleKind.AMD) {
94530                 if (!node.importClause) {
94531                     // import "mod";
94532                     return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createRequireCall(node)), node), node);
94533                 }
94534                 else {
94535                     var variables = [];
94536                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
94537                         // import * as n from "mod";
94538                         variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
94539                         /*exclamationToken*/ undefined, 
94540                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
94541                     }
94542                     else {
94543                         // import d from "mod";
94544                         // import { x, y } from "mod";
94545                         // import d, { x, y } from "mod";
94546                         // import d, * as n from "mod";
94547                         variables.push(factory.createVariableDeclaration(factory.getGeneratedNameForNode(node), 
94548                         /*exclamationToken*/ undefined, 
94549                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
94550                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
94551                             variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
94552                             /*exclamationToken*/ undefined, 
94553                             /*type*/ undefined, factory.getGeneratedNameForNode(node)));
94554                         }
94555                     }
94556                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
94557                     /*modifiers*/ undefined, factory.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
94558                     /*location*/ node), 
94559                     /*original*/ node));
94560                 }
94561             }
94562             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
94563                 // import d, * as n from "mod";
94564                 statements = ts.append(statements, factory.createVariableStatement(
94565                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
94566                     ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
94567                     /*exclamationToken*/ undefined, 
94568                     /*type*/ undefined, factory.getGeneratedNameForNode(node)), 
94569                     /*location*/ node), 
94570                     /*original*/ node)
94571                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
94572             }
94573             if (hasAssociatedEndOfDeclarationMarker(node)) {
94574                 // Defer exports until we encounter an EndOfDeclarationMarker node
94575                 var id = ts.getOriginalNodeId(node);
94576                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
94577             }
94578             else {
94579                 statements = appendExportsOfImportDeclaration(statements, node);
94580             }
94581             return ts.singleOrMany(statements);
94582         }
94583         /**
94584          * Creates a `require()` call to import an external module.
94585          *
94586          * @param importNode The declararation to import.
94587          */
94588         function createRequireCall(importNode) {
94589             var moduleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
94590             var args = [];
94591             if (moduleName) {
94592                 args.push(moduleName);
94593             }
94594             return factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, args);
94595         }
94596         /**
94597          * Visits an ImportEqualsDeclaration node.
94598          *
94599          * @param node The node to visit.
94600          */
94601         function visitImportEqualsDeclaration(node) {
94602             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
94603             var statements;
94604             if (moduleKind !== ts.ModuleKind.AMD) {
94605                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94606                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
94607                 }
94608                 else {
94609                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
94610                     /*modifiers*/ undefined, factory.createVariableDeclarationList([
94611                         factory.createVariableDeclaration(factory.cloneNode(node.name), 
94612                         /*exclamationToken*/ undefined, 
94613                         /*type*/ undefined, createRequireCall(node))
94614                     ], 
94615                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
94616                 }
94617             }
94618             else {
94619                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94620                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(node), factory.getLocalName(node))), node), node));
94621                 }
94622             }
94623             if (hasAssociatedEndOfDeclarationMarker(node)) {
94624                 // Defer exports until we encounter an EndOfDeclarationMarker node
94625                 var id = ts.getOriginalNodeId(node);
94626                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
94627             }
94628             else {
94629                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
94630             }
94631             return ts.singleOrMany(statements);
94632         }
94633         /**
94634          * Visits an ExportDeclaration node.
94635          *
94636          * @param The node to visit.
94637          */
94638         function visitExportDeclaration(node) {
94639             if (!node.moduleSpecifier) {
94640                 // Elide export declarations with no module specifier as they are handled
94641                 // elsewhere.
94642                 return undefined;
94643             }
94644             var generatedName = factory.getGeneratedNameForNode(node);
94645             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
94646                 var statements = [];
94647                 // export { x, y } from "mod";
94648                 if (moduleKind !== ts.ModuleKind.AMD) {
94649                     statements.push(ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
94650                     /*modifiers*/ undefined, factory.createVariableDeclarationList([
94651                         factory.createVariableDeclaration(generatedName, 
94652                         /*exclamationToken*/ undefined, 
94653                         /*type*/ undefined, createRequireCall(node))
94654                     ])), 
94655                     /*location*/ node), 
94656                     /* original */ node));
94657                 }
94658                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
94659                     var specifier = _a[_i];
94660                     if (languageVersion === 0 /* ES3 */) {
94661                         statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createCreateBindingHelper(generatedName, factory.createStringLiteralFromNode(specifier.propertyName || specifier.name), specifier.propertyName ? factory.createStringLiteralFromNode(specifier.name) : undefined)), specifier), specifier));
94662                     }
94663                     else {
94664                         var exportNeedsImportDefault = !!compilerOptions.esModuleInterop &&
94665                             !(ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) &&
94666                             ts.idText(specifier.propertyName || specifier.name) === "default";
94667                         var exportedValue = factory.createPropertyAccessExpression(exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, specifier.propertyName || specifier.name);
94668                         statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
94669                     }
94670                 }
94671                 return ts.singleOrMany(statements);
94672             }
94673             else if (node.exportClause) {
94674                 var statements = [];
94675                 // export * as ns from "mod";
94676                 // export * as default from "mod";
94677                 statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.cloneNode(node.exportClause.name), getHelperExpressionForExport(node, moduleKind !== ts.ModuleKind.AMD ?
94678                     createRequireCall(node) :
94679                     ts.isExportNamespaceAsDefaultDeclaration(node) ? generatedName :
94680                         factory.createIdentifier(ts.idText(node.exportClause.name))))), node), node));
94681                 return ts.singleOrMany(statements);
94682             }
94683             else {
94684                 // export * from "mod";
94685                 return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExportStarHelper(moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
94686             }
94687         }
94688         /**
94689          * Visits an ExportAssignment node.
94690          *
94691          * @param node The node to visit.
94692          */
94693         function visitExportAssignment(node) {
94694             if (node.isExportEquals) {
94695                 return undefined;
94696             }
94697             var statements;
94698             var original = node.original;
94699             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
94700                 // Defer exports until we encounter an EndOfDeclarationMarker node
94701                 var id = ts.getOriginalNodeId(node);
94702                 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
94703             }
94704             else {
94705                 statements = appendExportStatement(statements, factory.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
94706             }
94707             return ts.singleOrMany(statements);
94708         }
94709         /**
94710          * Visits a FunctionDeclaration node.
94711          *
94712          * @param node The node to visit.
94713          */
94714         function visitFunctionDeclaration(node) {
94715             var statements;
94716             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94717                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
94718                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
94719                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
94720                 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
94721                 /*location*/ node), 
94722                 /*original*/ node));
94723             }
94724             else {
94725                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
94726             }
94727             if (hasAssociatedEndOfDeclarationMarker(node)) {
94728                 // Defer exports until we encounter an EndOfDeclarationMarker node
94729                 var id = ts.getOriginalNodeId(node);
94730                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
94731             }
94732             else {
94733                 statements = appendExportsOfHoistedDeclaration(statements, node);
94734             }
94735             return ts.singleOrMany(statements);
94736         }
94737         /**
94738          * Visits a ClassDeclaration node.
94739          *
94740          * @param node The node to visit.
94741          */
94742         function visitClassDeclaration(node) {
94743             var statements;
94744             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94745                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(
94746                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
94747                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
94748             }
94749             else {
94750                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
94751             }
94752             if (hasAssociatedEndOfDeclarationMarker(node)) {
94753                 // Defer exports until we encounter an EndOfDeclarationMarker node
94754                 var id = ts.getOriginalNodeId(node);
94755                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
94756             }
94757             else {
94758                 statements = appendExportsOfHoistedDeclaration(statements, node);
94759             }
94760             return ts.singleOrMany(statements);
94761         }
94762         /**
94763          * Visits a VariableStatement node.
94764          *
94765          * @param node The node to visit.
94766          */
94767         function visitVariableStatement(node) {
94768             var statements;
94769             var variables;
94770             var expressions;
94771             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94772                 var modifiers = void 0;
94773                 var removeCommentsOnExpressions = false;
94774                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
94775                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
94776                     var variable = _a[_i];
94777                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
94778                         if (!modifiers) {
94779                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
94780                         }
94781                         variables = ts.append(variables, variable);
94782                     }
94783                     else if (variable.initializer) {
94784                         if (!ts.isBindingPattern(variable.name) && (ts.isArrowFunction(variable.initializer) || ts.isFunctionExpression(variable.initializer) || ts.isClassExpression(variable.initializer))) {
94785                             var expression = factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), variable.name), 
94786                             /*location*/ variable.name), factory.createIdentifier(ts.getTextOfIdentifierOrLiteral(variable.name)));
94787                             var updatedVariable = factory.createVariableDeclaration(variable.name, variable.exclamationToken, variable.type, ts.visitNode(variable.initializer, moduleExpressionElementVisitor));
94788                             variables = ts.append(variables, updatedVariable);
94789                             expressions = ts.append(expressions, expression);
94790                             removeCommentsOnExpressions = true;
94791                         }
94792                         else {
94793                             expressions = ts.append(expressions, transformInitializedVariable(variable));
94794                         }
94795                     }
94796                 }
94797                 if (variables) {
94798                     statements = ts.append(statements, factory.updateVariableStatement(node, modifiers, factory.updateVariableDeclarationList(node.declarationList, variables)));
94799                 }
94800                 if (expressions) {
94801                     var statement = ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node), node);
94802                     if (removeCommentsOnExpressions) {
94803                         ts.removeAllComments(statement);
94804                     }
94805                     statements = ts.append(statements, statement);
94806                 }
94807             }
94808             else {
94809                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
94810             }
94811             if (hasAssociatedEndOfDeclarationMarker(node)) {
94812                 // Defer exports until we encounter an EndOfDeclarationMarker node
94813                 var id = ts.getOriginalNodeId(node);
94814                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
94815             }
94816             else {
94817                 statements = appendExportsOfVariableStatement(statements, node);
94818             }
94819             return ts.singleOrMany(statements);
94820         }
94821         function createAllExportExpressions(name, value, location) {
94822             var exportedNames = getExports(name);
94823             if (exportedNames) {
94824                 // For each additional export of the declaration, apply an export assignment.
94825                 var expression = ts.isExportName(name) ? value : factory.createAssignment(name, value);
94826                 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
94827                     var exportName = exportedNames_1[_i];
94828                     // Mark the node to prevent triggering substitution.
94829                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
94830                     expression = createExportExpression(exportName, expression, /*location*/ location);
94831                 }
94832                 return expression;
94833             }
94834             return factory.createAssignment(name, value);
94835         }
94836         /**
94837          * Transforms an exported variable with an initializer into an expression.
94838          *
94839          * @param node The node to transform.
94840          */
94841         function transformInitializedVariable(node) {
94842             if (ts.isBindingPattern(node.name)) {
94843                 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
94844                 /*visitor*/ undefined, context, 0 /* All */, 
94845                 /*needsValue*/ false, createAllExportExpressions);
94846             }
94847             else {
94848                 return factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), node.name), 
94849                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : factory.createVoidZero());
94850             }
94851         }
94852         /**
94853          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
94854          * and transformed declaration.
94855          *
94856          * @param node The node to visit.
94857          */
94858         function visitMergeDeclarationMarker(node) {
94859             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
94860             // declaration we do not emit a leading variable declaration. To preserve the
94861             // begin/end semantics of the declararation and to properly handle exports
94862             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
94863             //
94864             // To balance the declaration, add the exports of the elided variable
94865             // statement.
94866             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) {
94867                 var id = ts.getOriginalNodeId(node);
94868                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
94869             }
94870             return node;
94871         }
94872         /**
94873          * Determines whether a node has an associated EndOfDeclarationMarker.
94874          *
94875          * @param node The node to test.
94876          */
94877         function hasAssociatedEndOfDeclarationMarker(node) {
94878             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
94879         }
94880         /**
94881          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
94882          * declaration.
94883          *
94884          * @param node The node to visit.
94885          */
94886         function visitEndOfDeclarationMarker(node) {
94887             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
94888             // end of the transformed declaration. We use this marker to emit any deferred exports
94889             // of the declaration.
94890             var id = ts.getOriginalNodeId(node);
94891             var statements = deferredExports[id];
94892             if (statements) {
94893                 delete deferredExports[id];
94894                 return ts.append(statements, node);
94895             }
94896             return node;
94897         }
94898         /**
94899          * Appends the exports of an ImportDeclaration to a statement list, returning the
94900          * statement list.
94901          *
94902          * @param statements A statement list to which the down-level export statements are to be
94903          * appended. If `statements` is `undefined`, a new array is allocated if statements are
94904          * appended.
94905          * @param decl The declaration whose exports are to be recorded.
94906          */
94907         function appendExportsOfImportDeclaration(statements, decl) {
94908             if (currentModuleInfo.exportEquals) {
94909                 return statements;
94910             }
94911             var importClause = decl.importClause;
94912             if (!importClause) {
94913                 return statements;
94914             }
94915             if (importClause.name) {
94916                 statements = appendExportsOfDeclaration(statements, importClause);
94917             }
94918             var namedBindings = importClause.namedBindings;
94919             if (namedBindings) {
94920                 switch (namedBindings.kind) {
94921                     case 263 /* NamespaceImport */:
94922                         statements = appendExportsOfDeclaration(statements, namedBindings);
94923                         break;
94924                     case 264 /* NamedImports */:
94925                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
94926                             var importBinding = _a[_i];
94927                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
94928                         }
94929                         break;
94930                 }
94931             }
94932             return statements;
94933         }
94934         /**
94935          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
94936          * statement list.
94937          *
94938          * @param statements A statement list to which the down-level export statements are to be
94939          * appended. If `statements` is `undefined`, a new array is allocated if statements are
94940          * appended.
94941          * @param decl The declaration whose exports are to be recorded.
94942          */
94943         function appendExportsOfImportEqualsDeclaration(statements, decl) {
94944             if (currentModuleInfo.exportEquals) {
94945                 return statements;
94946             }
94947             return appendExportsOfDeclaration(statements, decl);
94948         }
94949         /**
94950          * Appends the exports of a VariableStatement to a statement list, returning the statement
94951          * list.
94952          *
94953          * @param statements A statement list to which the down-level export statements are to be
94954          * appended. If `statements` is `undefined`, a new array is allocated if statements are
94955          * appended.
94956          * @param node The VariableStatement whose exports are to be recorded.
94957          */
94958         function appendExportsOfVariableStatement(statements, node) {
94959             if (currentModuleInfo.exportEquals) {
94960                 return statements;
94961             }
94962             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
94963                 var decl = _a[_i];
94964                 statements = appendExportsOfBindingElement(statements, decl);
94965             }
94966             return statements;
94967         }
94968         /**
94969          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
94970          * returning the statement list.
94971          *
94972          * @param statements A statement list to which the down-level export statements are to be
94973          * appended. If `statements` is `undefined`, a new array is allocated if statements are
94974          * appended.
94975          * @param decl The declaration whose exports are to be recorded.
94976          */
94977         function appendExportsOfBindingElement(statements, decl) {
94978             if (currentModuleInfo.exportEquals) {
94979                 return statements;
94980             }
94981             if (ts.isBindingPattern(decl.name)) {
94982                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
94983                     var element = _a[_i];
94984                     if (!ts.isOmittedExpression(element)) {
94985                         statements = appendExportsOfBindingElement(statements, element);
94986                     }
94987                 }
94988             }
94989             else if (!ts.isGeneratedIdentifier(decl.name)) {
94990                 statements = appendExportsOfDeclaration(statements, decl);
94991             }
94992             return statements;
94993         }
94994         /**
94995          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
94996          * returning the statement list.
94997          *
94998          * @param statements A statement list to which the down-level export statements are to be
94999          * appended. If `statements` is `undefined`, a new array is allocated if statements are
95000          * appended.
95001          * @param decl The declaration whose exports are to be recorded.
95002          */
95003         function appendExportsOfHoistedDeclaration(statements, decl) {
95004             if (currentModuleInfo.exportEquals) {
95005                 return statements;
95006             }
95007             if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
95008                 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createIdentifier("default") : factory.getDeclarationName(decl);
95009                 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl), /*location*/ decl);
95010             }
95011             if (decl.name) {
95012                 statements = appendExportsOfDeclaration(statements, decl);
95013             }
95014             return statements;
95015         }
95016         /**
95017          * Appends the exports of a declaration to a statement list, returning the statement list.
95018          *
95019          * @param statements A statement list to which the down-level export statements are to be
95020          * appended. If `statements` is `undefined`, a new array is allocated if statements are
95021          * appended.
95022          * @param decl The declaration to export.
95023          */
95024         function appendExportsOfDeclaration(statements, decl, liveBinding) {
95025             var name = factory.getDeclarationName(decl);
95026             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
95027             if (exportSpecifiers) {
95028                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
95029                     var exportSpecifier = exportSpecifiers_1[_i];
95030                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
95031                 }
95032             }
95033             return statements;
95034         }
95035         /**
95036          * Appends the down-level representation of an export to a statement list, returning the
95037          * statement list.
95038          *
95039          * @param statements A statement list to which the down-level export statements are to be
95040          * appended. If `statements` is `undefined`, a new array is allocated if statements are
95041          * appended.
95042          * @param exportName The name of the export.
95043          * @param expression The expression to export.
95044          * @param location The location to use for source maps and comments for the export.
95045          * @param allowComments Whether to allow comments on the export.
95046          */
95047         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
95048             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
95049             return statements;
95050         }
95051         function createUnderscoreUnderscoreESModule() {
95052             var statement;
95053             if (languageVersion === 0 /* ES3 */) {
95054                 statement = factory.createExpressionStatement(createExportExpression(factory.createIdentifier("__esModule"), factory.createTrue()));
95055             }
95056             else {
95057                 statement = factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
95058                 /*typeArguments*/ undefined, [
95059                     factory.createIdentifier("exports"),
95060                     factory.createStringLiteral("__esModule"),
95061                     factory.createObjectLiteralExpression([
95062                         factory.createPropertyAssignment("value", factory.createTrue())
95063                     ])
95064                 ]));
95065             }
95066             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
95067             return statement;
95068         }
95069         /**
95070          * Creates a call to the current file's export function to export a value.
95071          *
95072          * @param name The bound name of the export.
95073          * @param value The exported value.
95074          * @param location The location to use for source maps and comments for the export.
95075          * @param allowComments An optional value indicating whether to emit comments for the statement.
95076          */
95077         function createExportStatement(name, value, location, allowComments, liveBinding) {
95078             var statement = ts.setTextRange(factory.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
95079             ts.startOnNewLine(statement);
95080             if (!allowComments) {
95081                 ts.setEmitFlags(statement, 1536 /* NoComments */);
95082             }
95083             return statement;
95084         }
95085         /**
95086          * Creates a call to the current file's export function to export a value.
95087          *
95088          * @param name The bound name of the export.
95089          * @param value The exported value.
95090          * @param location The location to use for source maps and comments for the export.
95091          */
95092         function createExportExpression(name, value, location, liveBinding) {
95093             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
95094             /*typeArguments*/ undefined, [
95095                 factory.createIdentifier("exports"),
95096                 factory.createStringLiteralFromNode(name),
95097                 factory.createObjectLiteralExpression([
95098                     factory.createPropertyAssignment("enumerable", factory.createTrue()),
95099                     factory.createPropertyAssignment("get", factory.createFunctionExpression(
95100                     /*modifiers*/ undefined, 
95101                     /*asteriskToken*/ undefined, 
95102                     /*name*/ undefined, 
95103                     /*typeParameters*/ undefined, 
95104                     /*parameters*/ [], 
95105                     /*type*/ undefined, factory.createBlock([factory.createReturnStatement(value)])))
95106                 ])
95107             ]) : factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(name)), value), location);
95108         }
95109         //
95110         // Modifier Visitors
95111         //
95112         /**
95113          * Visit nodes to elide module-specific modifiers.
95114          *
95115          * @param node The node to visit.
95116          */
95117         function modifierVisitor(node) {
95118             // Elide module-specific modifiers.
95119             switch (node.kind) {
95120                 case 92 /* ExportKeyword */:
95121                 case 87 /* DefaultKeyword */:
95122                     return undefined;
95123             }
95124             return node;
95125         }
95126         //
95127         // Emit Notification
95128         //
95129         /**
95130          * Hook for node emit notifications.
95131          *
95132          * @param hint A hint as to the intended usage of the node.
95133          * @param node The node to emit.
95134          * @param emit A callback used to emit the node in the printer.
95135          */
95136         function onEmitNode(hint, node, emitCallback) {
95137             if (node.kind === 297 /* SourceFile */) {
95138                 currentSourceFile = node;
95139                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
95140                 noSubstitution = [];
95141                 previousOnEmitNode(hint, node, emitCallback);
95142                 currentSourceFile = undefined;
95143                 currentModuleInfo = undefined;
95144                 noSubstitution = undefined;
95145             }
95146             else {
95147                 previousOnEmitNode(hint, node, emitCallback);
95148             }
95149         }
95150         //
95151         // Substitutions
95152         //
95153         /**
95154          * Hooks node substitutions.
95155          *
95156          * @param hint A hint as to the intended usage of the node.
95157          * @param node The node to substitute.
95158          */
95159         function onSubstituteNode(hint, node) {
95160             node = previousOnSubstituteNode(hint, node);
95161             if (node.id && noSubstitution[node.id]) {
95162                 return node;
95163             }
95164             if (hint === 1 /* Expression */) {
95165                 return substituteExpression(node);
95166             }
95167             else if (ts.isShorthandPropertyAssignment(node)) {
95168                 return substituteShorthandPropertyAssignment(node);
95169             }
95170             return node;
95171         }
95172         /**
95173          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
95174          * or exported symbol.
95175          *
95176          * @param node The node to substitute.
95177          */
95178         function substituteShorthandPropertyAssignment(node) {
95179             var name = node.name;
95180             var exportedOrImportedName = substituteExpressionIdentifier(name);
95181             if (exportedOrImportedName !== name) {
95182                 // A shorthand property with an assignment initializer is probably part of a
95183                 // destructuring assignment
95184                 if (node.objectAssignmentInitializer) {
95185                     var initializer = factory.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
95186                     return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
95187                 }
95188                 return ts.setTextRange(factory.createPropertyAssignment(name, exportedOrImportedName), node);
95189             }
95190             return node;
95191         }
95192         /**
95193          * Substitution for an Expression that may contain an imported or exported symbol.
95194          *
95195          * @param node The node to substitute.
95196          */
95197         function substituteExpression(node) {
95198             switch (node.kind) {
95199                 case 78 /* Identifier */:
95200                     return substituteExpressionIdentifier(node);
95201                 case 216 /* BinaryExpression */:
95202                     return substituteBinaryExpression(node);
95203                 case 215 /* PostfixUnaryExpression */:
95204                 case 214 /* PrefixUnaryExpression */:
95205                     return substituteUnaryExpression(node);
95206             }
95207             return node;
95208         }
95209         /**
95210          * Substitution for an Identifier expression that may contain an imported or exported
95211          * symbol.
95212          *
95213          * @param node The node to substitute.
95214          */
95215         function substituteExpressionIdentifier(node) {
95216             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
95217                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
95218                 if (externalHelpersModuleName) {
95219                     return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
95220                 }
95221                 return node;
95222             }
95223             if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) {
95224                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
95225                 if (exportContainer && exportContainer.kind === 297 /* SourceFile */) {
95226                     return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), 
95227                     /*location*/ node);
95228                 }
95229                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
95230                 if (importDeclaration) {
95231                     if (ts.isImportClause(importDeclaration)) {
95232                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), 
95233                         /*location*/ node);
95234                     }
95235                     else if (ts.isImportSpecifier(importDeclaration)) {
95236                         var name = importDeclaration.propertyName || importDeclaration.name;
95237                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(name)), 
95238                         /*location*/ node);
95239                     }
95240                 }
95241             }
95242             return node;
95243         }
95244         /**
95245          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
95246          *
95247          * @param node The node to substitute.
95248          */
95249         function substituteBinaryExpression(node) {
95250             // When we see an assignment expression whose left-hand side is an exported symbol,
95251             // we should ensure all exports of that symbol are updated with the correct value.
95252             //
95253             // - We do not substitute generated identifiers for any reason.
95254             // - We do not substitute identifiers tagged with the LocalName flag.
95255             // - We do not substitute identifiers that were originally the name of an enum or
95256             //   namespace due to how they are transformed in TypeScript.
95257             // - We only substitute identifiers that are exported at the top level.
95258             if (ts.isAssignmentOperator(node.operatorToken.kind)
95259                 && ts.isIdentifier(node.left)
95260                 && !ts.isGeneratedIdentifier(node.left)
95261                 && !ts.isLocalName(node.left)
95262                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
95263                 var exportedNames = getExports(node.left);
95264                 if (exportedNames) {
95265                     // For each additional export of the declaration, apply an export assignment.
95266                     var expression = node;
95267                     for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
95268                         var exportName = exportedNames_2[_i];
95269                         // Mark the node to prevent triggering this rule again.
95270                         noSubstitution[ts.getNodeId(expression)] = true;
95271                         expression = createExportExpression(exportName, expression, /*location*/ node);
95272                     }
95273                     return expression;
95274                 }
95275             }
95276             return node;
95277         }
95278         /**
95279          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
95280          *
95281          * @param node The node to substitute.
95282          */
95283         function substituteUnaryExpression(node) {
95284             // When we see a prefix or postfix increment expression whose operand is an exported
95285             // symbol, we should ensure all exports of that symbol are updated with the correct
95286             // value.
95287             //
95288             // - We do not substitute generated identifiers for any reason.
95289             // - We do not substitute identifiers tagged with the LocalName flag.
95290             // - We do not substitute identifiers that were originally the name of an enum or
95291             //   namespace due to how they are transformed in TypeScript.
95292             // - We only substitute identifiers that are exported at the top level.
95293             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
95294                 && ts.isIdentifier(node.operand)
95295                 && !ts.isGeneratedIdentifier(node.operand)
95296                 && !ts.isLocalName(node.operand)
95297                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
95298                 var exportedNames = getExports(node.operand);
95299                 if (exportedNames) {
95300                     var expression = node.kind === 215 /* PostfixUnaryExpression */
95301                         ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), factory.createNumericLiteral(1)), 
95302                         /*location*/ node)
95303                         : node;
95304                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
95305                         var exportName = exportedNames_3[_i];
95306                         // Mark the node to prevent triggering this rule again.
95307                         noSubstitution[ts.getNodeId(expression)] = true;
95308                         expression = createExportExpression(exportName, expression);
95309                     }
95310                     return expression;
95311                 }
95312             }
95313             return node;
95314         }
95315         /**
95316          * Gets the additional exports of a name.
95317          *
95318          * @param name The name.
95319          */
95320         function getExports(name) {
95321             if (!ts.isGeneratedIdentifier(name)) {
95322                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
95323                     || resolver.getReferencedValueDeclaration(name);
95324                 if (valueDeclaration) {
95325                     return currentModuleInfo
95326                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
95327                 }
95328             }
95329         }
95330     }
95331     ts.transformModule = transformModule;
95332     // emit helper for dynamic import
95333     var dynamicImportUMDHelper = {
95334         name: "typescript:dynamicimport-sync-require",
95335         scoped: true,
95336         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
95337     };
95338 })(ts || (ts = {}));
95339 /*@internal*/
95340 var ts;
95341 (function (ts) {
95342     function transformSystemModule(context) {
95343         var factory = context.factory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
95344         var compilerOptions = context.getCompilerOptions();
95345         var resolver = context.getEmitResolver();
95346         var host = context.getEmitHost();
95347         var previousOnSubstituteNode = context.onSubstituteNode;
95348         var previousOnEmitNode = context.onEmitNode;
95349         context.onSubstituteNode = onSubstituteNode;
95350         context.onEmitNode = onEmitNode;
95351         context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers for imported symbols.
95352         context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
95353         context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols.
95354         context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
95355         context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
95356         context.enableSubstitution(226 /* MetaProperty */); // Substitutes 'import.meta'
95357         context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file.
95358         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
95359         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
95360         var exportFunctionsMap = []; // The export function associated with a source file.
95361         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
95362         var contextObjectMap = []; // The context object associated with a source file.
95363         var currentSourceFile; // The current file.
95364         var moduleInfo; // ExternalModuleInfo for the current file.
95365         var exportFunction; // The export function for the current file.
95366         var contextObject; // The context object for the current file.
95367         var hoistedStatements;
95368         var enclosingBlockScopedContainer;
95369         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
95370         return ts.chainBundle(context, transformSourceFile);
95371         /**
95372          * Transforms the module aspects of a SourceFile.
95373          *
95374          * @param node The SourceFile node.
95375          */
95376         function transformSourceFile(node) {
95377             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
95378                 return node;
95379             }
95380             var id = ts.getOriginalNodeId(node);
95381             currentSourceFile = node;
95382             enclosingBlockScopedContainer = node;
95383             // System modules have the following shape:
95384             //
95385             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
95386             //
95387             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
95388             // is used to publish exported values. 'exports' returns its 'value' argument so in
95389             // most cases expressions that mutate exported values can be rewritten as:
95390             //
95391             //     expr -> exports('name', expr)
95392             //
95393             // The only exception in this rule is postfix unary operators,
95394             // see comment to 'substitutePostfixUnaryExpression' for more details
95395             // Collect information about the external module and dependency groups.
95396             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
95397             // Make sure that the name of the 'exports' function does not conflict with
95398             // existing identifiers.
95399             exportFunction = factory.createUniqueName("exports");
95400             exportFunctionsMap[id] = exportFunction;
95401             contextObject = contextObjectMap[id] = factory.createUniqueName("context");
95402             // Add the body of the module.
95403             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
95404             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
95405             var moduleBodyFunction = factory.createFunctionExpression(
95406             /*modifiers*/ undefined, 
95407             /*asteriskToken*/ undefined, 
95408             /*name*/ undefined, 
95409             /*typeParameters*/ undefined, [
95410                 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
95411                 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
95412             ], 
95413             /*type*/ undefined, moduleBodyBlock);
95414             // Write the call to `System.register`
95415             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
95416             // So the helper will be emit at the correct position instead of at the top of the source-file
95417             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
95418             var dependencies = factory.createArrayLiteralExpression(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
95419             var updated = ts.setEmitFlags(factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
95420                 factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("System"), "register"), 
95421                 /*typeArguments*/ undefined, moduleName
95422                     ? [moduleName, dependencies, moduleBodyFunction]
95423                     : [dependencies, moduleBodyFunction]))
95424             ]), node.statements)), 1024 /* NoTrailingComments */);
95425             if (!ts.outFile(compilerOptions)) {
95426                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
95427             }
95428             if (noSubstitution) {
95429                 noSubstitutionMap[id] = noSubstitution;
95430                 noSubstitution = undefined;
95431             }
95432             currentSourceFile = undefined;
95433             moduleInfo = undefined;
95434             exportFunction = undefined;
95435             contextObject = undefined;
95436             hoistedStatements = undefined;
95437             enclosingBlockScopedContainer = undefined;
95438             return updated;
95439         }
95440         /**
95441          * Collects the dependency groups for this files imports.
95442          *
95443          * @param externalImports The imports for the file.
95444          */
95445         function collectDependencyGroups(externalImports) {
95446             var groupIndices = new ts.Map();
95447             var dependencyGroups = [];
95448             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
95449                 var externalImport = externalImports_1[_i];
95450                 var externalModuleName = ts.getExternalModuleNameLiteral(factory, externalImport, currentSourceFile, host, resolver, compilerOptions);
95451                 if (externalModuleName) {
95452                     var text = externalModuleName.text;
95453                     var groupIndex = groupIndices.get(text);
95454                     if (groupIndex !== undefined) {
95455                         // deduplicate/group entries in dependency list by the dependency name
95456                         dependencyGroups[groupIndex].externalImports.push(externalImport);
95457                     }
95458                     else {
95459                         groupIndices.set(text, dependencyGroups.length);
95460                         dependencyGroups.push({
95461                             name: externalModuleName,
95462                             externalImports: [externalImport]
95463                         });
95464                     }
95465                 }
95466             }
95467             return dependencyGroups;
95468         }
95469         /**
95470          * Adds the statements for the module body function for the source file.
95471          *
95472          * @param node The source file for the module.
95473          * @param dependencyGroups The grouped dependencies of the module.
95474          */
95475         function createSystemModuleBody(node, dependencyGroups) {
95476             // Shape of the body in system modules:
95477             //
95478             //  function (exports) {
95479             //      <list of local aliases for imports>
95480             //      <hoisted variable declarations>
95481             //      <hoisted function declarations>
95482             //      return {
95483             //          setters: [
95484             //              <list of setter function for imports>
95485             //          ],
95486             //          execute: function() {
95487             //              <module statements>
95488             //          }
95489             //      }
95490             //      <temp declarations>
95491             //  }
95492             //
95493             // i.e:
95494             //
95495             //   import {x} from 'file1'
95496             //   var y = 1;
95497             //   export function foo() { return y + x(); }
95498             //   console.log(y);
95499             //
95500             // Will be transformed to:
95501             //
95502             //  function(exports) {
95503             //      function foo() { return y + file_1.x(); }
95504             //      exports("foo", foo);
95505             //      var file_1, y;
95506             //      return {
95507             //          setters: [
95508             //              function(v) { file_1 = v }
95509             //          ],
95510             //          execute(): function() {
95511             //              y = 1;
95512             //              console.log(y);
95513             //          }
95514             //      };
95515             //  }
95516             var statements = [];
95517             // We start a new lexical environment in this function body, but *not* in the
95518             // body of the execute function. This allows us to emit temporary declarations
95519             // only in the outer module body and not in the inner one.
95520             startLexicalEnvironment();
95521             // Add any prologue directives.
95522             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
95523             var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict, sourceElementVisitor);
95524             // var __moduleName = context_1 && context_1.id;
95525             statements.push(factory.createVariableStatement(
95526             /*modifiers*/ undefined, factory.createVariableDeclarationList([
95527                 factory.createVariableDeclaration("__moduleName", 
95528                 /*exclamationToken*/ undefined, 
95529                 /*type*/ undefined, factory.createLogicalAnd(contextObject, factory.createPropertyAccessExpression(contextObject, "id")))
95530             ])));
95531             // Visit the synthetic external helpers import declaration if present
95532             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
95533             // Visit the statements of the source file, emitting any transformations into
95534             // the `executeStatements` array. We do this *before* we fill the `setters` array
95535             // as we both emit transformations as well as aggregate some data used when creating
95536             // setters. This allows us to reduce the number of times we need to loop through the
95537             // statements of the source file.
95538             var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
95539             // Emit early exports for function declarations.
95540             ts.addRange(statements, hoistedStatements);
95541             // We emit hoisted variables early to align roughly with our previous emit output.
95542             // Two key differences in this approach are:
95543             // - Temporary variables will appear at the top rather than at the bottom of the file
95544             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
95545             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
95546             var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
95547                 factory.createModifiersFromModifierFlags(256 /* Async */) :
95548                 undefined;
95549             var moduleObject = factory.createObjectLiteralExpression([
95550                 factory.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
95551                 factory.createPropertyAssignment("execute", factory.createFunctionExpression(modifiers, 
95552                 /*asteriskToken*/ undefined, 
95553                 /*name*/ undefined, 
95554                 /*typeParameters*/ undefined, 
95555                 /*parameters*/ [], 
95556                 /*type*/ undefined, factory.createBlock(executeStatements, /*multiLine*/ true)))
95557             ], /*multiLine*/ true);
95558             statements.push(factory.createReturnStatement(moduleObject));
95559             return factory.createBlock(statements, /*multiLine*/ true);
95560         }
95561         /**
95562          * Adds an exportStar function to a statement list if it is needed for the file.
95563          *
95564          * @param statements A statement list.
95565          */
95566         function addExportStarIfNeeded(statements) {
95567             if (!moduleInfo.hasExportStarsToExportValues) {
95568                 return;
95569             }
95570             // when resolving exports local exported entries/indirect exported entries in the module
95571             // should always win over entries with similar names that were added via star exports
95572             // to support this we store names of local/indirect exported entries in a set.
95573             // this set is used to filter names brought by star expors.
95574             // local names set should only be added if we have anything exported
95575             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
95576                 // no exported declarations (export var ...) or export specifiers (export {x})
95577                 // check if we have any non star export declarations.
95578                 var hasExportDeclarationWithExportClause = false;
95579                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
95580                     var externalImport = _a[_i];
95581                     if (externalImport.kind === 267 /* ExportDeclaration */ && externalImport.exportClause) {
95582                         hasExportDeclarationWithExportClause = true;
95583                         break;
95584                     }
95585                 }
95586                 if (!hasExportDeclarationWithExportClause) {
95587                     // we still need to emit exportStar helper
95588                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
95589                     statements.push(exportStarFunction_1);
95590                     return exportStarFunction_1.name;
95591                 }
95592             }
95593             var exportedNames = [];
95594             if (moduleInfo.exportedNames) {
95595                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
95596                     var exportedLocalName = _c[_b];
95597                     if (exportedLocalName.escapedText === "default") {
95598                         continue;
95599                     }
95600                     // write name of exported declaration, i.e 'export var x...'
95601                     exportedNames.push(factory.createPropertyAssignment(factory.createStringLiteralFromNode(exportedLocalName), factory.createTrue()));
95602                 }
95603             }
95604             var exportedNamesStorageRef = factory.createUniqueName("exportedNames");
95605             statements.push(factory.createVariableStatement(
95606             /*modifiers*/ undefined, factory.createVariableDeclarationList([
95607                 factory.createVariableDeclaration(exportedNamesStorageRef, 
95608                 /*exclamationToken*/ undefined, 
95609                 /*type*/ undefined, factory.createObjectLiteralExpression(exportedNames, /*multiline*/ true))
95610             ])));
95611             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
95612             statements.push(exportStarFunction);
95613             return exportStarFunction.name;
95614         }
95615         /**
95616          * Creates an exportStar function for the file, with an optional set of excluded local
95617          * names.
95618          *
95619          * @param localNames An optional reference to an object containing a set of excluded local
95620          * names.
95621          */
95622         function createExportStarFunction(localNames) {
95623             var exportStarFunction = factory.createUniqueName("exportStar");
95624             var m = factory.createIdentifier("m");
95625             var n = factory.createIdentifier("n");
95626             var exports = factory.createIdentifier("exports");
95627             var condition = factory.createStrictInequality(n, factory.createStringLiteral("default"));
95628             if (localNames) {
95629                 condition = factory.createLogicalAnd(condition, factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(localNames, "hasOwnProperty"), 
95630                 /*typeArguments*/ undefined, [n])));
95631             }
95632             return factory.createFunctionDeclaration(
95633             /*decorators*/ undefined, 
95634             /*modifiers*/ undefined, 
95635             /*asteriskToken*/ undefined, exportStarFunction, 
95636             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
95637             /*type*/ undefined, factory.createBlock([
95638                 factory.createVariableStatement(
95639                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
95640                     factory.createVariableDeclaration(exports, 
95641                     /*exclamationToken*/ undefined, 
95642                     /*type*/ undefined, factory.createObjectLiteralExpression([]))
95643                 ])),
95644                 factory.createForInStatement(factory.createVariableDeclarationList([
95645                     factory.createVariableDeclaration(n)
95646                 ]), m, factory.createBlock([
95647                     ts.setEmitFlags(factory.createIfStatement(condition, factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(exports, n), factory.createElementAccessExpression(m, n)))), 1 /* SingleLine */)
95648                 ])),
95649                 factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
95650                 /*typeArguments*/ undefined, [exports]))
95651             ], /*multiline*/ true));
95652         }
95653         /**
95654          * Creates an array setter callbacks for each dependency group.
95655          *
95656          * @param exportStarFunction A reference to an exportStarFunction for the file.
95657          * @param dependencyGroups An array of grouped dependencies.
95658          */
95659         function createSettersArray(exportStarFunction, dependencyGroups) {
95660             var setters = [];
95661             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
95662                 var group_2 = dependencyGroups_1[_i];
95663                 // derive a unique name for parameter from the first named entry in the group
95664                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(factory, i, currentSourceFile); });
95665                 var parameterName = localName ? factory.getGeneratedNameForNode(localName) : factory.createUniqueName("");
95666                 var statements = [];
95667                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
95668                     var entry = _b[_a];
95669                     var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217
95670                     switch (entry.kind) {
95671                         case 261 /* ImportDeclaration */:
95672                             if (!entry.importClause) {
95673                                 // 'import "..."' case
95674                                 // module is imported only for side-effects, no emit required
95675                                 break;
95676                             }
95677                         // falls through
95678                         case 260 /* ImportEqualsDeclaration */:
95679                             ts.Debug.assert(importVariableName !== undefined);
95680                             // save import into the local
95681                             statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName)));
95682                             break;
95683                         case 267 /* ExportDeclaration */:
95684                             ts.Debug.assert(importVariableName !== undefined);
95685                             if (entry.exportClause) {
95686                                 if (ts.isNamedExports(entry.exportClause)) {
95687                                     //  export {a, b as c} from 'foo'
95688                                     //
95689                                     // emit as:
95690                                     //
95691                                     //  exports_({
95692                                     //     "a": _["a"],
95693                                     //     "c": _["b"]
95694                                     //  });
95695                                     var properties = [];
95696                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
95697                                         var e = _d[_c];
95698                                         properties.push(factory.createPropertyAssignment(factory.createStringLiteral(ts.idText(e.name)), factory.createElementAccessExpression(parameterName, factory.createStringLiteral(ts.idText(e.propertyName || e.name)))));
95699                                     }
95700                                     statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
95701                                     /*typeArguments*/ undefined, [factory.createObjectLiteralExpression(properties, /*multiline*/ true)])));
95702                                 }
95703                                 else {
95704                                     statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
95705                                     /*typeArguments*/ undefined, [
95706                                         factory.createStringLiteral(ts.idText(entry.exportClause.name)),
95707                                         parameterName
95708                                     ])));
95709                                 }
95710                             }
95711                             else {
95712                                 //  export * from 'foo'
95713                                 //
95714                                 // emit as:
95715                                 //
95716                                 //  exportStar(foo_1_1);
95717                                 statements.push(factory.createExpressionStatement(factory.createCallExpression(exportStarFunction, 
95718                                 /*typeArguments*/ undefined, [parameterName])));
95719                             }
95720                             break;
95721                     }
95722                 }
95723                 setters.push(factory.createFunctionExpression(
95724                 /*modifiers*/ undefined, 
95725                 /*asteriskToken*/ undefined, 
95726                 /*name*/ undefined, 
95727                 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
95728                 /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true)));
95729             }
95730             return factory.createArrayLiteralExpression(setters, /*multiLine*/ true);
95731         }
95732         //
95733         // Top-level Source Element Visitors
95734         //
95735         /**
95736          * Visit source elements at the top-level of a module.
95737          *
95738          * @param node The node to visit.
95739          */
95740         function sourceElementVisitor(node) {
95741             switch (node.kind) {
95742                 case 261 /* ImportDeclaration */:
95743                     return visitImportDeclaration(node);
95744                 case 260 /* ImportEqualsDeclaration */:
95745                     return visitImportEqualsDeclaration(node);
95746                 case 267 /* ExportDeclaration */:
95747                     return visitExportDeclaration(node);
95748                 case 266 /* ExportAssignment */:
95749                     return visitExportAssignment(node);
95750                 default:
95751                     return nestedElementVisitor(node);
95752             }
95753         }
95754         /**
95755          * Visits an ImportDeclaration node.
95756          *
95757          * @param node The node to visit.
95758          */
95759         function visitImportDeclaration(node) {
95760             var statements;
95761             if (node.importClause) {
95762                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
95763             }
95764             if (hasAssociatedEndOfDeclarationMarker(node)) {
95765                 // Defer exports until we encounter an EndOfDeclarationMarker node
95766                 var id = ts.getOriginalNodeId(node);
95767                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
95768             }
95769             else {
95770                 statements = appendExportsOfImportDeclaration(statements, node);
95771             }
95772             return ts.singleOrMany(statements);
95773         }
95774         function visitExportDeclaration(node) {
95775             ts.Debug.assertIsDefined(node);
95776             return undefined;
95777         }
95778         /**
95779          * Visits an ImportEqualsDeclaration node.
95780          *
95781          * @param node The node to visit.
95782          */
95783         function visitImportEqualsDeclaration(node) {
95784             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
95785             var statements;
95786             hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
95787             if (hasAssociatedEndOfDeclarationMarker(node)) {
95788                 // Defer exports until we encounter an EndOfDeclarationMarker node
95789                 var id = ts.getOriginalNodeId(node);
95790                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
95791             }
95792             else {
95793                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
95794             }
95795             return ts.singleOrMany(statements);
95796         }
95797         /**
95798          * Visits an ExportAssignment node.
95799          *
95800          * @param node The node to visit.
95801          */
95802         function visitExportAssignment(node) {
95803             if (node.isExportEquals) {
95804                 // Elide `export=` as it is illegal in a SystemJS module.
95805                 return undefined;
95806             }
95807             var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
95808             var original = node.original;
95809             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
95810                 // Defer exports until we encounter an EndOfDeclarationMarker node
95811                 var id = ts.getOriginalNodeId(node);
95812                 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), expression, /*allowComments*/ true);
95813             }
95814             else {
95815                 return createExportStatement(factory.createIdentifier("default"), expression, /*allowComments*/ true);
95816             }
95817         }
95818         /**
95819          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
95820          *
95821          * @param node The node to visit.
95822          */
95823         function visitFunctionDeclaration(node) {
95824             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
95825                 hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
95826                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
95827                 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
95828             }
95829             else {
95830                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
95831             }
95832             if (hasAssociatedEndOfDeclarationMarker(node)) {
95833                 // Defer exports until we encounter an EndOfDeclarationMarker node
95834                 var id = ts.getOriginalNodeId(node);
95835                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
95836             }
95837             else {
95838                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
95839             }
95840             return undefined;
95841         }
95842         /**
95843          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
95844          *
95845          * @param node The node to visit.
95846          */
95847         function visitClassDeclaration(node) {
95848             var statements;
95849             // Hoist the name of the class declaration to the outer module body function.
95850             var name = factory.getLocalName(node);
95851             hoistVariableDeclaration(name);
95852             // Rewrite the class declaration into an assignment of a class expression.
95853             statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, destructuringAndImportCallVisitor, ts.isDecorator), 
95854             /*modifiers*/ undefined, node.name, 
95855             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
95856             if (hasAssociatedEndOfDeclarationMarker(node)) {
95857                 // Defer exports until we encounter an EndOfDeclarationMarker node
95858                 var id = ts.getOriginalNodeId(node);
95859                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
95860             }
95861             else {
95862                 statements = appendExportsOfHoistedDeclaration(statements, node);
95863             }
95864             return ts.singleOrMany(statements);
95865         }
95866         /**
95867          * Visits a variable statement, hoisting declared names to the top-level module body.
95868          * Each declaration is rewritten into an assignment expression.
95869          *
95870          * @param node The node to visit.
95871          */
95872         function visitVariableStatement(node) {
95873             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
95874                 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
95875             }
95876             var expressions;
95877             var isExportedDeclaration = ts.hasSyntacticModifier(node, 1 /* Export */);
95878             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
95879             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
95880                 var variable = _a[_i];
95881                 if (variable.initializer) {
95882                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
95883                 }
95884                 else {
95885                     hoistBindingElement(variable);
95886                 }
95887             }
95888             var statements;
95889             if (expressions) {
95890                 statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node));
95891             }
95892             if (isMarkedDeclaration) {
95893                 // Defer exports until we encounter an EndOfDeclarationMarker node
95894                 var id = ts.getOriginalNodeId(node);
95895                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
95896             }
95897             else {
95898                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
95899             }
95900             return ts.singleOrMany(statements);
95901         }
95902         /**
95903          * Hoists the declared names of a VariableDeclaration or BindingElement.
95904          *
95905          * @param node The declaration to hoist.
95906          */
95907         function hoistBindingElement(node) {
95908             if (ts.isBindingPattern(node.name)) {
95909                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
95910                     var element = _a[_i];
95911                     if (!ts.isOmittedExpression(element)) {
95912                         hoistBindingElement(element);
95913                     }
95914                 }
95915             }
95916             else {
95917                 hoistVariableDeclaration(factory.cloneNode(node.name));
95918             }
95919         }
95920         /**
95921          * Determines whether a VariableDeclarationList should be hoisted.
95922          *
95923          * @param node The node to test.
95924          */
95925         function shouldHoistVariableDeclarationList(node) {
95926             // hoist only non-block scoped declarations or block scoped declarations parented by source file
95927             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
95928                 && (enclosingBlockScopedContainer.kind === 297 /* SourceFile */
95929                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
95930         }
95931         /**
95932          * Transform an initialized variable declaration into an expression.
95933          *
95934          * @param node The node to transform.
95935          * @param isExportedDeclaration A value indicating whether the variable is exported.
95936          */
95937         function transformInitializedVariable(node, isExportedDeclaration) {
95938             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
95939             return ts.isBindingPattern(node.name)
95940                 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
95941                 /*needsValue*/ false, createAssignment)
95942                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
95943         }
95944         /**
95945          * Creates an assignment expression for an exported variable declaration.
95946          *
95947          * @param name The name of the variable.
95948          * @param value The value of the variable's initializer.
95949          * @param location The source map location for the assignment.
95950          */
95951         function createExportedVariableAssignment(name, value, location) {
95952             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
95953         }
95954         /**
95955          * Creates an assignment expression for a non-exported variable declaration.
95956          *
95957          * @param name The name of the variable.
95958          * @param value The value of the variable's initializer.
95959          * @param location The source map location for the assignment.
95960          */
95961         function createNonExportedVariableAssignment(name, value, location) {
95962             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
95963         }
95964         /**
95965          * Creates an assignment expression for a variable declaration.
95966          *
95967          * @param name The name of the variable.
95968          * @param value The value of the variable's initializer.
95969          * @param location The source map location for the assignment.
95970          * @param isExportedDeclaration A value indicating whether the variable is exported.
95971          */
95972         function createVariableAssignment(name, value, location, isExportedDeclaration) {
95973             hoistVariableDeclaration(factory.cloneNode(name));
95974             return isExportedDeclaration
95975                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location)))
95976                 : preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location));
95977         }
95978         /**
95979          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
95980          * and transformed declaration.
95981          *
95982          * @param node The node to visit.
95983          */
95984         function visitMergeDeclarationMarker(node) {
95985             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
95986             // declaration we do not emit a leading variable declaration. To preserve the
95987             // begin/end semantics of the declararation and to properly handle exports
95988             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
95989             //
95990             // To balance the declaration, we defer the exports of the elided variable
95991             // statement until we visit this declaration's `EndOfDeclarationMarker`.
95992             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) {
95993                 var id = ts.getOriginalNodeId(node);
95994                 var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */);
95995                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
95996             }
95997             return node;
95998         }
95999         /**
96000          * Determines whether a node has an associated EndOfDeclarationMarker.
96001          *
96002          * @param node The node to test.
96003          */
96004         function hasAssociatedEndOfDeclarationMarker(node) {
96005             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
96006         }
96007         /**
96008          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
96009          * declaration.
96010          *
96011          * @param node The node to visit.
96012          */
96013         function visitEndOfDeclarationMarker(node) {
96014             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
96015             // end of the transformed declaration. We use this marker to emit any deferred exports
96016             // of the declaration.
96017             var id = ts.getOriginalNodeId(node);
96018             var statements = deferredExports[id];
96019             if (statements) {
96020                 delete deferredExports[id];
96021                 return ts.append(statements, node);
96022             }
96023             else {
96024                 var original = ts.getOriginalNode(node);
96025                 if (ts.isModuleOrEnumDeclaration(original)) {
96026                     return ts.append(appendExportsOfDeclaration(statements, original), node);
96027                 }
96028             }
96029             return node;
96030         }
96031         /**
96032          * Appends the exports of an ImportDeclaration to a statement list, returning the
96033          * statement list.
96034          *
96035          * @param statements A statement list to which the down-level export statements are to be
96036          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96037          * appended.
96038          * @param decl The declaration whose exports are to be recorded.
96039          */
96040         function appendExportsOfImportDeclaration(statements, decl) {
96041             if (moduleInfo.exportEquals) {
96042                 return statements;
96043             }
96044             var importClause = decl.importClause;
96045             if (!importClause) {
96046                 return statements;
96047             }
96048             if (importClause.name) {
96049                 statements = appendExportsOfDeclaration(statements, importClause);
96050             }
96051             var namedBindings = importClause.namedBindings;
96052             if (namedBindings) {
96053                 switch (namedBindings.kind) {
96054                     case 263 /* NamespaceImport */:
96055                         statements = appendExportsOfDeclaration(statements, namedBindings);
96056                         break;
96057                     case 264 /* NamedImports */:
96058                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
96059                             var importBinding = _a[_i];
96060                             statements = appendExportsOfDeclaration(statements, importBinding);
96061                         }
96062                         break;
96063                 }
96064             }
96065             return statements;
96066         }
96067         /**
96068          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
96069          * statement list.
96070          *
96071          * @param statements A statement list to which the down-level export statements are to be
96072          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96073          * appended.
96074          * @param decl The declaration whose exports are to be recorded.
96075          */
96076         function appendExportsOfImportEqualsDeclaration(statements, decl) {
96077             if (moduleInfo.exportEquals) {
96078                 return statements;
96079             }
96080             return appendExportsOfDeclaration(statements, decl);
96081         }
96082         /**
96083          * Appends the exports of a VariableStatement to a statement list, returning the statement
96084          * list.
96085          *
96086          * @param statements A statement list to which the down-level export statements are to be
96087          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96088          * appended.
96089          * @param node The VariableStatement whose exports are to be recorded.
96090          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
96091          * `nodes` declaration list.
96092          */
96093         function appendExportsOfVariableStatement(statements, node, exportSelf) {
96094             if (moduleInfo.exportEquals) {
96095                 return statements;
96096             }
96097             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
96098                 var decl = _a[_i];
96099                 if (decl.initializer || exportSelf) {
96100                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
96101                 }
96102             }
96103             return statements;
96104         }
96105         /**
96106          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
96107          * returning the statement list.
96108          *
96109          * @param statements A statement list to which the down-level export statements are to be
96110          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96111          * appended.
96112          * @param decl The declaration whose exports are to be recorded.
96113          * @param exportSelf A value indicating whether to also export the declaration itself.
96114          */
96115         function appendExportsOfBindingElement(statements, decl, exportSelf) {
96116             if (moduleInfo.exportEquals) {
96117                 return statements;
96118             }
96119             if (ts.isBindingPattern(decl.name)) {
96120                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
96121                     var element = _a[_i];
96122                     if (!ts.isOmittedExpression(element)) {
96123                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
96124                     }
96125                 }
96126             }
96127             else if (!ts.isGeneratedIdentifier(decl.name)) {
96128                 var excludeName = void 0;
96129                 if (exportSelf) {
96130                     statements = appendExportStatement(statements, decl.name, factory.getLocalName(decl));
96131                     excludeName = ts.idText(decl.name);
96132                 }
96133                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
96134             }
96135             return statements;
96136         }
96137         /**
96138          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
96139          * returning the statement list.
96140          *
96141          * @param statements A statement list to which the down-level export statements are to be
96142          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96143          * appended.
96144          * @param decl The declaration whose exports are to be recorded.
96145          */
96146         function appendExportsOfHoistedDeclaration(statements, decl) {
96147             if (moduleInfo.exportEquals) {
96148                 return statements;
96149             }
96150             var excludeName;
96151             if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
96152                 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createStringLiteral("default") : decl.name;
96153                 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl));
96154                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
96155             }
96156             if (decl.name) {
96157                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
96158             }
96159             return statements;
96160         }
96161         /**
96162          * Appends the exports of a declaration to a statement list, returning the statement list.
96163          *
96164          * @param statements A statement list to which the down-level export statements are to be
96165          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96166          * appended.
96167          * @param decl The declaration to export.
96168          * @param excludeName An optional name to exclude from exports.
96169          */
96170         function appendExportsOfDeclaration(statements, decl, excludeName) {
96171             if (moduleInfo.exportEquals) {
96172                 return statements;
96173             }
96174             var name = factory.getDeclarationName(decl);
96175             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
96176             if (exportSpecifiers) {
96177                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
96178                     var exportSpecifier = exportSpecifiers_2[_i];
96179                     if (exportSpecifier.name.escapedText !== excludeName) {
96180                         statements = appendExportStatement(statements, exportSpecifier.name, name);
96181                     }
96182                 }
96183             }
96184             return statements;
96185         }
96186         /**
96187          * Appends the down-level representation of an export to a statement list, returning the
96188          * statement list.
96189          *
96190          * @param statements A statement list to which the down-level export statements are to be
96191          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96192          * appended.
96193          * @param exportName The name of the export.
96194          * @param expression The expression to export.
96195          * @param allowComments Whether to allow comments on the export.
96196          */
96197         function appendExportStatement(statements, exportName, expression, allowComments) {
96198             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
96199             return statements;
96200         }
96201         /**
96202          * Creates a call to the current file's export function to export a value.
96203          *
96204          * @param name The bound name of the export.
96205          * @param value The exported value.
96206          * @param allowComments An optional value indicating whether to emit comments for the statement.
96207          */
96208         function createExportStatement(name, value, allowComments) {
96209             var statement = factory.createExpressionStatement(createExportExpression(name, value));
96210             ts.startOnNewLine(statement);
96211             if (!allowComments) {
96212                 ts.setEmitFlags(statement, 1536 /* NoComments */);
96213             }
96214             return statement;
96215         }
96216         /**
96217          * Creates a call to the current file's export function to export a value.
96218          *
96219          * @param name The bound name of the export.
96220          * @param value The exported value.
96221          */
96222         function createExportExpression(name, value) {
96223             var exportName = ts.isIdentifier(name) ? factory.createStringLiteralFromNode(name) : name;
96224             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
96225             return ts.setCommentRange(factory.createCallExpression(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
96226         }
96227         //
96228         // Top-Level or Nested Source Element Visitors
96229         //
96230         /**
96231          * Visit nested elements at the top-level of a module.
96232          *
96233          * @param node The node to visit.
96234          */
96235         function nestedElementVisitor(node) {
96236             switch (node.kind) {
96237                 case 232 /* VariableStatement */:
96238                     return visitVariableStatement(node);
96239                 case 251 /* FunctionDeclaration */:
96240                     return visitFunctionDeclaration(node);
96241                 case 252 /* ClassDeclaration */:
96242                     return visitClassDeclaration(node);
96243                 case 237 /* ForStatement */:
96244                     return visitForStatement(node);
96245                 case 238 /* ForInStatement */:
96246                     return visitForInStatement(node);
96247                 case 239 /* ForOfStatement */:
96248                     return visitForOfStatement(node);
96249                 case 235 /* DoStatement */:
96250                     return visitDoStatement(node);
96251                 case 236 /* WhileStatement */:
96252                     return visitWhileStatement(node);
96253                 case 245 /* LabeledStatement */:
96254                     return visitLabeledStatement(node);
96255                 case 243 /* WithStatement */:
96256                     return visitWithStatement(node);
96257                 case 244 /* SwitchStatement */:
96258                     return visitSwitchStatement(node);
96259                 case 258 /* CaseBlock */:
96260                     return visitCaseBlock(node);
96261                 case 284 /* CaseClause */:
96262                     return visitCaseClause(node);
96263                 case 285 /* DefaultClause */:
96264                     return visitDefaultClause(node);
96265                 case 247 /* TryStatement */:
96266                     return visitTryStatement(node);
96267                 case 287 /* CatchClause */:
96268                     return visitCatchClause(node);
96269                 case 230 /* Block */:
96270                     return visitBlock(node);
96271                 case 338 /* MergeDeclarationMarker */:
96272                     return visitMergeDeclarationMarker(node);
96273                 case 339 /* EndOfDeclarationMarker */:
96274                     return visitEndOfDeclarationMarker(node);
96275                 default:
96276                     return destructuringAndImportCallVisitor(node);
96277             }
96278         }
96279         /**
96280          * Visits the body of a ForStatement to hoist declarations.
96281          *
96282          * @param node The node to visit.
96283          */
96284         function visitForStatement(node) {
96285             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96286             enclosingBlockScopedContainer = node;
96287             node = factory.updateForStatement(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));
96288             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96289             return node;
96290         }
96291         /**
96292          * Visits the body of a ForInStatement to hoist declarations.
96293          *
96294          * @param node The node to visit.
96295          */
96296         function visitForInStatement(node) {
96297             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96298             enclosingBlockScopedContainer = node;
96299             node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96300             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96301             return node;
96302         }
96303         /**
96304          * Visits the body of a ForOfStatement to hoist declarations.
96305          *
96306          * @param node The node to visit.
96307          */
96308         function visitForOfStatement(node) {
96309             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96310             enclosingBlockScopedContainer = node;
96311             node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96312             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96313             return node;
96314         }
96315         /**
96316          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
96317          * ForOfStatement.
96318          *
96319          * @param node The node to test.
96320          */
96321         function shouldHoistForInitializer(node) {
96322             return ts.isVariableDeclarationList(node)
96323                 && shouldHoistVariableDeclarationList(node);
96324         }
96325         /**
96326          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
96327          *
96328          * @param node The node to visit.
96329          */
96330         function visitForInitializer(node) {
96331             if (shouldHoistForInitializer(node)) {
96332                 var expressions = void 0;
96333                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
96334                     var variable = _a[_i];
96335                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
96336                     if (!variable.initializer) {
96337                         hoistBindingElement(variable);
96338                     }
96339                 }
96340                 return expressions ? factory.inlineExpressions(expressions) : factory.createOmittedExpression();
96341             }
96342             else {
96343                 return ts.visitEachChild(node, nestedElementVisitor, context);
96344             }
96345         }
96346         /**
96347          * Visits the body of a DoStatement to hoist declarations.
96348          *
96349          * @param node The node to visit.
96350          */
96351         function visitDoStatement(node) {
96352             return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
96353         }
96354         /**
96355          * Visits the body of a WhileStatement to hoist declarations.
96356          *
96357          * @param node The node to visit.
96358          */
96359         function visitWhileStatement(node) {
96360             return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96361         }
96362         /**
96363          * Visits the body of a LabeledStatement to hoist declarations.
96364          *
96365          * @param node The node to visit.
96366          */
96367         function visitLabeledStatement(node) {
96368             return factory.updateLabeledStatement(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96369         }
96370         /**
96371          * Visits the body of a WithStatement to hoist declarations.
96372          *
96373          * @param node The node to visit.
96374          */
96375         function visitWithStatement(node) {
96376             return factory.updateWithStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96377         }
96378         /**
96379          * Visits the body of a SwitchStatement to hoist declarations.
96380          *
96381          * @param node The node to visit.
96382          */
96383         function visitSwitchStatement(node) {
96384             return factory.updateSwitchStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
96385         }
96386         /**
96387          * Visits the body of a CaseBlock to hoist declarations.
96388          *
96389          * @param node The node to visit.
96390          */
96391         function visitCaseBlock(node) {
96392             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96393             enclosingBlockScopedContainer = node;
96394             node = factory.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
96395             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96396             return node;
96397         }
96398         /**
96399          * Visits the body of a CaseClause to hoist declarations.
96400          *
96401          * @param node The node to visit.
96402          */
96403         function visitCaseClause(node) {
96404             return factory.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
96405         }
96406         /**
96407          * Visits the body of a DefaultClause to hoist declarations.
96408          *
96409          * @param node The node to visit.
96410          */
96411         function visitDefaultClause(node) {
96412             return ts.visitEachChild(node, nestedElementVisitor, context);
96413         }
96414         /**
96415          * Visits the body of a TryStatement to hoist declarations.
96416          *
96417          * @param node The node to visit.
96418          */
96419         function visitTryStatement(node) {
96420             return ts.visitEachChild(node, nestedElementVisitor, context);
96421         }
96422         /**
96423          * Visits the body of a CatchClause to hoist declarations.
96424          *
96425          * @param node The node to visit.
96426          */
96427         function visitCatchClause(node) {
96428             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96429             enclosingBlockScopedContainer = node;
96430             node = factory.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
96431             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96432             return node;
96433         }
96434         /**
96435          * Visits the body of a Block to hoist declarations.
96436          *
96437          * @param node The node to visit.
96438          */
96439         function visitBlock(node) {
96440             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96441             enclosingBlockScopedContainer = node;
96442             node = ts.visitEachChild(node, nestedElementVisitor, context);
96443             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96444             return node;
96445         }
96446         //
96447         // Destructuring Assignment Visitors
96448         //
96449         /**
96450          * Visit nodes to flatten destructuring assignments to exported symbols.
96451          *
96452          * @param node The node to visit.
96453          */
96454         function destructuringAndImportCallVisitor(node) {
96455             if (ts.isDestructuringAssignment(node)) {
96456                 return visitDestructuringAssignment(node);
96457             }
96458             else if (ts.isImportCall(node)) {
96459                 return visitImportCallExpression(node);
96460             }
96461             else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
96462                 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
96463             }
96464             else {
96465                 return node;
96466             }
96467         }
96468         function visitImportCallExpression(node) {
96469             // import("./blah")
96470             // emit as
96471             // System.register([], function (_export, _context) {
96472             //     return {
96473             //         setters: [],
96474             //         execute: () => {
96475             //             _context.import('./blah');
96476             //         }
96477             //     };
96478             // });
96479             return factory.createCallExpression(factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("import")), 
96480             /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
96481         }
96482         /**
96483          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
96484          *
96485          * @param node The node to visit.
96486          */
96487         function visitDestructuringAssignment(node) {
96488             if (hasExportedReferenceInDestructuringTarget(node.left)) {
96489                 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
96490                 /*needsValue*/ true);
96491             }
96492             return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
96493         }
96494         /**
96495          * Determines whether the target of a destructuring assigment refers to an exported symbol.
96496          *
96497          * @param node The destructuring target.
96498          */
96499         function hasExportedReferenceInDestructuringTarget(node) {
96500             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
96501                 return hasExportedReferenceInDestructuringTarget(node.left);
96502             }
96503             else if (ts.isSpreadElement(node)) {
96504                 return hasExportedReferenceInDestructuringTarget(node.expression);
96505             }
96506             else if (ts.isObjectLiteralExpression(node)) {
96507                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
96508             }
96509             else if (ts.isArrayLiteralExpression(node)) {
96510                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
96511             }
96512             else if (ts.isShorthandPropertyAssignment(node)) {
96513                 return hasExportedReferenceInDestructuringTarget(node.name);
96514             }
96515             else if (ts.isPropertyAssignment(node)) {
96516                 return hasExportedReferenceInDestructuringTarget(node.initializer);
96517             }
96518             else if (ts.isIdentifier(node)) {
96519                 var container = resolver.getReferencedExportContainer(node);
96520                 return container !== undefined && container.kind === 297 /* SourceFile */;
96521             }
96522             else {
96523                 return false;
96524             }
96525         }
96526         //
96527         // Modifier Visitors
96528         //
96529         /**
96530          * Visit nodes to elide module-specific modifiers.
96531          *
96532          * @param node The node to visit.
96533          */
96534         function modifierVisitor(node) {
96535             switch (node.kind) {
96536                 case 92 /* ExportKeyword */:
96537                 case 87 /* DefaultKeyword */:
96538                     return undefined;
96539             }
96540             return node;
96541         }
96542         //
96543         // Emit Notification
96544         //
96545         /**
96546          * Hook for node emit notifications.
96547          *
96548          * @param hint A hint as to the intended usage of the node.
96549          * @param node The node to emit.
96550          * @param emitCallback A callback used to emit the node in the printer.
96551          */
96552         function onEmitNode(hint, node, emitCallback) {
96553             if (node.kind === 297 /* SourceFile */) {
96554                 var id = ts.getOriginalNodeId(node);
96555                 currentSourceFile = node;
96556                 moduleInfo = moduleInfoMap[id];
96557                 exportFunction = exportFunctionsMap[id];
96558                 noSubstitution = noSubstitutionMap[id];
96559                 contextObject = contextObjectMap[id];
96560                 if (noSubstitution) {
96561                     delete noSubstitutionMap[id];
96562                 }
96563                 previousOnEmitNode(hint, node, emitCallback);
96564                 currentSourceFile = undefined;
96565                 moduleInfo = undefined;
96566                 exportFunction = undefined;
96567                 contextObject = undefined;
96568                 noSubstitution = undefined;
96569             }
96570             else {
96571                 previousOnEmitNode(hint, node, emitCallback);
96572             }
96573         }
96574         //
96575         // Substitutions
96576         //
96577         /**
96578          * Hooks node substitutions.
96579          *
96580          * @param hint A hint as to the intended usage of the node.
96581          * @param node The node to substitute.
96582          */
96583         function onSubstituteNode(hint, node) {
96584             node = previousOnSubstituteNode(hint, node);
96585             if (isSubstitutionPrevented(node)) {
96586                 return node;
96587             }
96588             if (hint === 1 /* Expression */) {
96589                 return substituteExpression(node);
96590             }
96591             else if (hint === 4 /* Unspecified */) {
96592                 return substituteUnspecified(node);
96593             }
96594             return node;
96595         }
96596         /**
96597          * Substitute the node, if necessary.
96598          *
96599          * @param node The node to substitute.
96600          */
96601         function substituteUnspecified(node) {
96602             switch (node.kind) {
96603                 case 289 /* ShorthandPropertyAssignment */:
96604                     return substituteShorthandPropertyAssignment(node);
96605             }
96606             return node;
96607         }
96608         /**
96609          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
96610          *
96611          * @param node The node to substitute.
96612          */
96613         function substituteShorthandPropertyAssignment(node) {
96614             var name = node.name;
96615             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
96616                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
96617                 if (importDeclaration) {
96618                     if (ts.isImportClause(importDeclaration)) {
96619                         return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default"))), 
96620                         /*location*/ node);
96621                     }
96622                     else if (ts.isImportSpecifier(importDeclaration)) {
96623                         return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name))), 
96624                         /*location*/ node);
96625                     }
96626                 }
96627             }
96628             return node;
96629         }
96630         /**
96631          * Substitute the expression, if necessary.
96632          *
96633          * @param node The node to substitute.
96634          */
96635         function substituteExpression(node) {
96636             switch (node.kind) {
96637                 case 78 /* Identifier */:
96638                     return substituteExpressionIdentifier(node);
96639                 case 216 /* BinaryExpression */:
96640                     return substituteBinaryExpression(node);
96641                 case 214 /* PrefixUnaryExpression */:
96642                 case 215 /* PostfixUnaryExpression */:
96643                     return substituteUnaryExpression(node);
96644                 case 226 /* MetaProperty */:
96645                     return substituteMetaProperty(node);
96646             }
96647             return node;
96648         }
96649         /**
96650          * Substitution for an Identifier expression that may contain an imported or exported symbol.
96651          *
96652          * @param node The node to substitute.
96653          */
96654         function substituteExpressionIdentifier(node) {
96655             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
96656                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
96657                 if (externalHelpersModuleName) {
96658                     return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
96659                 }
96660                 return node;
96661             }
96662             // When we see an identifier in an expression position that
96663             // points to an imported symbol, we should substitute a qualified
96664             // reference to the imported symbol if one is needed.
96665             //
96666             // - We do not substitute generated identifiers for any reason.
96667             // - We do not substitute identifiers tagged with the LocalName flag.
96668             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
96669                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
96670                 if (importDeclaration) {
96671                     if (ts.isImportClause(importDeclaration)) {
96672                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), 
96673                         /*location*/ node);
96674                     }
96675                     else if (ts.isImportSpecifier(importDeclaration)) {
96676                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name)), 
96677                         /*location*/ node);
96678                     }
96679                 }
96680             }
96681             return node;
96682         }
96683         /**
96684          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
96685          *
96686          * @param node The node to substitute.
96687          */
96688         function substituteBinaryExpression(node) {
96689             // When we see an assignment expression whose left-hand side is an exported symbol,
96690             // we should ensure all exports of that symbol are updated with the correct value.
96691             //
96692             // - We do not substitute generated identifiers for any reason.
96693             // - We do not substitute identifiers tagged with the LocalName flag.
96694             // - We do not substitute identifiers that were originally the name of an enum or
96695             //   namespace due to how they are transformed in TypeScript.
96696             // - We only substitute identifiers that are exported at the top level.
96697             if (ts.isAssignmentOperator(node.operatorToken.kind)
96698                 && ts.isIdentifier(node.left)
96699                 && !ts.isGeneratedIdentifier(node.left)
96700                 && !ts.isLocalName(node.left)
96701                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
96702                 var exportedNames = getExports(node.left);
96703                 if (exportedNames) {
96704                     // For each additional export of the declaration, apply an export assignment.
96705                     var expression = node;
96706                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
96707                         var exportName = exportedNames_4[_i];
96708                         expression = createExportExpression(exportName, preventSubstitution(expression));
96709                     }
96710                     return expression;
96711                 }
96712             }
96713             return node;
96714         }
96715         /**
96716          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
96717          *
96718          * @param node The node to substitute.
96719          */
96720         function substituteUnaryExpression(node) {
96721             // When we see a prefix or postfix increment expression whose operand is an exported
96722             // symbol, we should ensure all exports of that symbol are updated with the correct
96723             // value.
96724             //
96725             // - We do not substitute generated identifiers for any reason.
96726             // - We do not substitute identifiers tagged with the LocalName flag.
96727             // - We do not substitute identifiers that were originally the name of an enum or
96728             //   namespace due to how they are transformed in TypeScript.
96729             // - We only substitute identifiers that are exported at the top level.
96730             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
96731                 && ts.isIdentifier(node.operand)
96732                 && !ts.isGeneratedIdentifier(node.operand)
96733                 && !ts.isLocalName(node.operand)
96734                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
96735                 var exportedNames = getExports(node.operand);
96736                 if (exportedNames) {
96737                     var expression = node.kind === 215 /* PostfixUnaryExpression */
96738                         ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node)
96739                         : node;
96740                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
96741                         var exportName = exportedNames_5[_i];
96742                         expression = createExportExpression(exportName, preventSubstitution(expression));
96743                     }
96744                     if (node.kind === 215 /* PostfixUnaryExpression */) {
96745                         expression = node.operator === 45 /* PlusPlusToken */
96746                             ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1))
96747                             : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1));
96748                     }
96749                     return expression;
96750                 }
96751             }
96752             return node;
96753         }
96754         function substituteMetaProperty(node) {
96755             if (ts.isImportMeta(node)) {
96756                 return factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("meta"));
96757             }
96758             return node;
96759         }
96760         /**
96761          * Gets the exports of a name.
96762          *
96763          * @param name The name.
96764          */
96765         function getExports(name) {
96766             var exportedNames;
96767             if (!ts.isGeneratedIdentifier(name)) {
96768                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
96769                     || resolver.getReferencedValueDeclaration(name);
96770                 if (valueDeclaration) {
96771                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
96772                     if (exportContainer && exportContainer.kind === 297 /* SourceFile */) {
96773                         exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration));
96774                     }
96775                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
96776                 }
96777             }
96778             return exportedNames;
96779         }
96780         /**
96781          * Prevent substitution of a node for this transformer.
96782          *
96783          * @param node The node which should not be substituted.
96784          */
96785         function preventSubstitution(node) {
96786             if (noSubstitution === undefined)
96787                 noSubstitution = [];
96788             noSubstitution[ts.getNodeId(node)] = true;
96789             return node;
96790         }
96791         /**
96792          * Determines whether a node should not be substituted.
96793          *
96794          * @param node The node to test.
96795          */
96796         function isSubstitutionPrevented(node) {
96797             return noSubstitution && node.id && noSubstitution[node.id];
96798         }
96799     }
96800     ts.transformSystemModule = transformSystemModule;
96801 })(ts || (ts = {}));
96802 /*@internal*/
96803 var ts;
96804 (function (ts) {
96805     function transformECMAScriptModule(context) {
96806         var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
96807         var compilerOptions = context.getCompilerOptions();
96808         var previousOnEmitNode = context.onEmitNode;
96809         var previousOnSubstituteNode = context.onSubstituteNode;
96810         context.onEmitNode = onEmitNode;
96811         context.onSubstituteNode = onSubstituteNode;
96812         context.enableEmitNotification(297 /* SourceFile */);
96813         context.enableSubstitution(78 /* Identifier */);
96814         var helperNameSubstitutions;
96815         return ts.chainBundle(context, transformSourceFile);
96816         function transformSourceFile(node) {
96817             if (node.isDeclarationFile) {
96818                 return node;
96819             }
96820             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
96821                 var result = updateExternalModule(node);
96822                 if (!ts.isExternalModule(node) || ts.some(result.statements, ts.isExternalModuleIndicator)) {
96823                     return result;
96824                 }
96825                 return factory.updateSourceFile(result, ts.setTextRange(factory.createNodeArray(__spreadArrays(result.statements, [ts.createEmptyExports(factory)])), result.statements));
96826             }
96827             return node;
96828         }
96829         function updateExternalModule(node) {
96830             var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(factory, emitHelpers(), node, compilerOptions);
96831             if (externalHelpersImportDeclaration) {
96832                 var statements = [];
96833                 var statementOffset = factory.copyPrologue(node.statements, statements);
96834                 ts.append(statements, externalHelpersImportDeclaration);
96835                 ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
96836                 return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
96837             }
96838             else {
96839                 return ts.visitEachChild(node, visitor, context);
96840             }
96841         }
96842         function visitor(node) {
96843             switch (node.kind) {
96844                 case 260 /* ImportEqualsDeclaration */:
96845                     // Elide `import=` as it is not legal with --module ES6
96846                     return undefined;
96847                 case 266 /* ExportAssignment */:
96848                     return visitExportAssignment(node);
96849                 case 267 /* ExportDeclaration */:
96850                     var exportDecl = node;
96851                     return visitExportDeclaration(exportDecl);
96852             }
96853             return node;
96854         }
96855         function visitExportAssignment(node) {
96856             // Elide `export=` as it is not legal with --module ES6
96857             return node.isExportEquals ? undefined : node;
96858         }
96859         function visitExportDeclaration(node) {
96860             // `export * as ns` only needs to be transformed in ES2015
96861             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
96862                 return node;
96863             }
96864             // Either ill-formed or don't need to be tranformed.
96865             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
96866                 return node;
96867             }
96868             var oldIdentifier = node.exportClause.name;
96869             var synthName = factory.getGeneratedNameForNode(oldIdentifier);
96870             var importDecl = factory.createImportDeclaration(
96871             /*decorators*/ undefined, 
96872             /*modifiers*/ undefined, factory.createImportClause(
96873             /*isTypeOnly*/ false, 
96874             /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier);
96875             ts.setOriginalNode(importDecl, node.exportClause);
96876             var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration(
96877             /*decorators*/ undefined, 
96878             /*modifiers*/ undefined, 
96879             /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(synthName, oldIdentifier)]));
96880             ts.setOriginalNode(exportDecl, node);
96881             return [importDecl, exportDecl];
96882         }
96883         //
96884         // Emit Notification
96885         //
96886         /**
96887          * Hook for node emit.
96888          *
96889          * @param hint A hint as to the intended usage of the node.
96890          * @param node The node to emit.
96891          * @param emit A callback used to emit the node in the printer.
96892          */
96893         function onEmitNode(hint, node, emitCallback) {
96894             if (ts.isSourceFile(node)) {
96895                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
96896                     helperNameSubstitutions = new ts.Map();
96897                 }
96898                 previousOnEmitNode(hint, node, emitCallback);
96899                 helperNameSubstitutions = undefined;
96900             }
96901             else {
96902                 previousOnEmitNode(hint, node, emitCallback);
96903             }
96904         }
96905         //
96906         // Substitutions
96907         //
96908         /**
96909          * Hooks node substitutions.
96910          *
96911          * @param hint A hint as to the intended usage of the node.
96912          * @param node The node to substitute.
96913          */
96914         function onSubstituteNode(hint, node) {
96915             node = previousOnSubstituteNode(hint, node);
96916             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
96917                 return substituteHelperName(node);
96918             }
96919             return node;
96920         }
96921         function substituteHelperName(node) {
96922             var name = ts.idText(node);
96923             var substitution = helperNameSubstitutions.get(name);
96924             if (!substitution) {
96925                 helperNameSubstitutions.set(name, substitution = factory.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */));
96926             }
96927             return substitution;
96928         }
96929     }
96930     ts.transformECMAScriptModule = transformECMAScriptModule;
96931 })(ts || (ts = {}));
96932 /* @internal */
96933 var ts;
96934 (function (ts) {
96935     function canProduceDiagnostics(node) {
96936         return ts.isVariableDeclaration(node) ||
96937             ts.isPropertyDeclaration(node) ||
96938             ts.isPropertySignature(node) ||
96939             ts.isBindingElement(node) ||
96940             ts.isSetAccessor(node) ||
96941             ts.isGetAccessor(node) ||
96942             ts.isConstructSignatureDeclaration(node) ||
96943             ts.isCallSignatureDeclaration(node) ||
96944             ts.isMethodDeclaration(node) ||
96945             ts.isMethodSignature(node) ||
96946             ts.isFunctionDeclaration(node) ||
96947             ts.isParameter(node) ||
96948             ts.isTypeParameterDeclaration(node) ||
96949             ts.isExpressionWithTypeArguments(node) ||
96950             ts.isImportEqualsDeclaration(node) ||
96951             ts.isTypeAliasDeclaration(node) ||
96952             ts.isConstructorDeclaration(node) ||
96953             ts.isIndexSignatureDeclaration(node) ||
96954             ts.isPropertyAccessExpression(node);
96955     }
96956     ts.canProduceDiagnostics = canProduceDiagnostics;
96957     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
96958         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
96959             return getAccessorNameVisibilityError;
96960         }
96961         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
96962             return getMethodNameVisibilityError;
96963         }
96964         else {
96965             return createGetSymbolAccessibilityDiagnosticForNode(node);
96966         }
96967         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
96968             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
96969             return diagnosticMessage !== undefined ? {
96970                 diagnosticMessage: diagnosticMessage,
96971                 errorNode: node,
96972                 typeName: node.name
96973             } : undefined;
96974         }
96975         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
96976             if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
96977                 return symbolAccessibilityResult.errorModuleName ?
96978                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
96979                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
96980                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
96981                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
96982             }
96983             else if (node.parent.kind === 252 /* ClassDeclaration */) {
96984                 return symbolAccessibilityResult.errorModuleName ?
96985                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
96986                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
96987                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
96988                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
96989             }
96990             else {
96991                 return symbolAccessibilityResult.errorModuleName ?
96992                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
96993                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
96994             }
96995         }
96996         function getMethodNameVisibilityError(symbolAccessibilityResult) {
96997             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
96998             return diagnosticMessage !== undefined ? {
96999                 diagnosticMessage: diagnosticMessage,
97000                 errorNode: node,
97001                 typeName: node.name
97002             } : undefined;
97003         }
97004         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
97005             if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97006                 return symbolAccessibilityResult.errorModuleName ?
97007                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97008                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97009                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
97010                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
97011             }
97012             else if (node.parent.kind === 252 /* ClassDeclaration */) {
97013                 return symbolAccessibilityResult.errorModuleName ?
97014                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97015                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97016                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
97017                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
97018             }
97019             else {
97020                 return symbolAccessibilityResult.errorModuleName ?
97021                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97022                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
97023             }
97024         }
97025     }
97026     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
97027     function createGetSymbolAccessibilityDiagnosticForNode(node) {
97028         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
97029             return getVariableDeclarationTypeVisibilityError;
97030         }
97031         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
97032             return getAccessorDeclarationTypeVisibilityError;
97033         }
97034         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
97035             return getReturnTypeVisibilityError;
97036         }
97037         else if (ts.isParameter(node)) {
97038             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasSyntacticModifier(node.parent, 8 /* Private */)) {
97039                 return getVariableDeclarationTypeVisibilityError;
97040             }
97041             return getParameterDeclarationTypeVisibilityError;
97042         }
97043         else if (ts.isTypeParameterDeclaration(node)) {
97044             return getTypeParameterConstraintVisibilityError;
97045         }
97046         else if (ts.isExpressionWithTypeArguments(node)) {
97047             return getHeritageClauseVisibilityError;
97048         }
97049         else if (ts.isImportEqualsDeclaration(node)) {
97050             return getImportEntityNameVisibilityError;
97051         }
97052         else if (ts.isTypeAliasDeclaration(node)) {
97053             return getTypeAliasDeclarationVisibilityError;
97054         }
97055         else {
97056             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
97057         }
97058         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
97059             if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) {
97060                 return symbolAccessibilityResult.errorModuleName ?
97061                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97062                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97063                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
97064                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
97065             }
97066             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
97067             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
97068             else if (node.kind === 163 /* PropertyDeclaration */ || node.kind === 201 /* PropertyAccessExpression */ || node.kind === 162 /* PropertySignature */ ||
97069                 (node.kind === 160 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) {
97070                 // TODO(jfreeman): Deal with computed properties in error reporting.
97071                 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97072                     return symbolAccessibilityResult.errorModuleName ?
97073                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97074                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97075                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
97076                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
97077                 }
97078                 else if (node.parent.kind === 252 /* ClassDeclaration */ || node.kind === 160 /* Parameter */) {
97079                     return symbolAccessibilityResult.errorModuleName ?
97080                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97081                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97082                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
97083                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
97084                 }
97085                 else {
97086                     // Interfaces cannot have types that cannot be named
97087                     return symbolAccessibilityResult.errorModuleName ?
97088                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97089                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
97090                 }
97091             }
97092         }
97093         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
97094             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
97095             return diagnosticMessage !== undefined ? {
97096                 diagnosticMessage: diagnosticMessage,
97097                 errorNode: node,
97098                 typeName: node.name
97099             } : undefined;
97100         }
97101         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
97102             var diagnosticMessage;
97103             if (node.kind === 168 /* SetAccessor */) {
97104                 // Getters can infer the return type from the returned expression, but setters cannot, so the
97105                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
97106                 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97107                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97108                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97109                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
97110                 }
97111                 else {
97112                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97113                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97114                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
97115                 }
97116             }
97117             else {
97118                 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97119                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97120                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97121                             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 :
97122                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97123                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
97124                 }
97125                 else {
97126                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97127                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97128                             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 :
97129                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97130                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
97131                 }
97132             }
97133             return {
97134                 diagnosticMessage: diagnosticMessage,
97135                 errorNode: node.name,
97136                 typeName: node.name
97137             };
97138         }
97139         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
97140             var diagnosticMessage;
97141             switch (node.kind) {
97142                 case 170 /* ConstructSignature */:
97143                     // Interfaces cannot have return types that cannot be named
97144                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97145                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
97146                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
97147                     break;
97148                 case 169 /* CallSignature */:
97149                     // Interfaces cannot have return types that cannot be named
97150                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97151                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
97152                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
97153                     break;
97154                 case 171 /* IndexSignature */:
97155                     // Interfaces cannot have return types that cannot be named
97156                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97157                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
97158                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
97159                     break;
97160                 case 165 /* MethodDeclaration */:
97161                 case 164 /* MethodSignature */:
97162                     if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97163                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97164                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97165                                 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 :
97166                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
97167                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
97168                     }
97169                     else if (node.parent.kind === 252 /* ClassDeclaration */) {
97170                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97171                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97172                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
97173                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
97174                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
97175                     }
97176                     else {
97177                         // Interfaces cannot have return types that cannot be named
97178                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97179                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
97180                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
97181                     }
97182                     break;
97183                 case 251 /* FunctionDeclaration */:
97184                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97185                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97186                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
97187                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
97188                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
97189                     break;
97190                 default:
97191                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
97192             }
97193             return {
97194                 diagnosticMessage: diagnosticMessage,
97195                 errorNode: node.name || node
97196             };
97197         }
97198         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
97199             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
97200             return diagnosticMessage !== undefined ? {
97201                 diagnosticMessage: diagnosticMessage,
97202                 errorNode: node,
97203                 typeName: node.name
97204             } : undefined;
97205         }
97206         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
97207             switch (node.parent.kind) {
97208                 case 166 /* Constructor */:
97209                     return symbolAccessibilityResult.errorModuleName ?
97210                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97211                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97212                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97213                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
97214                 case 170 /* ConstructSignature */:
97215                 case 175 /* ConstructorType */:
97216                     // Interfaces cannot have parameter types that cannot be named
97217                     return symbolAccessibilityResult.errorModuleName ?
97218                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97219                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
97220                 case 169 /* CallSignature */:
97221                     // Interfaces cannot have parameter types that cannot be named
97222                     return symbolAccessibilityResult.errorModuleName ?
97223                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97224                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
97225                 case 171 /* IndexSignature */:
97226                     // Interfaces cannot have parameter types that cannot be named
97227                     return symbolAccessibilityResult.errorModuleName ?
97228                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97229                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
97230                 case 165 /* MethodDeclaration */:
97231                 case 164 /* MethodSignature */:
97232                     if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) {
97233                         return symbolAccessibilityResult.errorModuleName ?
97234                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97235                                 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 :
97236                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97237                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
97238                     }
97239                     else if (node.parent.parent.kind === 252 /* ClassDeclaration */) {
97240                         return symbolAccessibilityResult.errorModuleName ?
97241                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97242                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97243                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97244                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
97245                     }
97246                     else {
97247                         // Interfaces cannot have parameter types that cannot be named
97248                         return symbolAccessibilityResult.errorModuleName ?
97249                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97250                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
97251                     }
97252                 case 251 /* FunctionDeclaration */:
97253                 case 174 /* FunctionType */:
97254                     return symbolAccessibilityResult.errorModuleName ?
97255                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97256                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97257                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
97258                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
97259                 case 168 /* SetAccessor */:
97260                 case 167 /* GetAccessor */:
97261                     return symbolAccessibilityResult.errorModuleName ?
97262                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97263                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97264                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
97265                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
97266                 default:
97267                     return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
97268             }
97269         }
97270         function getTypeParameterConstraintVisibilityError() {
97271             // Type parameter constraints are named by user so we should always be able to name it
97272             var diagnosticMessage;
97273             switch (node.parent.kind) {
97274                 case 252 /* ClassDeclaration */:
97275                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
97276                     break;
97277                 case 253 /* InterfaceDeclaration */:
97278                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
97279                     break;
97280                 case 190 /* MappedType */:
97281                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
97282                     break;
97283                 case 175 /* ConstructorType */:
97284                 case 170 /* ConstructSignature */:
97285                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
97286                     break;
97287                 case 169 /* CallSignature */:
97288                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
97289                     break;
97290                 case 165 /* MethodDeclaration */:
97291                 case 164 /* MethodSignature */:
97292                     if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) {
97293                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
97294                     }
97295                     else if (node.parent.parent.kind === 252 /* ClassDeclaration */) {
97296                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
97297                     }
97298                     else {
97299                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
97300                     }
97301                     break;
97302                 case 174 /* FunctionType */:
97303                 case 251 /* FunctionDeclaration */:
97304                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
97305                     break;
97306                 case 254 /* TypeAliasDeclaration */:
97307                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
97308                     break;
97309                 default:
97310                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
97311             }
97312             return {
97313                 diagnosticMessage: diagnosticMessage,
97314                 errorNode: node,
97315                 typeName: node.name
97316             };
97317         }
97318         function getHeritageClauseVisibilityError() {
97319             var diagnosticMessage;
97320             // Heritage clause is written by user so it can always be named
97321             if (ts.isClassDeclaration(node.parent.parent)) {
97322                 // Class or Interface implemented/extended is inaccessible
97323                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 116 /* ImplementsKeyword */ ?
97324                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
97325                     node.parent.parent.name ? ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 :
97326                         ts.Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0;
97327             }
97328             else {
97329                 // interface is inaccessible
97330                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
97331             }
97332             return {
97333                 diagnosticMessage: diagnosticMessage,
97334                 errorNode: node,
97335                 typeName: ts.getNameOfDeclaration(node.parent.parent)
97336             };
97337         }
97338         function getImportEntityNameVisibilityError() {
97339             return {
97340                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
97341                 errorNode: node,
97342                 typeName: node.name
97343             };
97344         }
97345         function getTypeAliasDeclarationVisibilityError() {
97346             return {
97347                 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
97348                 errorNode: node.type,
97349                 typeName: node.name
97350             };
97351         }
97352     }
97353     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
97354 })(ts || (ts = {}));
97355 /*@internal*/
97356 var ts;
97357 (function (ts) {
97358     function getDeclarationDiagnostics(host, resolver, file) {
97359         var compilerOptions = host.getCompilerOptions();
97360         var result = ts.transformNodes(resolver, host, ts.factory, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
97361         return result.diagnostics;
97362     }
97363     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
97364     function hasInternalAnnotation(range, currentSourceFile) {
97365         var comment = currentSourceFile.text.substring(range.pos, range.end);
97366         return ts.stringContains(comment, "@internal");
97367     }
97368     function isInternalDeclaration(node, currentSourceFile) {
97369         var parseTreeNode = ts.getParseTreeNode(node);
97370         if (parseTreeNode && parseTreeNode.kind === 160 /* Parameter */) {
97371             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
97372             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
97373             var text = currentSourceFile.text;
97374             var commentRanges = previousSibling
97375                 ? ts.concatenate(
97376                 // to handle
97377                 // ... parameters, /* @internal */
97378                 // public param: string
97379                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
97380                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
97381             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
97382         }
97383         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
97384         return !!ts.forEach(leadingCommentRanges, function (range) {
97385             return hasInternalAnnotation(range, currentSourceFile);
97386         });
97387     }
97388     ts.isInternalDeclaration = isInternalDeclaration;
97389     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
97390         2048 /* WriteClassExpressionAsTypeLiteral */ |
97391         4096 /* UseTypeOfFunction */ |
97392         8 /* UseStructuralFallback */ |
97393         524288 /* AllowEmptyTuple */ |
97394         4 /* GenerateNamesForShadowedTypeParams */ |
97395         1 /* NoTruncation */;
97396     /**
97397      * Transforms a ts file into a .d.ts file
97398      * This process requires type information, which is retrieved through the emit resolver. Because of this,
97399      * in many places this transformer assumes it will be operating on parse tree nodes directly.
97400      * This means that _no transforms should be allowed to occur before this one_.
97401      */
97402     function transformDeclarations(context) {
97403         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
97404         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
97405         var needsDeclare = true;
97406         var isBundledEmit = false;
97407         var resultHasExternalModuleIndicator = false;
97408         var needsScopeFixMarker = false;
97409         var resultHasScopeMarker = false;
97410         var enclosingDeclaration;
97411         var necessaryTypeReferences;
97412         var lateMarkedStatements;
97413         var lateStatementReplacementMap;
97414         var suppressNewDiagnosticContexts;
97415         var exportedModulesFromDeclarationEmit;
97416         var factory = context.factory;
97417         var host = context.getEmitHost();
97418         var symbolTracker = {
97419             trackSymbol: trackSymbol,
97420             reportInaccessibleThisError: reportInaccessibleThisError,
97421             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
97422             reportCyclicStructureError: reportCyclicStructureError,
97423             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
97424             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
97425             reportTruncationError: reportTruncationError,
97426             moduleResolverHost: host,
97427             trackReferencedAmbientModule: trackReferencedAmbientModule,
97428             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
97429             reportNonlocalAugmentation: reportNonlocalAugmentation
97430         };
97431         var errorNameNode;
97432         var currentSourceFile;
97433         var refs;
97434         var libs;
97435         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
97436         var resolver = context.getEmitResolver();
97437         var options = context.getCompilerOptions();
97438         var noResolve = options.noResolve, stripInternal = options.stripInternal;
97439         return transformRoot;
97440         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
97441             if (!typeReferenceDirectives) {
97442                 return;
97443             }
97444             necessaryTypeReferences = necessaryTypeReferences || new ts.Set();
97445             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
97446                 var ref = typeReferenceDirectives_2[_i];
97447                 necessaryTypeReferences.add(ref);
97448             }
97449         }
97450         function trackReferencedAmbientModule(node, symbol) {
97451             // If it is visible via `// <reference types="..."/>`, then we should just use that
97452             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
97453             if (ts.length(directives)) {
97454                 return recordTypeReferenceDirectivesIfNecessary(directives);
97455             }
97456             // Otherwise we should emit a path-based reference
97457             var container = ts.getSourceFileOfNode(node);
97458             refs.set(ts.getOriginalNodeId(container), container);
97459         }
97460         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
97461             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
97462                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
97463                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
97464                     if (!lateMarkedStatements) {
97465                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
97466                     }
97467                     else {
97468                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
97469                             var ref = _a[_i];
97470                             ts.pushIfUnique(lateMarkedStatements, ref);
97471                         }
97472                     }
97473                 }
97474                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
97475             }
97476             else {
97477                 // Report error
97478                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
97479                 if (errorInfo) {
97480                     if (errorInfo.typeName) {
97481                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
97482                     }
97483                     else {
97484                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
97485                     }
97486                 }
97487             }
97488         }
97489         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
97490             if (!isBundledEmit) {
97491                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
97492             }
97493         }
97494         function trackSymbol(symbol, enclosingDeclaration, meaning) {
97495             if (symbol.flags & 262144 /* TypeParameter */)
97496                 return;
97497             handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
97498             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
97499         }
97500         function reportPrivateInBaseOfClassExpression(propertyName) {
97501             if (errorNameNode) {
97502                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
97503             }
97504         }
97505         function reportInaccessibleUniqueSymbolError() {
97506             if (errorNameNode) {
97507                 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"));
97508             }
97509         }
97510         function reportCyclicStructureError() {
97511             if (errorNameNode) {
97512                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode)));
97513             }
97514         }
97515         function reportInaccessibleThisError() {
97516             if (errorNameNode) {
97517                 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"));
97518             }
97519         }
97520         function reportLikelyUnsafeImportRequiredError(specifier) {
97521             if (errorNameNode) {
97522                 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));
97523             }
97524         }
97525         function reportTruncationError() {
97526             if (errorNameNode) {
97527                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed));
97528             }
97529         }
97530         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
97531             var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
97532             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
97533             for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
97534                 var augmentations = augmentingDeclarations_1[_i];
97535                 context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file)));
97536             }
97537         }
97538         function transformDeclarationsForJS(sourceFile, bundled) {
97539             var oldDiag = getSymbolAccessibilityDiagnostic;
97540             getSymbolAccessibilityDiagnostic = function (s) { return ({
97541                 diagnosticMessage: s.errorModuleName
97542                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
97543                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
97544                 errorNode: s.errorNode || sourceFile
97545             }); };
97546             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
97547             getSymbolAccessibilityDiagnostic = oldDiag;
97548             return result;
97549         }
97550         function transformRoot(node) {
97551             if (node.kind === 297 /* SourceFile */ && node.isDeclarationFile) {
97552                 return node;
97553             }
97554             if (node.kind === 298 /* Bundle */) {
97555                 isBundledEmit = true;
97556                 refs = new ts.Map();
97557                 libs = new ts.Map();
97558                 var hasNoDefaultLib_1 = false;
97559                 var bundle = factory.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
97560                     if (sourceFile.isDeclarationFile)
97561                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
97562                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
97563                     currentSourceFile = sourceFile;
97564                     enclosingDeclaration = sourceFile;
97565                     lateMarkedStatements = undefined;
97566                     suppressNewDiagnosticContexts = false;
97567                     lateStatementReplacementMap = new ts.Map();
97568                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
97569                     needsScopeFixMarker = false;
97570                     resultHasScopeMarker = false;
97571                     collectReferences(sourceFile, refs);
97572                     collectLibs(sourceFile, libs);
97573                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
97574                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
97575                         needsDeclare = false;
97576                         var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
97577                         var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(133 /* DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
97578                         return newFile;
97579                     }
97580                     needsDeclare = true;
97581                     var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
97582                     return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
97583                 }), ts.mapDefined(node.prepends, function (prepend) {
97584                     if (prepend.kind === 300 /* InputFiles */) {
97585                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
97586                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
97587                         collectReferences(sourceFile, refs);
97588                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
97589                         collectLibs(sourceFile, libs);
97590                         return sourceFile;
97591                     }
97592                     return prepend;
97593                 }));
97594                 bundle.syntheticFileReferences = [];
97595                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
97596                 bundle.syntheticLibReferences = getLibReferences();
97597                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
97598                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
97599                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
97600                 refs.forEach(referenceVisitor_1);
97601                 return bundle;
97602             }
97603             // Single source file
97604             needsDeclare = true;
97605             needsScopeFixMarker = false;
97606             resultHasScopeMarker = false;
97607             enclosingDeclaration = node;
97608             currentSourceFile = node;
97609             getSymbolAccessibilityDiagnostic = throwDiagnostic;
97610             isBundledEmit = false;
97611             resultHasExternalModuleIndicator = false;
97612             suppressNewDiagnosticContexts = false;
97613             lateMarkedStatements = undefined;
97614             lateStatementReplacementMap = new ts.Map();
97615             necessaryTypeReferences = undefined;
97616             refs = collectReferences(currentSourceFile, new ts.Map());
97617             libs = collectLibs(currentSourceFile, new ts.Map());
97618             var references = [];
97619             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
97620             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
97621             var combinedStatements;
97622             if (ts.isSourceFileJS(currentSourceFile)) {
97623                 combinedStatements = factory.createNodeArray(transformDeclarationsForJS(node));
97624                 refs.forEach(referenceVisitor);
97625                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
97626             }
97627             else {
97628                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
97629                 combinedStatements = ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
97630                 refs.forEach(referenceVisitor);
97631                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
97632                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
97633                     combinedStatements = ts.setTextRange(factory.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports(factory)])), combinedStatements);
97634                 }
97635             }
97636             var updated = factory.updateSourceFile(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
97637             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
97638             return updated;
97639             function getLibReferences() {
97640                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
97641             }
97642             function getFileReferencesForUsedTypeReferences() {
97643                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
97644             }
97645             function getFileReferenceForTypeName(typeName) {
97646                 // Elide type references for which we have imports
97647                 if (emittedImports) {
97648                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
97649                         var importStatement = emittedImports_1[_i];
97650                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
97651                             var expr = importStatement.moduleReference.expression;
97652                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
97653                                 return undefined;
97654                             }
97655                         }
97656                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
97657                             return undefined;
97658                         }
97659                     }
97660                 }
97661                 return { fileName: typeName, pos: -1, end: -1 };
97662             }
97663             function mapReferencesIntoArray(references, outputFilePath) {
97664                 return function (file) {
97665                     var declFileName;
97666                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
97667                         declFileName = file.fileName;
97668                     }
97669                     else {
97670                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
97671                             return; // Omit references to files which are being merged
97672                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
97673                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
97674                     }
97675                     if (declFileName) {
97676                         var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, 
97677                         /*preferences*/ undefined);
97678                         if (!ts.pathIsRelative(specifier)) {
97679                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
97680                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
97681                             // a relative path to the declaration file
97682                             recordTypeReferenceDirectivesIfNecessary([specifier]);
97683                             return;
97684                         }
97685                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
97686                         /*isAbsolutePathAnUrl*/ false);
97687                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
97688                             fileName = fileName.substring(2);
97689                         }
97690                         // omit references to files from node_modules (npm may disambiguate module
97691                         // references when installing this package, making the path is unreliable).
97692                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
97693                             return;
97694                         }
97695                         references.push({ pos: -1, end: -1, fileName: fileName });
97696                     }
97697                 };
97698             }
97699         }
97700         function collectReferences(sourceFile, ret) {
97701             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
97702                 return ret;
97703             ts.forEach(sourceFile.referencedFiles, function (f) {
97704                 var elem = host.getSourceFileFromReference(sourceFile, f);
97705                 if (elem) {
97706                     ret.set(ts.getOriginalNodeId(elem), elem);
97707                 }
97708             });
97709             return ret;
97710         }
97711         function collectLibs(sourceFile, ret) {
97712             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
97713                 var lib = host.getLibFileFromReference(ref);
97714                 if (lib) {
97715                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
97716                 }
97717             });
97718             return ret;
97719         }
97720         function filterBindingPatternInitializers(name) {
97721             if (name.kind === 78 /* Identifier */) {
97722                 return name;
97723             }
97724             else {
97725                 if (name.kind === 197 /* ArrayBindingPattern */) {
97726                     return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
97727                 }
97728                 else {
97729                     return factory.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
97730                 }
97731             }
97732             function visitBindingElement(elem) {
97733                 if (elem.kind === 222 /* OmittedExpression */) {
97734                     return elem;
97735                 }
97736                 return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
97737             }
97738         }
97739         function ensureParameter(p, modifierMask, type) {
97740             var oldDiag;
97741             if (!suppressNewDiagnosticContexts) {
97742                 oldDiag = getSymbolAccessibilityDiagnostic;
97743                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
97744             }
97745             var newParam = factory.updateParameterDeclaration(p, 
97746             /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param
97747             ensureNoInitializer(p));
97748             if (!suppressNewDiagnosticContexts) {
97749                 getSymbolAccessibilityDiagnostic = oldDiag;
97750             }
97751             return newParam;
97752         }
97753         function shouldPrintWithInitializer(node) {
97754             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
97755         }
97756         function ensureNoInitializer(node) {
97757             if (shouldPrintWithInitializer(node)) {
97758                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
97759             }
97760             return undefined;
97761         }
97762         function ensureType(node, type, ignorePrivate) {
97763             if (!ignorePrivate && ts.hasEffectiveModifier(node, 8 /* Private */)) {
97764                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
97765                 return;
97766             }
97767             if (shouldPrintWithInitializer(node)) {
97768                 // Literal const declarations will have an initializer ensured rather than a type
97769                 return;
97770             }
97771             var shouldUseResolverType = node.kind === 160 /* Parameter */ &&
97772                 (resolver.isRequiredInitializedParameter(node) ||
97773                     resolver.isOptionalUninitializedParameterProperty(node));
97774             if (type && !shouldUseResolverType) {
97775                 return ts.visitNode(type, visitDeclarationSubtree);
97776             }
97777             if (!ts.getParseTreeNode(node)) {
97778                 return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128 /* AnyKeyword */);
97779             }
97780             if (node.kind === 168 /* SetAccessor */) {
97781                 // 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
97782                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
97783                 return factory.createKeywordTypeNode(128 /* AnyKeyword */);
97784             }
97785             errorNameNode = node.name;
97786             var oldDiag;
97787             if (!suppressNewDiagnosticContexts) {
97788                 oldDiag = getSymbolAccessibilityDiagnostic;
97789                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
97790             }
97791             if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) {
97792                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
97793             }
97794             if (node.kind === 160 /* Parameter */
97795                 || node.kind === 163 /* PropertyDeclaration */
97796                 || node.kind === 162 /* PropertySignature */) {
97797                 if (!node.initializer)
97798                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
97799                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
97800             }
97801             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
97802             function cleanup(returnValue) {
97803                 errorNameNode = undefined;
97804                 if (!suppressNewDiagnosticContexts) {
97805                     getSymbolAccessibilityDiagnostic = oldDiag;
97806                 }
97807                 return returnValue || factory.createKeywordTypeNode(128 /* AnyKeyword */);
97808             }
97809         }
97810         function isDeclarationAndNotVisible(node) {
97811             node = ts.getParseTreeNode(node);
97812             switch (node.kind) {
97813                 case 251 /* FunctionDeclaration */:
97814                 case 256 /* ModuleDeclaration */:
97815                 case 253 /* InterfaceDeclaration */:
97816                 case 252 /* ClassDeclaration */:
97817                 case 254 /* TypeAliasDeclaration */:
97818                 case 255 /* EnumDeclaration */:
97819                     return !resolver.isDeclarationVisible(node);
97820                 // The following should be doing their own visibility checks based on filtering their members
97821                 case 249 /* VariableDeclaration */:
97822                     return !getBindingNameVisible(node);
97823                 case 260 /* ImportEqualsDeclaration */:
97824                 case 261 /* ImportDeclaration */:
97825                 case 267 /* ExportDeclaration */:
97826                 case 266 /* ExportAssignment */:
97827                     return false;
97828             }
97829             return false;
97830         }
97831         function getBindingNameVisible(elem) {
97832             if (ts.isOmittedExpression(elem)) {
97833                 return false;
97834             }
97835             if (ts.isBindingPattern(elem.name)) {
97836                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
97837                 return ts.some(elem.name.elements, getBindingNameVisible);
97838             }
97839             else {
97840                 return resolver.isDeclarationVisible(elem);
97841             }
97842         }
97843         function updateParamsList(node, params, modifierMask) {
97844             if (ts.hasEffectiveModifier(node, 8 /* Private */)) {
97845                 return undefined; // TODO: GH#18217
97846             }
97847             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
97848             if (!newParams) {
97849                 return undefined; // TODO: GH#18217
97850             }
97851             return factory.createNodeArray(newParams, params.hasTrailingComma);
97852         }
97853         function updateAccessorParamsList(input, isPrivate) {
97854             var newParams;
97855             if (!isPrivate) {
97856                 var thisParameter = ts.getThisParameter(input);
97857                 if (thisParameter) {
97858                     newParams = [ensureParameter(thisParameter)];
97859                 }
97860             }
97861             if (ts.isSetAccessorDeclaration(input)) {
97862                 var newValueParameter = void 0;
97863                 if (!isPrivate) {
97864                     var valueParameter = ts.getSetAccessorValueParameter(input);
97865                     if (valueParameter) {
97866                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
97867                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
97868                     }
97869                 }
97870                 if (!newValueParameter) {
97871                     newValueParameter = factory.createParameterDeclaration(
97872                     /*decorators*/ undefined, 
97873                     /*modifiers*/ undefined, 
97874                     /*dotDotDotToken*/ undefined, "value");
97875                 }
97876                 newParams = ts.append(newParams, newValueParameter);
97877             }
97878             return factory.createNodeArray(newParams || ts.emptyArray);
97879         }
97880         function ensureTypeParams(node, params) {
97881             return ts.hasEffectiveModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
97882         }
97883         function isEnclosingDeclaration(node) {
97884             return ts.isSourceFile(node)
97885                 || ts.isTypeAliasDeclaration(node)
97886                 || ts.isModuleDeclaration(node)
97887                 || ts.isClassDeclaration(node)
97888                 || ts.isInterfaceDeclaration(node)
97889                 || ts.isFunctionLike(node)
97890                 || ts.isIndexSignatureDeclaration(node)
97891                 || ts.isMappedTypeNode(node);
97892         }
97893         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
97894             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
97895             handleSymbolAccessibilityError(visibilityResult);
97896             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
97897         }
97898         function preserveJsDoc(updated, original) {
97899             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
97900                 updated.jsDoc = original.jsDoc;
97901             }
97902             return ts.setCommentRange(updated, ts.getCommentRange(original));
97903         }
97904         function rewriteModuleSpecifier(parent, input) {
97905             if (!input)
97906                 return undefined; // TODO: GH#18217
97907             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 256 /* ModuleDeclaration */ && parent.kind !== 195 /* ImportType */);
97908             if (ts.isStringLiteralLike(input)) {
97909                 if (isBundledEmit) {
97910                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
97911                     if (newName) {
97912                         return factory.createStringLiteral(newName);
97913                     }
97914                 }
97915                 else {
97916                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
97917                     if (symbol) {
97918                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
97919                     }
97920                 }
97921             }
97922             return input;
97923         }
97924         function transformImportEqualsDeclaration(decl) {
97925             if (!resolver.isDeclarationVisible(decl))
97926                 return;
97927             if (decl.moduleReference.kind === 272 /* ExternalModuleReference */) {
97928                 // Rewrite external module names if necessary
97929                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
97930                 return factory.updateImportEqualsDeclaration(decl, 
97931                 /*decorators*/ undefined, decl.modifiers, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
97932             }
97933             else {
97934                 var oldDiag = getSymbolAccessibilityDiagnostic;
97935                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
97936                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
97937                 getSymbolAccessibilityDiagnostic = oldDiag;
97938                 return decl;
97939             }
97940         }
97941         function transformImportDeclaration(decl) {
97942             if (!decl.importClause) {
97943                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
97944                 return factory.updateImportDeclaration(decl, 
97945                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
97946             }
97947             // The `importClause` visibility corresponds to the default's visibility.
97948             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
97949             if (!decl.importClause.namedBindings) {
97950                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
97951                 return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, 
97952                 /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
97953             }
97954             if (decl.importClause.namedBindings.kind === 263 /* NamespaceImport */) {
97955                 // Namespace import (optionally with visible default)
97956                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
97957                 return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
97958             }
97959             // Named imports (optionally with visible default)
97960             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
97961             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
97962                 return factory.updateImportDeclaration(decl, 
97963                 /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
97964             }
97965             // Augmentation of export depends on import
97966             if (resolver.isImportRequiredByAugmentation(decl)) {
97967                 return factory.updateImportDeclaration(decl, 
97968                 /*decorators*/ undefined, decl.modifiers, 
97969                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
97970             }
97971             // Nothing visible
97972         }
97973         function transformAndReplaceLatePaintedStatements(statements) {
97974             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
97975             // error handling which must now be included in the output and themselves checked for errors.
97976             // For example:
97977             // ```
97978             // module A {
97979             //   export module Q {}
97980             //   import B = Q;
97981             //   import C = B;
97982             //   export import D = C;
97983             // }
97984             // ```
97985             // 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
97986             // 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
97987             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
97988             while (ts.length(lateMarkedStatements)) {
97989                 var i = lateMarkedStatements.shift();
97990                 if (!ts.isLateVisibilityPaintedStatement(i)) {
97991                     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));
97992                 }
97993                 var priorNeedsDeclare = needsDeclare;
97994                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
97995                 var result = transformTopLevelDeclaration(i);
97996                 needsDeclare = priorNeedsDeclare;
97997                 lateStatementReplacementMap.set(ts.getOriginalNodeId(i), result);
97998             }
97999             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
98000             // (and remove them from the set to examine for outter declarations)
98001             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
98002             function visitLateVisibilityMarkedStatements(statement) {
98003                 if (ts.isLateVisibilityPaintedStatement(statement)) {
98004                     var key = ts.getOriginalNodeId(statement);
98005                     if (lateStatementReplacementMap.has(key)) {
98006                         var result = lateStatementReplacementMap.get(key);
98007                         lateStatementReplacementMap.delete(key);
98008                         if (result) {
98009                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
98010                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
98011                                 needsScopeFixMarker = true;
98012                             }
98013                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
98014                                 resultHasExternalModuleIndicator = true;
98015                             }
98016                         }
98017                         return result;
98018                     }
98019                 }
98020                 return statement;
98021             }
98022         }
98023         function visitDeclarationSubtree(input) {
98024             if (shouldStripInternal(input))
98025                 return;
98026             if (ts.isDeclaration(input)) {
98027                 if (isDeclarationAndNotVisible(input))
98028                     return;
98029                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
98030                     return;
98031                 }
98032             }
98033             // Elide implementation signatures from overload sets
98034             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
98035                 return;
98036             // Elide semicolon class statements
98037             if (ts.isSemicolonClassElement(input))
98038                 return;
98039             var previousEnclosingDeclaration;
98040             if (isEnclosingDeclaration(input)) {
98041                 previousEnclosingDeclaration = enclosingDeclaration;
98042                 enclosingDeclaration = input;
98043             }
98044             var oldDiag = getSymbolAccessibilityDiagnostic;
98045             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
98046             // We'd see a TDZ violation at runtime
98047             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
98048             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
98049             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 177 /* TypeLiteral */ || input.kind === 190 /* MappedType */) && input.parent.kind !== 254 /* TypeAliasDeclaration */);
98050             // Emit methods which are private as properties with no type information
98051             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
98052                 if (ts.hasEffectiveModifier(input, 8 /* Private */)) {
98053                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
98054                         return; // Elide all but the first overload
98055                     return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
98056                 }
98057             }
98058             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
98059                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
98060             }
98061             if (ts.isTypeQueryNode(input)) {
98062                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
98063             }
98064             if (shouldEnterSuppressNewDiagnosticsContextContext) {
98065                 // 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.
98066                 suppressNewDiagnosticContexts = true;
98067             }
98068             if (isProcessedComponent(input)) {
98069                 switch (input.kind) {
98070                     case 223 /* ExpressionWithTypeArguments */: {
98071                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
98072                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
98073                         }
98074                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
98075                         return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments));
98076                     }
98077                     case 173 /* TypeReference */: {
98078                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
98079                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
98080                         return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments));
98081                     }
98082                     case 170 /* ConstructSignature */:
98083                         return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
98084                     case 166 /* Constructor */: {
98085                         // A constructor declaration may not have a type annotation
98086                         var ctor = factory.createConstructorDeclaration(
98087                         /*decorators*/ undefined, 
98088                         /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* None */), 
98089                         /*body*/ undefined);
98090                         return cleanup(ctor);
98091                     }
98092                     case 165 /* MethodDeclaration */: {
98093                         if (ts.isPrivateIdentifier(input.name)) {
98094                             return cleanup(/*returnValue*/ undefined);
98095                         }
98096                         var sig = factory.createMethodDeclaration(
98097                         /*decorators*/ undefined, ensureModifiers(input), 
98098                         /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
98099                         /*body*/ undefined);
98100                         return cleanup(sig);
98101                     }
98102                     case 167 /* GetAccessor */: {
98103                         if (ts.isPrivateIdentifier(input.name)) {
98104                             return cleanup(/*returnValue*/ undefined);
98105                         }
98106                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
98107                         return cleanup(factory.updateGetAccessorDeclaration(input, 
98108                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
98109                         /*body*/ undefined));
98110                     }
98111                     case 168 /* SetAccessor */: {
98112                         if (ts.isPrivateIdentifier(input.name)) {
98113                             return cleanup(/*returnValue*/ undefined);
98114                         }
98115                         return cleanup(factory.updateSetAccessorDeclaration(input, 
98116                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), 
98117                         /*body*/ undefined));
98118                     }
98119                     case 163 /* PropertyDeclaration */:
98120                         if (ts.isPrivateIdentifier(input.name)) {
98121                             return cleanup(/*returnValue*/ undefined);
98122                         }
98123                         return cleanup(factory.updatePropertyDeclaration(input, 
98124                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
98125                     case 162 /* PropertySignature */:
98126                         if (ts.isPrivateIdentifier(input.name)) {
98127                             return cleanup(/*returnValue*/ undefined);
98128                         }
98129                         return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type)));
98130                     case 164 /* MethodSignature */: {
98131                         if (ts.isPrivateIdentifier(input.name)) {
98132                             return cleanup(/*returnValue*/ undefined);
98133                         }
98134                         return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
98135                     }
98136                     case 169 /* CallSignature */: {
98137                         return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
98138                     }
98139                     case 171 /* IndexSignature */: {
98140                         return cleanup(factory.updateIndexSignature(input, 
98141                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128 /* AnyKeyword */)));
98142                     }
98143                     case 249 /* VariableDeclaration */: {
98144                         if (ts.isBindingPattern(input.name)) {
98145                             return recreateBindingPattern(input.name);
98146                         }
98147                         shouldEnterSuppressNewDiagnosticsContextContext = true;
98148                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
98149                         return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
98150                     }
98151                     case 159 /* TypeParameter */: {
98152                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
98153                             return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
98154                         }
98155                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
98156                     }
98157                     case 184 /* ConditionalType */: {
98158                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
98159                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
98160                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
98161                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
98162                         var oldEnclosingDecl = enclosingDeclaration;
98163                         enclosingDeclaration = input.trueType;
98164                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
98165                         enclosingDeclaration = oldEnclosingDecl;
98166                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
98167                         return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
98168                     }
98169                     case 174 /* FunctionType */: {
98170                         return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
98171                     }
98172                     case 175 /* ConstructorType */: {
98173                         return cleanup(factory.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
98174                     }
98175                     case 195 /* ImportType */: {
98176                         if (!ts.isLiteralImportTypeNode(input))
98177                             return cleanup(input);
98178                         return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf));
98179                     }
98180                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
98181                 }
98182             }
98183             if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) {
98184                 ts.setEmitFlags(input, 1 /* SingleLine */);
98185             }
98186             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
98187             function cleanup(returnValue) {
98188                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
98189                     checkName(input);
98190                 }
98191                 if (isEnclosingDeclaration(input)) {
98192                     enclosingDeclaration = previousEnclosingDeclaration;
98193                 }
98194                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
98195                     getSymbolAccessibilityDiagnostic = oldDiag;
98196                 }
98197                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
98198                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
98199                 }
98200                 if (returnValue === input) {
98201                     return returnValue;
98202                 }
98203                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
98204             }
98205         }
98206         function isPrivateMethodTypeParameter(node) {
98207             return node.parent.kind === 165 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */);
98208         }
98209         function visitDeclarationStatements(input) {
98210             if (!isPreservedDeclarationStatement(input)) {
98211                 // return undefined for unmatched kinds to omit them from the tree
98212                 return;
98213             }
98214             if (shouldStripInternal(input))
98215                 return;
98216             switch (input.kind) {
98217                 case 267 /* ExportDeclaration */: {
98218                     if (ts.isSourceFile(input.parent)) {
98219                         resultHasExternalModuleIndicator = true;
98220                     }
98221                     resultHasScopeMarker = true;
98222                     // Always visible if the parent node isn't dropped for being not visible
98223                     // Rewrite external module names if necessary
98224                     return factory.updateExportDeclaration(input, 
98225                     /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier));
98226                 }
98227                 case 266 /* ExportAssignment */: {
98228                     // Always visible if the parent node isn't dropped for being not visible
98229                     if (ts.isSourceFile(input.parent)) {
98230                         resultHasExternalModuleIndicator = true;
98231                     }
98232                     resultHasScopeMarker = true;
98233                     if (input.expression.kind === 78 /* Identifier */) {
98234                         return input;
98235                     }
98236                     else {
98237                         var newId = factory.createUniqueName("_default", 16 /* Optimistic */);
98238                         getSymbolAccessibilityDiagnostic = function () { return ({
98239                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
98240                             errorNode: input
98241                         }); };
98242                         var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
98243                         var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
98244                         return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
98245                     }
98246                 }
98247             }
98248             var result = transformTopLevelDeclaration(input);
98249             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
98250             lateStatementReplacementMap.set(ts.getOriginalNodeId(input), result);
98251             return input;
98252         }
98253         function stripExportModifiers(statement) {
98254             if (ts.isImportEqualsDeclaration(statement) || ts.hasEffectiveModifier(statement, 512 /* Default */) || !ts.canHaveModifiers(statement)) {
98255                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
98256                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
98257                 return statement;
98258             }
98259             var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 /* All */ ^ 1 /* Export */));
98260             return factory.updateModifiers(statement, modifiers);
98261         }
98262         function transformTopLevelDeclaration(input) {
98263             if (shouldStripInternal(input))
98264                 return;
98265             switch (input.kind) {
98266                 case 260 /* ImportEqualsDeclaration */: {
98267                     return transformImportEqualsDeclaration(input);
98268                 }
98269                 case 261 /* ImportDeclaration */: {
98270                     return transformImportDeclaration(input);
98271                 }
98272             }
98273             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
98274                 return;
98275             // Elide implementation signatures from overload sets
98276             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
98277                 return;
98278             var previousEnclosingDeclaration;
98279             if (isEnclosingDeclaration(input)) {
98280                 previousEnclosingDeclaration = enclosingDeclaration;
98281                 enclosingDeclaration = input;
98282             }
98283             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
98284             var oldDiag = getSymbolAccessibilityDiagnostic;
98285             if (canProdiceDiagnostic) {
98286                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
98287             }
98288             var previousNeedsDeclare = needsDeclare;
98289             switch (input.kind) {
98290                 case 254 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
98291                     return cleanup(factory.updateTypeAliasDeclaration(input, 
98292                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
98293                 case 253 /* InterfaceDeclaration */: {
98294                     return cleanup(factory.updateInterfaceDeclaration(input, 
98295                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
98296                 }
98297                 case 251 /* FunctionDeclaration */: {
98298                     // Generators lose their generator-ness, excepting their return type
98299                     var clean = cleanup(factory.updateFunctionDeclaration(input, 
98300                     /*decorators*/ undefined, ensureModifiers(input), 
98301                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
98302                     /*body*/ undefined));
98303                     if (clean && resolver.isExpandoFunctionDeclaration(input)) {
98304                         var props = resolver.getPropertiesOfContainerFunction(input);
98305                         // Use parseNodeFactory so it is usable as an enclosing declaration
98306                         var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* Namespace */);
98307                         ts.setParent(fakespace_1, enclosingDeclaration);
98308                         fakespace_1.locals = ts.createSymbolTable(props);
98309                         fakespace_1.symbol = props[0].parent;
98310                         var exportMappings_1 = [];
98311                         var declarations = ts.mapDefined(props, function (p) {
98312                             if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
98313                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
98314                             }
98315                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
98316                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
98317                             getSymbolAccessibilityDiagnostic = oldDiag;
98318                             var nameStr = ts.unescapeLeadingUnderscores(p.escapedName);
98319                             var isNonContextualKeywordName = ts.isStringANonContextualKeyword(nameStr);
98320                             var name = isNonContextualKeywordName ? factory.getGeneratedNameForNode(p.valueDeclaration) : factory.createIdentifier(nameStr);
98321                             if (isNonContextualKeywordName) {
98322                                 exportMappings_1.push([name, nameStr]);
98323                             }
98324                             var varDecl = factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, type, /*initializer*/ undefined);
98325                             return factory.createVariableStatement(isNonContextualKeywordName ? undefined : [factory.createToken(92 /* ExportKeyword */)], factory.createVariableDeclarationList([varDecl]));
98326                         });
98327                         if (!exportMappings_1.length) {
98328                             declarations = ts.mapDefined(declarations, function (declaration) { return factory.updateModifiers(declaration, 0 /* None */); });
98329                         }
98330                         else {
98331                             declarations.push(factory.createExportDeclaration(
98332                             /*decorators*/ undefined, 
98333                             /*modifiers*/ undefined, 
98334                             /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) {
98335                                 var gen = _a[0], exp = _a[1];
98336                                 return factory.createExportSpecifier(gen, exp);
98337                             }))));
98338                         }
98339                         var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* Namespace */);
98340                         if (!ts.hasEffectiveModifier(clean, 512 /* Default */)) {
98341                             return [clean, namespaceDecl];
98342                         }
98343                         var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
98344                         var cleanDeclaration = factory.updateFunctionDeclaration(clean, 
98345                         /*decorators*/ undefined, modifiers, 
98346                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
98347                         /*body*/ undefined);
98348                         var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, 
98349                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
98350                         var exportDefaultDeclaration = factory.createExportAssignment(
98351                         /*decorators*/ undefined, 
98352                         /*modifiers*/ undefined, 
98353                         /*isExportEquals*/ false, namespaceDecl.name);
98354                         if (ts.isSourceFile(input.parent)) {
98355                             resultHasExternalModuleIndicator = true;
98356                         }
98357                         resultHasScopeMarker = true;
98358                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
98359                     }
98360                     else {
98361                         return clean;
98362                     }
98363                 }
98364                 case 256 /* ModuleDeclaration */: {
98365                     needsDeclare = false;
98366                     var inner = input.body;
98367                     if (inner && inner.kind === 257 /* ModuleBlock */) {
98368                         var oldNeedsScopeFix = needsScopeFixMarker;
98369                         var oldHasScopeFix = resultHasScopeMarker;
98370                         resultHasScopeMarker = false;
98371                         needsScopeFixMarker = false;
98372                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
98373                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
98374                         if (input.flags & 8388608 /* Ambient */) {
98375                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
98376                         }
98377                         // With the final list of statements, there are 3 possibilities:
98378                         // 1. There's an export assignment or export declaration in the namespace - do nothing
98379                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
98380                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
98381                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
98382                             if (needsScopeFixMarker) {
98383                                 lateStatements = factory.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports(factory)]));
98384                             }
98385                             else {
98386                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
98387                             }
98388                         }
98389                         var body = factory.updateModuleBlock(inner, lateStatements);
98390                         needsDeclare = previousNeedsDeclare;
98391                         needsScopeFixMarker = oldNeedsScopeFix;
98392                         resultHasScopeMarker = oldHasScopeFix;
98393                         var mods = ensureModifiers(input);
98394                         return cleanup(factory.updateModuleDeclaration(input, 
98395                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
98396                     }
98397                     else {
98398                         needsDeclare = previousNeedsDeclare;
98399                         var mods = ensureModifiers(input);
98400                         needsDeclare = false;
98401                         ts.visitNode(inner, visitDeclarationStatements);
98402                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
98403                         var id = ts.getOriginalNodeId(inner); // TODO: GH#18217
98404                         var body = lateStatementReplacementMap.get(id);
98405                         lateStatementReplacementMap.delete(id);
98406                         return cleanup(factory.updateModuleDeclaration(input, 
98407                         /*decorators*/ undefined, mods, input.name, body));
98408                     }
98409                 }
98410                 case 252 /* ClassDeclaration */: {
98411                     var modifiers = factory.createNodeArray(ensureModifiers(input));
98412                     var typeParameters = ensureTypeParams(input, input.typeParameters);
98413                     var ctor = ts.getFirstConstructorWithBody(input);
98414                     var parameterProperties = void 0;
98415                     if (ctor) {
98416                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
98417                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
98418                             if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
98419                                 return;
98420                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
98421                             if (param.name.kind === 78 /* Identifier */) {
98422                                 return preserveJsDoc(factory.createPropertyDeclaration(
98423                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
98424                             }
98425                             else {
98426                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
98427                                 return walkBindingPattern(param.name);
98428                             }
98429                             function walkBindingPattern(pattern) {
98430                                 var elems;
98431                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
98432                                     var elem = _a[_i];
98433                                     if (ts.isOmittedExpression(elem))
98434                                         continue;
98435                                     if (ts.isBindingPattern(elem.name)) {
98436                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
98437                                     }
98438                                     elems = elems || [];
98439                                     elems.push(factory.createPropertyDeclaration(
98440                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
98441                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
98442                                     /*initializer*/ undefined));
98443                                 }
98444                                 return elems;
98445                             }
98446                         }));
98447                         getSymbolAccessibilityDiagnostic = oldDiag_1;
98448                     }
98449                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
98450                     var privateIdentifier = hasPrivateIdentifier ? [
98451                         factory.createPropertyDeclaration(
98452                         /*decorators*/ undefined, 
98453                         /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), 
98454                         /*questionToken*/ undefined, 
98455                         /*type*/ undefined, 
98456                         /*initializer*/ undefined)
98457                     ] : undefined;
98458                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
98459                     var members = factory.createNodeArray(memberNodes);
98460                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
98461                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 103 /* NullKeyword */) {
98462                         // We must add a temporary declaration for the extends clause expression
98463                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
98464                         var newId_1 = factory.createUniqueName(oldId + "_base", 16 /* Optimistic */);
98465                         getSymbolAccessibilityDiagnostic = function () { return ({
98466                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
98467                             errorNode: extendsClause_1,
98468                             typeName: input.name
98469                         }); };
98470                         var varDecl = factory.createVariableDeclaration(newId_1, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
98471                         var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
98472                         var heritageClauses = factory.createNodeArray(ts.map(input.heritageClauses, function (clause) {
98473                             if (clause.token === 93 /* ExtendsKeyword */) {
98474                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
98475                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
98476                                 var newClause = factory.updateHeritageClause(clause, ts.map(clause.types, function (t) { return factory.updateExpressionWithTypeArguments(t, newId_1, ts.visitNodes(t.typeArguments, visitDeclarationSubtree)); }));
98477                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
98478                                 return newClause;
98479                             }
98480                             return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 103 /* NullKeyword */; })), visitDeclarationSubtree));
98481                         }));
98482                         return [statement, cleanup(factory.updateClassDeclaration(input, 
98483                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
98484                     }
98485                     else {
98486                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
98487                         return cleanup(factory.updateClassDeclaration(input, 
98488                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
98489                     }
98490                 }
98491                 case 232 /* VariableStatement */: {
98492                     return cleanup(transformVariableStatement(input));
98493                 }
98494                 case 255 /* EnumDeclaration */: {
98495                     return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) {
98496                         if (shouldStripInternal(m))
98497                             return;
98498                         // Rewrite enum values to their constants, if available
98499                         var constValue = resolver.getConstantValue(m);
98500                         return preserveJsDoc(factory.updateEnumMember(m, m.name, constValue !== undefined ? typeof constValue === "string" ? factory.createStringLiteral(constValue) : factory.createNumericLiteral(constValue) : undefined), m);
98501                     }))));
98502                 }
98503             }
98504             // Anything left unhandled is an error, so this should be unreachable
98505             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
98506             function cleanup(node) {
98507                 if (isEnclosingDeclaration(input)) {
98508                     enclosingDeclaration = previousEnclosingDeclaration;
98509                 }
98510                 if (canProdiceDiagnostic) {
98511                     getSymbolAccessibilityDiagnostic = oldDiag;
98512                 }
98513                 if (input.kind === 256 /* ModuleDeclaration */) {
98514                     needsDeclare = previousNeedsDeclare;
98515                 }
98516                 if (node === input) {
98517                     return node;
98518                 }
98519                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
98520             }
98521         }
98522         function transformVariableStatement(input) {
98523             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
98524                 return;
98525             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
98526             if (!ts.length(nodes))
98527                 return;
98528             return factory.updateVariableStatement(input, factory.createNodeArray(ensureModifiers(input)), factory.updateVariableDeclarationList(input.declarationList, nodes));
98529         }
98530         function recreateBindingPattern(d) {
98531             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
98532         }
98533         function recreateBindingElement(e) {
98534             if (e.kind === 222 /* OmittedExpression */) {
98535                 return;
98536             }
98537             if (e.name) {
98538                 if (!getBindingNameVisible(e))
98539                     return;
98540                 if (ts.isBindingPattern(e.name)) {
98541                     return recreateBindingPattern(e.name);
98542                 }
98543                 else {
98544                     return factory.createVariableDeclaration(e.name, /*exclamationToken*/ undefined, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
98545                 }
98546             }
98547         }
98548         function checkName(node) {
98549             var oldDiag;
98550             if (!suppressNewDiagnosticContexts) {
98551                 oldDiag = getSymbolAccessibilityDiagnostic;
98552                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
98553             }
98554             errorNameNode = node.name;
98555             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
98556             var decl = node;
98557             var entityName = decl.name.expression;
98558             checkEntityNameVisibility(entityName, enclosingDeclaration);
98559             if (!suppressNewDiagnosticContexts) {
98560                 getSymbolAccessibilityDiagnostic = oldDiag;
98561             }
98562             errorNameNode = undefined;
98563         }
98564         function shouldStripInternal(node) {
98565             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
98566         }
98567         function isScopeMarker(node) {
98568             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
98569         }
98570         function hasScopeMarker(statements) {
98571             return ts.some(statements, isScopeMarker);
98572         }
98573         function ensureModifiers(node) {
98574             var currentFlags = ts.getEffectiveModifierFlags(node);
98575             var newFlags = ensureModifierFlags(node);
98576             if (currentFlags === newFlags) {
98577                 return node.modifiers;
98578             }
98579             return factory.createModifiersFromModifierFlags(newFlags);
98580         }
98581         function ensureModifierFlags(node) {
98582             var mask = 11263 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
98583             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
98584             var parentIsFile = node.parent.kind === 297 /* SourceFile */;
98585             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
98586                 mask ^= 2 /* Ambient */;
98587                 additions = 0 /* None */;
98588             }
98589             return maskModifierFlags(node, mask, additions);
98590         }
98591         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
98592             var accessorType = getTypeAnnotationFromAccessor(node);
98593             if (!accessorType && node !== accessors.firstAccessor) {
98594                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
98595                 // 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
98596                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
98597             }
98598             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
98599                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
98600                 // 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
98601                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
98602             }
98603             return accessorType;
98604         }
98605         function transformHeritageClauses(nodes) {
98606             return factory.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) {
98607                 return ts.isEntityNameExpression(t.expression) || (clause.token === 93 /* ExtendsKeyword */ && t.expression.kind === 103 /* NullKeyword */);
98608             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
98609         }
98610     }
98611     ts.transformDeclarations = transformDeclarations;
98612     function isAlwaysType(node) {
98613         if (node.kind === 253 /* InterfaceDeclaration */) {
98614             return true;
98615         }
98616         return false;
98617     }
98618     // Elide "public" modifier, as it is the default
98619     function maskModifiers(node, modifierMask, modifierAdditions) {
98620         return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
98621     }
98622     function maskModifierFlags(node, modifierMask, modifierAdditions) {
98623         if (modifierMask === void 0) { modifierMask = 11263 /* All */ ^ 4 /* Public */; }
98624         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
98625         var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions;
98626         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
98627             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
98628             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
98629             flags ^= 1 /* Export */;
98630         }
98631         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
98632             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
98633         }
98634         return flags;
98635     }
98636     function getTypeAnnotationFromAccessor(accessor) {
98637         if (accessor) {
98638             return accessor.kind === 167 /* GetAccessor */
98639                 ? accessor.type // Getter - return type
98640                 : accessor.parameters.length > 0
98641                     ? accessor.parameters[0].type // Setter parameter type
98642                     : undefined;
98643         }
98644     }
98645     function canHaveLiteralInitializer(node) {
98646         switch (node.kind) {
98647             case 163 /* PropertyDeclaration */:
98648             case 162 /* PropertySignature */:
98649                 return !ts.hasEffectiveModifier(node, 8 /* Private */);
98650             case 160 /* Parameter */:
98651             case 249 /* VariableDeclaration */:
98652                 return true;
98653         }
98654         return false;
98655     }
98656     function isPreservedDeclarationStatement(node) {
98657         switch (node.kind) {
98658             case 251 /* FunctionDeclaration */:
98659             case 256 /* ModuleDeclaration */:
98660             case 260 /* ImportEqualsDeclaration */:
98661             case 253 /* InterfaceDeclaration */:
98662             case 252 /* ClassDeclaration */:
98663             case 254 /* TypeAliasDeclaration */:
98664             case 255 /* EnumDeclaration */:
98665             case 232 /* VariableStatement */:
98666             case 261 /* ImportDeclaration */:
98667             case 267 /* ExportDeclaration */:
98668             case 266 /* ExportAssignment */:
98669                 return true;
98670         }
98671         return false;
98672     }
98673     function isProcessedComponent(node) {
98674         switch (node.kind) {
98675             case 170 /* ConstructSignature */:
98676             case 166 /* Constructor */:
98677             case 165 /* MethodDeclaration */:
98678             case 167 /* GetAccessor */:
98679             case 168 /* SetAccessor */:
98680             case 163 /* PropertyDeclaration */:
98681             case 162 /* PropertySignature */:
98682             case 164 /* MethodSignature */:
98683             case 169 /* CallSignature */:
98684             case 171 /* IndexSignature */:
98685             case 249 /* VariableDeclaration */:
98686             case 159 /* TypeParameter */:
98687             case 223 /* ExpressionWithTypeArguments */:
98688             case 173 /* TypeReference */:
98689             case 184 /* ConditionalType */:
98690             case 174 /* FunctionType */:
98691             case 175 /* ConstructorType */:
98692             case 195 /* ImportType */:
98693                 return true;
98694         }
98695         return false;
98696     }
98697 })(ts || (ts = {}));
98698 /* @internal */
98699 var ts;
98700 (function (ts) {
98701     function getModuleTransformer(moduleKind) {
98702         switch (moduleKind) {
98703             case ts.ModuleKind.ESNext:
98704             case ts.ModuleKind.ES2020:
98705             case ts.ModuleKind.ES2015:
98706                 return ts.transformECMAScriptModule;
98707             case ts.ModuleKind.System:
98708                 return ts.transformSystemModule;
98709             default:
98710                 return ts.transformModule;
98711         }
98712     }
98713     var TransformationState;
98714     (function (TransformationState) {
98715         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
98716         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
98717         TransformationState[TransformationState["Completed"] = 2] = "Completed";
98718         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
98719     })(TransformationState || (TransformationState = {}));
98720     var SyntaxKindFeatureFlags;
98721     (function (SyntaxKindFeatureFlags) {
98722         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
98723         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
98724     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
98725     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
98726     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
98727         return {
98728             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
98729             declarationTransformers: getDeclarationTransformers(customTransformers),
98730         };
98731     }
98732     ts.getTransformers = getTransformers;
98733     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
98734         if (emitOnlyDtsFiles)
98735             return ts.emptyArray;
98736         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
98737         var moduleKind = ts.getEmitModuleKind(compilerOptions);
98738         var transformers = [];
98739         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
98740         transformers.push(ts.transformTypeScript);
98741         transformers.push(ts.transformClassFields);
98742         if (ts.getJSXTransformEnabled(compilerOptions)) {
98743             transformers.push(ts.transformJsx);
98744         }
98745         if (languageVersion < 99 /* ESNext */) {
98746             transformers.push(ts.transformESNext);
98747         }
98748         if (languageVersion < 7 /* ES2020 */) {
98749             transformers.push(ts.transformES2020);
98750         }
98751         if (languageVersion < 6 /* ES2019 */) {
98752             transformers.push(ts.transformES2019);
98753         }
98754         if (languageVersion < 5 /* ES2018 */) {
98755             transformers.push(ts.transformES2018);
98756         }
98757         if (languageVersion < 4 /* ES2017 */) {
98758             transformers.push(ts.transformES2017);
98759         }
98760         if (languageVersion < 3 /* ES2016 */) {
98761             transformers.push(ts.transformES2016);
98762         }
98763         if (languageVersion < 2 /* ES2015 */) {
98764             transformers.push(ts.transformES2015);
98765             transformers.push(ts.transformGenerators);
98766         }
98767         transformers.push(getModuleTransformer(moduleKind));
98768         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
98769         // for ES3.
98770         if (languageVersion < 1 /* ES5 */) {
98771             transformers.push(ts.transformES5);
98772         }
98773         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
98774         return transformers;
98775     }
98776     function getDeclarationTransformers(customTransformers) {
98777         var transformers = [];
98778         transformers.push(ts.transformDeclarations);
98779         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
98780         return transformers;
98781     }
98782     /**
98783      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
98784      */
98785     function wrapCustomTransformer(transformer) {
98786         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
98787     }
98788     /**
98789      * Wrap a transformer factory that may return a custom script or declaration transformer object.
98790      */
98791     function wrapCustomTransformerFactory(transformer, handleDefault) {
98792         return function (context) {
98793             var customTransformer = transformer(context);
98794             return typeof customTransformer === "function"
98795                 ? handleDefault(context, customTransformer)
98796                 : wrapCustomTransformer(customTransformer);
98797         };
98798     }
98799     function wrapScriptTransformerFactory(transformer) {
98800         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
98801     }
98802     function wrapDeclarationTransformerFactory(transformer) {
98803         return wrapCustomTransformerFactory(transformer, function (_, node) { return node; });
98804     }
98805     function noEmitSubstitution(_hint, node) {
98806         return node;
98807     }
98808     ts.noEmitSubstitution = noEmitSubstitution;
98809     function noEmitNotification(hint, node, callback) {
98810         callback(hint, node);
98811     }
98812     ts.noEmitNotification = noEmitNotification;
98813     /**
98814      * Transforms an array of SourceFiles by passing them through each transformer.
98815      *
98816      * @param resolver The emit resolver provided by the checker.
98817      * @param host The emit host object used to interact with the file system.
98818      * @param options Compiler options to surface in the `TransformationContext`.
98819      * @param nodes An array of nodes to transform.
98820      * @param transforms An array of `TransformerFactory` callbacks.
98821      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
98822      */
98823     function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) {
98824         var enabledSyntaxKindFeatures = new Array(341 /* Count */);
98825         var lexicalEnvironmentVariableDeclarations;
98826         var lexicalEnvironmentFunctionDeclarations;
98827         var lexicalEnvironmentStatements;
98828         var lexicalEnvironmentFlags = 0 /* None */;
98829         var lexicalEnvironmentVariableDeclarationsStack = [];
98830         var lexicalEnvironmentFunctionDeclarationsStack = [];
98831         var lexicalEnvironmentStatementsStack = [];
98832         var lexicalEnvironmentFlagsStack = [];
98833         var lexicalEnvironmentStackOffset = 0;
98834         var lexicalEnvironmentSuspended = false;
98835         var emitHelpers;
98836         var onSubstituteNode = noEmitSubstitution;
98837         var onEmitNode = noEmitNotification;
98838         var state = 0 /* Uninitialized */;
98839         var diagnostics = [];
98840         // The transformation context is provided to each transformer as part of transformer
98841         // initialization.
98842         var context = {
98843             factory: factory,
98844             getCompilerOptions: function () { return options; },
98845             getEmitResolver: function () { return resolver; },
98846             getEmitHost: function () { return host; },
98847             getEmitHelperFactory: ts.memoize(function () { return ts.createEmitHelperFactory(context); }),
98848             startLexicalEnvironment: startLexicalEnvironment,
98849             suspendLexicalEnvironment: suspendLexicalEnvironment,
98850             resumeLexicalEnvironment: resumeLexicalEnvironment,
98851             endLexicalEnvironment: endLexicalEnvironment,
98852             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
98853             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
98854             hoistVariableDeclaration: hoistVariableDeclaration,
98855             hoistFunctionDeclaration: hoistFunctionDeclaration,
98856             addInitializationStatement: addInitializationStatement,
98857             requestEmitHelper: requestEmitHelper,
98858             readEmitHelpers: readEmitHelpers,
98859             enableSubstitution: enableSubstitution,
98860             enableEmitNotification: enableEmitNotification,
98861             isSubstitutionEnabled: isSubstitutionEnabled,
98862             isEmitNotificationEnabled: isEmitNotificationEnabled,
98863             get onSubstituteNode() { return onSubstituteNode; },
98864             set onSubstituteNode(value) {
98865                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
98866                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
98867                 onSubstituteNode = value;
98868             },
98869             get onEmitNode() { return onEmitNode; },
98870             set onEmitNode(value) {
98871                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
98872                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
98873                 onEmitNode = value;
98874             },
98875             addDiagnostic: function (diag) {
98876                 diagnostics.push(diag);
98877             }
98878         };
98879         // Ensure the parse tree is clean before applying transformations
98880         for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
98881             var node = nodes_2[_i];
98882             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
98883         }
98884         ts.performance.mark("beforeTransform");
98885         // Chain together and initialize each transformer.
98886         var transformersWithContext = transformers.map(function (t) { return t(context); });
98887         var transformation = function (node) {
98888             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
98889                 var transform = transformersWithContext_1[_i];
98890                 node = transform(node);
98891             }
98892             return node;
98893         };
98894         // prevent modification of transformation hooks.
98895         state = 1 /* Initialized */;
98896         // Transform each node.
98897         var transformed = [];
98898         for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) {
98899             var node = nodes_3[_a];
98900             ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end });
98901             transformed.push((allowDtsFiles ? transformation : transformRoot)(node));
98902             ts.tracing.pop();
98903         }
98904         // prevent modification of the lexical environment.
98905         state = 2 /* Completed */;
98906         ts.performance.mark("afterTransform");
98907         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
98908         return {
98909             transformed: transformed,
98910             substituteNode: substituteNode,
98911             emitNodeWithNotification: emitNodeWithNotification,
98912             isEmitNotificationEnabled: isEmitNotificationEnabled,
98913             dispose: dispose,
98914             diagnostics: diagnostics
98915         };
98916         function transformRoot(node) {
98917             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
98918         }
98919         /**
98920          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
98921          */
98922         function enableSubstitution(kind) {
98923             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
98924             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
98925         }
98926         /**
98927          * Determines whether expression substitutions are enabled for the provided node.
98928          */
98929         function isSubstitutionEnabled(node) {
98930             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
98931                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
98932         }
98933         /**
98934          * Emits a node with possible substitution.
98935          *
98936          * @param hint A hint as to the intended usage of the node.
98937          * @param node The node to emit.
98938          * @param emitCallback The callback used to emit the node or its substitute.
98939          */
98940         function substituteNode(hint, node) {
98941             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
98942             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
98943         }
98944         /**
98945          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
98946          */
98947         function enableEmitNotification(kind) {
98948             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
98949             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
98950         }
98951         /**
98952          * Determines whether before/after emit notifications should be raised in the pretty
98953          * printer when it emits a node.
98954          */
98955         function isEmitNotificationEnabled(node) {
98956             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
98957                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
98958         }
98959         /**
98960          * Emits a node with possible emit notification.
98961          *
98962          * @param hint A hint as to the intended usage of the node.
98963          * @param node The node to emit.
98964          * @param emitCallback The callback used to emit the node.
98965          */
98966         function emitNodeWithNotification(hint, node, emitCallback) {
98967             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
98968             if (node) {
98969                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
98970                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
98971                 if (isEmitNotificationEnabled(node)) {
98972                     onEmitNode(hint, node, emitCallback);
98973                 }
98974                 else {
98975                     emitCallback(hint, node);
98976                 }
98977             }
98978         }
98979         /**
98980          * Records a hoisted variable declaration for the provided name within a lexical environment.
98981          */
98982         function hoistVariableDeclaration(name) {
98983             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
98984             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
98985             var decl = ts.setEmitFlags(factory.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
98986             if (!lexicalEnvironmentVariableDeclarations) {
98987                 lexicalEnvironmentVariableDeclarations = [decl];
98988             }
98989             else {
98990                 lexicalEnvironmentVariableDeclarations.push(decl);
98991             }
98992             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
98993                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
98994             }
98995         }
98996         /**
98997          * Records a hoisted function declaration within a lexical environment.
98998          */
98999         function hoistFunctionDeclaration(func) {
99000             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99001             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99002             ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
99003             if (!lexicalEnvironmentFunctionDeclarations) {
99004                 lexicalEnvironmentFunctionDeclarations = [func];
99005             }
99006             else {
99007                 lexicalEnvironmentFunctionDeclarations.push(func);
99008             }
99009         }
99010         /**
99011          * Adds an initialization statement to the top of the lexical environment.
99012          */
99013         function addInitializationStatement(node) {
99014             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99015             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99016             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
99017             if (!lexicalEnvironmentStatements) {
99018                 lexicalEnvironmentStatements = [node];
99019             }
99020             else {
99021                 lexicalEnvironmentStatements.push(node);
99022             }
99023         }
99024         /**
99025          * Starts a new lexical environment. Any existing hoisted variable or function declarations
99026          * are pushed onto a stack, and the related storage variables are reset.
99027          */
99028         function startLexicalEnvironment() {
99029             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99030             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99031             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
99032             // Save the current lexical environment. Rather than resizing the array we adjust the
99033             // stack size variable. This allows us to reuse existing array slots we've
99034             // already allocated between transformations to avoid allocation and GC overhead during
99035             // transformation.
99036             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
99037             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
99038             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
99039             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
99040             lexicalEnvironmentStackOffset++;
99041             lexicalEnvironmentVariableDeclarations = undefined;
99042             lexicalEnvironmentFunctionDeclarations = undefined;
99043             lexicalEnvironmentStatements = undefined;
99044             lexicalEnvironmentFlags = 0 /* None */;
99045         }
99046         /** Suspends the current lexical environment, usually after visiting a parameter list. */
99047         function suspendLexicalEnvironment() {
99048             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99049             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99050             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
99051             lexicalEnvironmentSuspended = true;
99052         }
99053         /** Resumes a suspended lexical environment, usually before visiting a function body. */
99054         function resumeLexicalEnvironment() {
99055             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99056             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99057             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
99058             lexicalEnvironmentSuspended = false;
99059         }
99060         /**
99061          * Ends a lexical environment. The previous set of hoisted declarations are restored and
99062          * any hoisted declarations added in this environment are returned.
99063          */
99064         function endLexicalEnvironment() {
99065             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99066             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99067             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
99068             var statements;
99069             if (lexicalEnvironmentVariableDeclarations ||
99070                 lexicalEnvironmentFunctionDeclarations ||
99071                 lexicalEnvironmentStatements) {
99072                 if (lexicalEnvironmentFunctionDeclarations) {
99073                     statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
99074                 }
99075                 if (lexicalEnvironmentVariableDeclarations) {
99076                     var statement = factory.createVariableStatement(
99077                     /*modifiers*/ undefined, factory.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
99078                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
99079                     if (!statements) {
99080                         statements = [statement];
99081                     }
99082                     else {
99083                         statements.push(statement);
99084                     }
99085                 }
99086                 if (lexicalEnvironmentStatements) {
99087                     if (!statements) {
99088                         statements = __spreadArrays(lexicalEnvironmentStatements);
99089                     }
99090                     else {
99091                         statements = __spreadArrays(statements, lexicalEnvironmentStatements);
99092                     }
99093                 }
99094             }
99095             // Restore the previous lexical environment.
99096             lexicalEnvironmentStackOffset--;
99097             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
99098             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
99099             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
99100             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
99101             if (lexicalEnvironmentStackOffset === 0) {
99102                 lexicalEnvironmentVariableDeclarationsStack = [];
99103                 lexicalEnvironmentFunctionDeclarationsStack = [];
99104                 lexicalEnvironmentStatementsStack = [];
99105                 lexicalEnvironmentFlagsStack = [];
99106             }
99107             return statements;
99108         }
99109         function setLexicalEnvironmentFlags(flags, value) {
99110             lexicalEnvironmentFlags = value ?
99111                 lexicalEnvironmentFlags | flags :
99112                 lexicalEnvironmentFlags & ~flags;
99113         }
99114         function getLexicalEnvironmentFlags() {
99115             return lexicalEnvironmentFlags;
99116         }
99117         function requestEmitHelper(helper) {
99118             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
99119             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
99120             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
99121             if (helper.dependencies) {
99122                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
99123                     var h = _a[_i];
99124                     requestEmitHelper(h);
99125                 }
99126             }
99127             emitHelpers = ts.append(emitHelpers, helper);
99128         }
99129         function readEmitHelpers() {
99130             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
99131             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
99132             var helpers = emitHelpers;
99133             emitHelpers = undefined;
99134             return helpers;
99135         }
99136         function dispose() {
99137             if (state < 3 /* Disposed */) {
99138                 // Clean up emit nodes on parse tree
99139                 for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
99140                     var node = nodes_4[_i];
99141                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
99142                 }
99143                 // Release references to external entries for GC purposes.
99144                 lexicalEnvironmentVariableDeclarations = undefined;
99145                 lexicalEnvironmentVariableDeclarationsStack = undefined;
99146                 lexicalEnvironmentFunctionDeclarations = undefined;
99147                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
99148                 onSubstituteNode = undefined;
99149                 onEmitNode = undefined;
99150                 emitHelpers = undefined;
99151                 // Prevent further use of the transformation result.
99152                 state = 3 /* Disposed */;
99153             }
99154         }
99155     }
99156     ts.transformNodes = transformNodes;
99157     ts.nullTransformationContext = {
99158         get factory() { return ts.factory; },
99159         enableEmitNotification: ts.noop,
99160         enableSubstitution: ts.noop,
99161         endLexicalEnvironment: ts.returnUndefined,
99162         getCompilerOptions: function () { return ({}); },
99163         getEmitHost: ts.notImplemented,
99164         getEmitResolver: ts.notImplemented,
99165         getEmitHelperFactory: ts.notImplemented,
99166         setLexicalEnvironmentFlags: ts.noop,
99167         getLexicalEnvironmentFlags: function () { return 0; },
99168         hoistFunctionDeclaration: ts.noop,
99169         hoistVariableDeclaration: ts.noop,
99170         addInitializationStatement: ts.noop,
99171         isEmitNotificationEnabled: ts.notImplemented,
99172         isSubstitutionEnabled: ts.notImplemented,
99173         onEmitNode: ts.noop,
99174         onSubstituteNode: ts.notImplemented,
99175         readEmitHelpers: ts.notImplemented,
99176         requestEmitHelper: ts.noop,
99177         resumeLexicalEnvironment: ts.noop,
99178         startLexicalEnvironment: ts.noop,
99179         suspendLexicalEnvironment: ts.noop,
99180         addDiagnostic: ts.noop,
99181     };
99182 })(ts || (ts = {}));
99183 var ts;
99184 (function (ts) {
99185     var brackets = createBracketsMap();
99186     var syntheticParent = { pos: -1, end: -1 };
99187     /*@internal*/
99188     function isBuildInfoFile(file) {
99189         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
99190     }
99191     ts.isBuildInfoFile = isBuildInfoFile;
99192     /*@internal*/
99193     /**
99194      * Iterates over the source files that are expected to have an emit output.
99195      *
99196      * @param host An EmitHost.
99197      * @param action The action to execute.
99198      * @param sourceFilesOrTargetSourceFile
99199      *   If an array, the full list of source files to emit.
99200      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
99201      */
99202     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
99203         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
99204         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
99205         var options = host.getCompilerOptions();
99206         if (ts.outFile(options)) {
99207             var prepends = host.getPrependNodes();
99208             if (sourceFiles.length || prepends.length) {
99209                 var bundle = ts.factory.createBundle(sourceFiles, prepends);
99210                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
99211                 if (result) {
99212                     return result;
99213                 }
99214             }
99215         }
99216         else {
99217             if (!onlyBuildInfo) {
99218                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
99219                     var sourceFile = sourceFiles_1[_a];
99220                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
99221                     if (result) {
99222                         return result;
99223                     }
99224                 }
99225             }
99226             if (includeBuildInfo) {
99227                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
99228                 if (buildInfoPath)
99229                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
99230             }
99231         }
99232     }
99233     ts.forEachEmittedFile = forEachEmittedFile;
99234     function getTsBuildInfoEmitOutputFilePath(options) {
99235         var configFile = options.configFilePath;
99236         if (!ts.isIncrementalCompilation(options))
99237             return undefined;
99238         if (options.tsBuildInfoFile)
99239             return options.tsBuildInfoFile;
99240         var outPath = ts.outFile(options);
99241         var buildInfoExtensionLess;
99242         if (outPath) {
99243             buildInfoExtensionLess = ts.removeFileExtension(outPath);
99244         }
99245         else {
99246             if (!configFile)
99247                 return undefined;
99248             var configFileExtensionLess = ts.removeFileExtension(configFile);
99249             buildInfoExtensionLess = options.outDir ?
99250                 options.rootDir ?
99251                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
99252                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
99253                 configFileExtensionLess;
99254         }
99255         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
99256     }
99257     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
99258     /*@internal*/
99259     function getOutputPathsForBundle(options, forceDtsPaths) {
99260         var outPath = ts.outFile(options);
99261         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
99262         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
99263         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
99264         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
99265         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
99266         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
99267     }
99268     ts.getOutputPathsForBundle = getOutputPathsForBundle;
99269     /*@internal*/
99270     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
99271         var options = host.getCompilerOptions();
99272         if (sourceFile.kind === 298 /* Bundle */) {
99273             return getOutputPathsForBundle(options, forceDtsPaths);
99274         }
99275         else {
99276             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
99277             var isJsonFile = ts.isJsonSourceFile(sourceFile);
99278             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
99279             var isJsonEmittedToSameLocation = isJsonFile &&
99280                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
99281             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
99282             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
99283             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
99284             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
99285             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
99286         }
99287     }
99288     ts.getOutputPathsFor = getOutputPathsFor;
99289     function getSourceMapFilePath(jsFilePath, options) {
99290         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
99291     }
99292     // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
99293     // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
99294     // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
99295     /* @internal */
99296     function getOutputExtension(sourceFile, options) {
99297         if (ts.isJsonSourceFile(sourceFile)) {
99298             return ".json" /* Json */;
99299         }
99300         if (options.jsx === 1 /* Preserve */) {
99301             if (ts.isSourceFileJS(sourceFile)) {
99302                 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
99303                     return ".jsx" /* Jsx */;
99304                 }
99305             }
99306             else if (sourceFile.languageVariant === 1 /* JSX */) {
99307                 // TypeScript source file preserving JSX syntax
99308                 return ".jsx" /* Jsx */;
99309             }
99310         }
99311         return ".js" /* Js */;
99312     }
99313     ts.getOutputExtension = getOutputExtension;
99314     function rootDirOfOptions(configFile) {
99315         return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
99316     }
99317     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
99318         return outputDir ?
99319             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
99320             inputFileName;
99321     }
99322     /* @internal */
99323     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
99324         ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
99325         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
99326     }
99327     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
99328     function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
99329         if (configFile.options.emitDeclarationOnly)
99330             return undefined;
99331         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
99332         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
99333             ".json" /* Json */ :
99334             ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
99335                 ".jsx" /* Jsx */ :
99336                 ".js" /* Js */);
99337         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
99338             outputFileName :
99339             undefined;
99340     }
99341     function createAddOutput() {
99342         var outputs;
99343         return { addOutput: addOutput, getOutputs: getOutputs };
99344         function addOutput(path) {
99345             if (path) {
99346                 (outputs || (outputs = [])).push(path);
99347             }
99348         }
99349         function getOutputs() {
99350             return outputs || ts.emptyArray;
99351         }
99352     }
99353     function getSingleOutputFileNames(configFile, addOutput) {
99354         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
99355         addOutput(jsFilePath);
99356         addOutput(sourceMapFilePath);
99357         addOutput(declarationFilePath);
99358         addOutput(declarationMapPath);
99359         addOutput(buildInfoPath);
99360     }
99361     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
99362         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
99363             return;
99364         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
99365         addOutput(js);
99366         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
99367             return;
99368         if (js && configFile.options.sourceMap) {
99369             addOutput(js + ".map");
99370         }
99371         if (ts.getEmitDeclarations(configFile.options)) {
99372             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
99373             addOutput(dts);
99374             if (configFile.options.declarationMap) {
99375                 addOutput(dts + ".map");
99376             }
99377         }
99378     }
99379     /*@internal*/
99380     function getAllProjectOutputs(configFile, ignoreCase) {
99381         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
99382         if (ts.outFile(configFile.options)) {
99383             getSingleOutputFileNames(configFile, addOutput);
99384         }
99385         else {
99386             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
99387                 var inputFileName = _c[_b];
99388                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
99389             }
99390             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
99391         }
99392         return getOutputs();
99393     }
99394     ts.getAllProjectOutputs = getAllProjectOutputs;
99395     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
99396         inputFileName = ts.normalizePath(inputFileName);
99397         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
99398         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
99399         if (ts.outFile(commandLine.options)) {
99400             getSingleOutputFileNames(commandLine, addOutput);
99401         }
99402         else {
99403             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
99404         }
99405         return getOutputs();
99406     }
99407     ts.getOutputFileNames = getOutputFileNames;
99408     /*@internal*/
99409     function getFirstProjectOutput(configFile, ignoreCase) {
99410         if (ts.outFile(configFile.options)) {
99411             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
99412             return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
99413         }
99414         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
99415             var inputFileName = _b[_a];
99416             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
99417                 continue;
99418             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
99419             if (jsFilePath)
99420                 return jsFilePath;
99421             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
99422                 continue;
99423             if (ts.getEmitDeclarations(configFile.options)) {
99424                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
99425             }
99426         }
99427         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
99428         if (buildInfoPath)
99429             return buildInfoPath;
99430         return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
99431     }
99432     ts.getFirstProjectOutput = getFirstProjectOutput;
99433     /*@internal*/
99434     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
99435     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
99436         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
99437         var compilerOptions = host.getCompilerOptions();
99438         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
99439         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
99440         var emitterDiagnostics = ts.createDiagnosticCollection();
99441         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
99442         var writer = ts.createTextWriter(newLine);
99443         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
99444         var bundleBuildInfo;
99445         var emitSkipped = false;
99446         var exportedModulesFromDeclarationEmit;
99447         // Emit each output file
99448         enter();
99449         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
99450         exit();
99451         return {
99452             emitSkipped: emitSkipped,
99453             diagnostics: emitterDiagnostics.getDiagnostics(),
99454             emittedFiles: emittedFilesList,
99455             sourceMaps: sourceMapDataList,
99456             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
99457         };
99458         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
99459             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
99460             var buildInfoDirectory;
99461             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
99462                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
99463                 bundleBuildInfo = {
99464                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
99465                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
99466                 };
99467             }
99468             ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath });
99469             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
99470             ts.tracing.pop();
99471             ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath });
99472             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
99473             ts.tracing.pop();
99474             ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath });
99475             emitBuildInfo(bundleBuildInfo, buildInfoPath);
99476             ts.tracing.pop();
99477             if (!emitSkipped && emittedFilesList) {
99478                 if (!emitOnlyDtsFiles) {
99479                     if (jsFilePath) {
99480                         emittedFilesList.push(jsFilePath);
99481                     }
99482                     if (sourceMapFilePath) {
99483                         emittedFilesList.push(sourceMapFilePath);
99484                     }
99485                     if (buildInfoPath) {
99486                         emittedFilesList.push(buildInfoPath);
99487                     }
99488                 }
99489                 if (declarationFilePath) {
99490                     emittedFilesList.push(declarationFilePath);
99491                 }
99492                 if (declarationMapPath) {
99493                     emittedFilesList.push(declarationMapPath);
99494                 }
99495             }
99496             function relativeToBuildInfo(path) {
99497                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
99498             }
99499         }
99500         function emitBuildInfo(bundle, buildInfoPath) {
99501             // Write build information if applicable
99502             if (!buildInfoPath || targetSourceFile || emitSkipped)
99503                 return;
99504             var program = host.getProgramBuildInfo();
99505             if (host.isEmitBlocked(buildInfoPath)) {
99506                 emitSkipped = true;
99507                 return;
99508             }
99509             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
99510             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
99511         }
99512         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
99513             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
99514                 return;
99515             }
99516             // Make sure not to write js file and source map file if any of them cannot be written
99517             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
99518                 emitSkipped = true;
99519                 return;
99520             }
99521             // Transform the source files
99522             var transform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
99523             var printerOptions = {
99524                 removeComments: compilerOptions.removeComments,
99525                 newLine: compilerOptions.newLine,
99526                 noEmitHelpers: compilerOptions.noEmitHelpers,
99527                 module: compilerOptions.module,
99528                 target: compilerOptions.target,
99529                 sourceMap: compilerOptions.sourceMap,
99530                 inlineSourceMap: compilerOptions.inlineSourceMap,
99531                 inlineSources: compilerOptions.inlineSources,
99532                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
99533                 writeBundleFileInfo: !!bundleBuildInfo,
99534                 relativeToBuildInfo: relativeToBuildInfo
99535             };
99536             // Create a printer to print the nodes
99537             var printer = createPrinter(printerOptions, {
99538                 // resolver hooks
99539                 hasGlobalName: resolver.hasGlobalName,
99540                 // transform hooks
99541                 onEmitNode: transform.emitNodeWithNotification,
99542                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
99543                 substituteNode: transform.substituteNode,
99544             });
99545             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
99546             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
99547             // Clean up emit nodes on parse tree
99548             transform.dispose();
99549             if (bundleBuildInfo)
99550                 bundleBuildInfo.js = printer.bundleFileInfo;
99551         }
99552         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
99553             if (!sourceFileOrBundle)
99554                 return;
99555             if (!declarationFilePath) {
99556                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
99557                     emitSkipped = true;
99558                 return;
99559             }
99560             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
99561             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
99562             // Setup and perform the transformation to retrieve declarations from the input files
99563             var inputListOrBundle = ts.outFile(compilerOptions) ? [ts.factory.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
99564             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
99565                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
99566                 // Do that here when emitting only dts files
99567                 filesForEmit.forEach(collectLinkedAliases);
99568             }
99569             var declarationTransform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
99570             if (ts.length(declarationTransform.diagnostics)) {
99571                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
99572                     var diagnostic = _b[_a];
99573                     emitterDiagnostics.add(diagnostic);
99574                 }
99575             }
99576             var printerOptions = {
99577                 removeComments: compilerOptions.removeComments,
99578                 newLine: compilerOptions.newLine,
99579                 noEmitHelpers: true,
99580                 module: compilerOptions.module,
99581                 target: compilerOptions.target,
99582                 sourceMap: compilerOptions.sourceMap,
99583                 inlineSourceMap: compilerOptions.inlineSourceMap,
99584                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
99585                 onlyPrintJsDocStyle: true,
99586                 writeBundleFileInfo: !!bundleBuildInfo,
99587                 recordInternalSection: !!bundleBuildInfo,
99588                 relativeToBuildInfo: relativeToBuildInfo
99589             };
99590             var declarationPrinter = createPrinter(printerOptions, {
99591                 // resolver hooks
99592                 hasGlobalName: resolver.hasGlobalName,
99593                 // transform hooks
99594                 onEmitNode: declarationTransform.emitNodeWithNotification,
99595                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
99596                 substituteNode: declarationTransform.substituteNode,
99597             });
99598             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
99599             emitSkipped = emitSkipped || declBlocked;
99600             if (!declBlocked || forceDtsEmit) {
99601                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
99602                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
99603                     sourceMap: compilerOptions.declarationMap,
99604                     sourceRoot: compilerOptions.sourceRoot,
99605                     mapRoot: compilerOptions.mapRoot,
99606                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
99607                 });
99608                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 297 /* SourceFile */) {
99609                     var sourceFile = declarationTransform.transformed[0];
99610                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
99611                 }
99612             }
99613             declarationTransform.dispose();
99614             if (bundleBuildInfo)
99615                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
99616         }
99617         function collectLinkedAliases(node) {
99618             if (ts.isExportAssignment(node)) {
99619                 if (node.expression.kind === 78 /* Identifier */) {
99620                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
99621                 }
99622                 return;
99623             }
99624             else if (ts.isExportSpecifier(node)) {
99625                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
99626                 return;
99627             }
99628             ts.forEachChild(node, collectLinkedAliases);
99629         }
99630         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
99631             var bundle = sourceFileOrBundle.kind === 298 /* Bundle */ ? sourceFileOrBundle : undefined;
99632             var sourceFile = sourceFileOrBundle.kind === 297 /* SourceFile */ ? sourceFileOrBundle : undefined;
99633             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
99634             var sourceMapGenerator;
99635             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
99636                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
99637             }
99638             if (bundle) {
99639                 printer.writeBundle(bundle, writer, sourceMapGenerator);
99640             }
99641             else {
99642                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
99643             }
99644             if (sourceMapGenerator) {
99645                 if (sourceMapDataList) {
99646                     sourceMapDataList.push({
99647                         inputSourceFileNames: sourceMapGenerator.getSources(),
99648                         sourceMap: sourceMapGenerator.toJSON()
99649                     });
99650                 }
99651                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
99652                 if (sourceMappingURL) {
99653                     if (!writer.isAtStartOfLine())
99654                         writer.rawWrite(newLine);
99655                     writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
99656                 }
99657                 // Write the source map
99658                 if (sourceMapFilePath) {
99659                     var sourceMap = sourceMapGenerator.toString();
99660                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
99661                 }
99662             }
99663             else {
99664                 writer.writeLine();
99665             }
99666             // Write the output file
99667             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
99668             // Reset state
99669             writer.clear();
99670         }
99671         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
99672             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
99673                 && (sourceFileOrBundle.kind !== 297 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
99674         }
99675         function getSourceRoot(mapOptions) {
99676             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
99677             // relative paths of the sources list in the sourcemap
99678             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
99679             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
99680         }
99681         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
99682             if (mapOptions.sourceRoot)
99683                 return host.getCommonSourceDirectory();
99684             if (mapOptions.mapRoot) {
99685                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
99686                 if (sourceFile) {
99687                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
99688                     // 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
99689                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
99690                 }
99691                 if (ts.getRootLength(sourceMapDir) === 0) {
99692                     // The relative paths are relative to the common directory
99693                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
99694                 }
99695                 return sourceMapDir;
99696             }
99697             return ts.getDirectoryPath(ts.normalizePath(filePath));
99698         }
99699         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
99700             if (mapOptions.inlineSourceMap) {
99701                 // Encode the sourceMap into the sourceMap url
99702                 var sourceMapText = sourceMapGenerator.toString();
99703                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
99704                 return "data:application/json;base64," + base64SourceMapText;
99705             }
99706             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
99707             if (mapOptions.mapRoot) {
99708                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
99709                 if (sourceFile) {
99710                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
99711                     // 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
99712                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
99713                 }
99714                 if (ts.getRootLength(sourceMapDir) === 0) {
99715                     // The relative paths are relative to the common directory
99716                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
99717                     return encodeURI(ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
99718                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
99719                     host.getCurrentDirectory(), host.getCanonicalFileName, 
99720                     /*isAbsolutePathAnUrl*/ true));
99721                 }
99722                 else {
99723                     return encodeURI(ts.combinePaths(sourceMapDir, sourceMapFile));
99724                 }
99725             }
99726             return encodeURI(sourceMapFile);
99727         }
99728     }
99729     ts.emitFiles = emitFiles;
99730     /*@internal*/
99731     function getBuildInfoText(buildInfo) {
99732         return JSON.stringify(buildInfo, undefined, 2);
99733     }
99734     ts.getBuildInfoText = getBuildInfoText;
99735     /*@internal*/
99736     function getBuildInfo(buildInfoText) {
99737         return JSON.parse(buildInfoText);
99738     }
99739     ts.getBuildInfo = getBuildInfo;
99740     /*@internal*/
99741     ts.notImplementedResolver = {
99742         hasGlobalName: ts.notImplemented,
99743         getReferencedExportContainer: ts.notImplemented,
99744         getReferencedImportDeclaration: ts.notImplemented,
99745         getReferencedDeclarationWithCollidingName: ts.notImplemented,
99746         isDeclarationWithCollidingName: ts.notImplemented,
99747         isValueAliasDeclaration: ts.notImplemented,
99748         isReferencedAliasDeclaration: ts.notImplemented,
99749         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
99750         getNodeCheckFlags: ts.notImplemented,
99751         isDeclarationVisible: ts.notImplemented,
99752         isLateBound: function (_node) { return false; },
99753         collectLinkedAliases: ts.notImplemented,
99754         isImplementationOfOverload: ts.notImplemented,
99755         isRequiredInitializedParameter: ts.notImplemented,
99756         isOptionalUninitializedParameterProperty: ts.notImplemented,
99757         isExpandoFunctionDeclaration: ts.notImplemented,
99758         getPropertiesOfContainerFunction: ts.notImplemented,
99759         createTypeOfDeclaration: ts.notImplemented,
99760         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
99761         createTypeOfExpression: ts.notImplemented,
99762         createLiteralConstValue: ts.notImplemented,
99763         isSymbolAccessible: ts.notImplemented,
99764         isEntityNameVisible: ts.notImplemented,
99765         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
99766         getConstantValue: ts.notImplemented,
99767         getReferencedValueDeclaration: ts.notImplemented,
99768         getTypeReferenceSerializationKind: ts.notImplemented,
99769         isOptionalParameter: ts.notImplemented,
99770         moduleExportsSomeValue: ts.notImplemented,
99771         isArgumentsLocalBinding: ts.notImplemented,
99772         getExternalModuleFileFromDeclaration: ts.notImplemented,
99773         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
99774         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
99775         isLiteralConstDeclaration: ts.notImplemented,
99776         getJsxFactoryEntity: ts.notImplemented,
99777         getJsxFragmentFactoryEntity: ts.notImplemented,
99778         getAllAccessorDeclarations: ts.notImplemented,
99779         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
99780         isBindingCapturedByNode: ts.notImplemented,
99781         getDeclarationStatementsForSourceFile: ts.notImplemented,
99782         isImportRequiredByAugmentation: ts.notImplemented,
99783     };
99784     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
99785         var _a;
99786         var jsBundle = ts.Debug.checkDefined(bundle.js);
99787         var prologueMap = ((_a = jsBundle.sources) === null || _a === void 0 ? void 0 : _a.prologues) && ts.arrayToMap(jsBundle.sources.prologues, function (prologueInfo) { return prologueInfo.file; });
99788         return bundle.sourceFiles.map(function (fileName, index) {
99789             var _a, _b;
99790             var prologueInfo = prologueMap === null || prologueMap === void 0 ? void 0 : prologueMap.get(index);
99791             var statements = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.directives.map(function (directive) {
99792                 var literal = ts.setTextRange(ts.factory.createStringLiteral(directive.expression.text), directive.expression);
99793                 var statement = ts.setTextRange(ts.factory.createExpressionStatement(literal), directive);
99794                 ts.setParent(literal, statement);
99795                 return statement;
99796             });
99797             var eofToken = ts.factory.createToken(1 /* EndOfFileToken */);
99798             var sourceFile = ts.factory.createSourceFile(statements !== null && statements !== void 0 ? statements : [], eofToken, 0 /* None */);
99799             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
99800             sourceFile.text = (_a = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text) !== null && _a !== void 0 ? _a : "";
99801             ts.setTextRangePosWidth(sourceFile, 0, (_b = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text.length) !== null && _b !== void 0 ? _b : 0);
99802             ts.setEachParent(sourceFile.statements, sourceFile);
99803             ts.setTextRangePosWidth(eofToken, sourceFile.end, 0);
99804             ts.setParent(eofToken, sourceFile);
99805             return sourceFile;
99806         });
99807     }
99808     /*@internal*/
99809     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
99810         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
99811         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
99812         if (!buildInfoText)
99813             return buildInfoPath;
99814         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
99815         if (!jsFileText)
99816             return jsFilePath;
99817         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
99818         // error if no source map or for now if inline sourcemap
99819         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
99820             return sourceMapFilePath || "inline sourcemap decoding";
99821         // read declaration text
99822         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
99823         if (declarationFilePath && !declarationText)
99824             return declarationFilePath;
99825         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
99826         // error if no source map or for now if inline sourcemap
99827         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
99828             return declarationMapPath || "inline sourcemap decoding";
99829         var buildInfo = getBuildInfo(buildInfoText);
99830         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
99831             return buildInfoPath;
99832         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
99833         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
99834         /*onlyOwnText*/ true);
99835         var outputFiles = [];
99836         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
99837         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
99838         var emitHost = {
99839             getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
99840             getCanonicalFileName: host.getCanonicalFileName,
99841             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
99842             getCompilerOptions: function () { return config.options; },
99843             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
99844             getNewLine: function () { return host.getNewLine(); },
99845             getSourceFile: ts.returnUndefined,
99846             getSourceFileByPath: ts.returnUndefined,
99847             getSourceFiles: function () { return sourceFilesForJsEmit; },
99848             getLibFileFromReference: ts.notImplemented,
99849             isSourceFileFromExternalLibrary: ts.returnFalse,
99850             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
99851             getProjectReferenceRedirect: ts.returnUndefined,
99852             isSourceOfProjectReferenceRedirect: ts.returnFalse,
99853             writeFile: function (name, text, writeByteOrderMark) {
99854                 switch (name) {
99855                     case jsFilePath:
99856                         if (jsFileText === text)
99857                             return;
99858                         break;
99859                     case sourceMapFilePath:
99860                         if (sourceMapText === text)
99861                             return;
99862                         break;
99863                     case buildInfoPath:
99864                         var newBuildInfo = getBuildInfo(text);
99865                         newBuildInfo.program = buildInfo.program;
99866                         // Update sourceFileInfo
99867                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
99868                         newBuildInfo.bundle.js.sources = js.sources;
99869                         if (dts) {
99870                             newBuildInfo.bundle.dts.sources = dts.sources;
99871                         }
99872                         newBuildInfo.bundle.sourceFiles = sourceFiles;
99873                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
99874                         return;
99875                     case declarationFilePath:
99876                         if (declarationText === text)
99877                             return;
99878                         break;
99879                     case declarationMapPath:
99880                         if (declarationMapText === text)
99881                             return;
99882                         break;
99883                     default:
99884                         ts.Debug.fail("Unexpected path: " + name);
99885                 }
99886                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
99887             },
99888             isEmitBlocked: ts.returnFalse,
99889             readFile: function (f) { return host.readFile(f); },
99890             fileExists: function (f) { return host.fileExists(f); },
99891             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
99892             getProgramBuildInfo: ts.returnUndefined,
99893             getSourceFileFromReference: ts.returnUndefined,
99894             redirectTargetsMap: ts.createMultiMap()
99895         };
99896         emitFiles(ts.notImplementedResolver, emitHost, 
99897         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
99898         return outputFiles;
99899     }
99900     ts.emitUsingBuildInfo = emitUsingBuildInfo;
99901     var PipelinePhase;
99902     (function (PipelinePhase) {
99903         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
99904         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
99905         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
99906         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
99907         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
99908     })(PipelinePhase || (PipelinePhase = {}));
99909     function createPrinter(printerOptions, handlers) {
99910         if (printerOptions === void 0) { printerOptions = {}; }
99911         if (handlers === void 0) { handlers = {}; }
99912         var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken;
99913         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
99914         var newLine = ts.getNewLineCharacter(printerOptions);
99915         var moduleKind = ts.getEmitModuleKind(printerOptions);
99916         var bundledHelpers = new ts.Map();
99917         var currentSourceFile;
99918         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
99919         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
99920         var generatedNames; // Set of names generated by the NameGenerator.
99921         var tempFlagsStack; // Stack of enclosing name generation scopes.
99922         var tempFlags; // TempFlags for the current name generation scope.
99923         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
99924         var reservedNames; // TempFlags to reserve in nested name generation scopes.
99925         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
99926         var nextListElementPos; // See comment in `getLeadingLineTerminatorCount`.
99927         var writer;
99928         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
99929         var write = writeBase;
99930         var isOwnFileEmit;
99931         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
99932         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
99933         var recordInternalSection = printerOptions.recordInternalSection;
99934         var sourceFileTextPos = 0;
99935         var sourceFileTextKind = "text" /* Text */;
99936         // Source Maps
99937         var sourceMapsDisabled = true;
99938         var sourceMapGenerator;
99939         var sourceMapSource;
99940         var sourceMapSourceIndex = -1;
99941         var mostRecentlyAddedSourceMapSource;
99942         var mostRecentlyAddedSourceMapSourceIndex = -1;
99943         // Comments
99944         var containerPos = -1;
99945         var containerEnd = -1;
99946         var declarationListContainerEnd = -1;
99947         var currentLineMap;
99948         var detachedCommentsInfo;
99949         var hasWrittenComment = false;
99950         var commentsDisabled = !!printerOptions.removeComments;
99951         var lastNode;
99952         var lastSubstitution;
99953         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
99954         reset();
99955         return {
99956             // public API
99957             printNode: printNode,
99958             printList: printList,
99959             printFile: printFile,
99960             printBundle: printBundle,
99961             // internal API
99962             writeNode: writeNode,
99963             writeList: writeList,
99964             writeFile: writeFile,
99965             writeBundle: writeBundle,
99966             bundleFileInfo: bundleFileInfo
99967         };
99968         function printNode(hint, node, sourceFile) {
99969             switch (hint) {
99970                 case 0 /* SourceFile */:
99971                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
99972                     break;
99973                 case 2 /* IdentifierName */:
99974                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
99975                     break;
99976                 case 1 /* Expression */:
99977                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
99978                     break;
99979             }
99980             switch (node.kind) {
99981                 case 297 /* SourceFile */: return printFile(node);
99982                 case 298 /* Bundle */: return printBundle(node);
99983                 case 299 /* UnparsedSource */: return printUnparsedSource(node);
99984             }
99985             writeNode(hint, node, sourceFile, beginPrint());
99986             return endPrint();
99987         }
99988         function printList(format, nodes, sourceFile) {
99989             writeList(format, nodes, sourceFile, beginPrint());
99990             return endPrint();
99991         }
99992         function printBundle(bundle) {
99993             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
99994             return endPrint();
99995         }
99996         function printFile(sourceFile) {
99997             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
99998             return endPrint();
99999         }
100000         function printUnparsedSource(unparsed) {
100001             writeUnparsedSource(unparsed, beginPrint());
100002             return endPrint();
100003         }
100004         function writeNode(hint, node, sourceFile, output) {
100005             var previousWriter = writer;
100006             setWriter(output, /*_sourceMapGenerator*/ undefined);
100007             print(hint, node, sourceFile);
100008             reset();
100009             writer = previousWriter;
100010         }
100011         function writeList(format, nodes, sourceFile, output) {
100012             var previousWriter = writer;
100013             setWriter(output, /*_sourceMapGenerator*/ undefined);
100014             if (sourceFile) {
100015                 setSourceFile(sourceFile);
100016             }
100017             emitList(syntheticParent, nodes, format);
100018             reset();
100019             writer = previousWriter;
100020         }
100021         function getTextPosWithWriteLine() {
100022             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
100023         }
100024         function updateOrPushBundleFileTextLike(pos, end, kind) {
100025             var last = ts.lastOrUndefined(bundleFileInfo.sections);
100026             if (last && last.kind === kind) {
100027                 last.end = end;
100028             }
100029             else {
100030                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
100031             }
100032         }
100033         function recordBundleFileInternalSectionStart(node) {
100034             if (recordInternalSection &&
100035                 bundleFileInfo &&
100036                 currentSourceFile &&
100037                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
100038                 ts.isInternalDeclaration(node, currentSourceFile) &&
100039                 sourceFileTextKind !== "internal" /* Internal */) {
100040                 var prevSourceFileTextKind = sourceFileTextKind;
100041                 recordBundleFileTextLikeSection(writer.getTextPos());
100042                 sourceFileTextPos = getTextPosWithWriteLine();
100043                 sourceFileTextKind = "internal" /* Internal */;
100044                 return prevSourceFileTextKind;
100045             }
100046             return undefined;
100047         }
100048         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
100049             if (prevSourceFileTextKind) {
100050                 recordBundleFileTextLikeSection(writer.getTextPos());
100051                 sourceFileTextPos = getTextPosWithWriteLine();
100052                 sourceFileTextKind = prevSourceFileTextKind;
100053             }
100054         }
100055         function recordBundleFileTextLikeSection(end) {
100056             if (sourceFileTextPos < end) {
100057                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
100058                 return true;
100059             }
100060             return false;
100061         }
100062         function writeBundle(bundle, output, sourceMapGenerator) {
100063             var _a;
100064             isOwnFileEmit = false;
100065             var previousWriter = writer;
100066             setWriter(output, sourceMapGenerator);
100067             emitShebangIfNeeded(bundle);
100068             emitPrologueDirectivesIfNeeded(bundle);
100069             emitHelpers(bundle);
100070             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
100071             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
100072                 var prepend = _c[_b];
100073                 writeLine();
100074                 var pos = writer.getTextPos();
100075                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
100076                 if (savedSections)
100077                     bundleFileInfo.sections = [];
100078                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
100079                 if (bundleFileInfo) {
100080                     var newSections = bundleFileInfo.sections;
100081                     bundleFileInfo.sections = savedSections;
100082                     if (prepend.oldFileOfCurrentEmit)
100083                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
100084                     else {
100085                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
100086                         bundleFileInfo.sections.push({
100087                             pos: pos,
100088                             end: writer.getTextPos(),
100089                             kind: "prepend" /* Prepend */,
100090                             data: relativeToBuildInfo(prepend.fileName),
100091                             texts: newSections
100092                         });
100093                     }
100094                 }
100095             }
100096             sourceFileTextPos = getTextPosWithWriteLine();
100097             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
100098                 var sourceFile = _e[_d];
100099                 print(0 /* SourceFile */, sourceFile, sourceFile);
100100             }
100101             if (bundleFileInfo && bundle.sourceFiles.length) {
100102                 var end = writer.getTextPos();
100103                 if (recordBundleFileTextLikeSection(end)) {
100104                     // Store prologues
100105                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
100106                     if (prologues) {
100107                         if (!bundleFileInfo.sources)
100108                             bundleFileInfo.sources = {};
100109                         bundleFileInfo.sources.prologues = prologues;
100110                     }
100111                     // Store helpes
100112                     var helpers = getHelpersFromBundledSourceFiles(bundle);
100113                     if (helpers) {
100114                         if (!bundleFileInfo.sources)
100115                             bundleFileInfo.sources = {};
100116                         bundleFileInfo.sources.helpers = helpers;
100117                     }
100118                 }
100119             }
100120             reset();
100121             writer = previousWriter;
100122         }
100123         function writeUnparsedSource(unparsed, output) {
100124             var previousWriter = writer;
100125             setWriter(output, /*_sourceMapGenerator*/ undefined);
100126             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
100127             reset();
100128             writer = previousWriter;
100129         }
100130         function writeFile(sourceFile, output, sourceMapGenerator) {
100131             isOwnFileEmit = true;
100132             var previousWriter = writer;
100133             setWriter(output, sourceMapGenerator);
100134             emitShebangIfNeeded(sourceFile);
100135             emitPrologueDirectivesIfNeeded(sourceFile);
100136             print(0 /* SourceFile */, sourceFile, sourceFile);
100137             reset();
100138             writer = previousWriter;
100139         }
100140         function beginPrint() {
100141             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
100142         }
100143         function endPrint() {
100144             var text = ownWriter.getText();
100145             ownWriter.clear();
100146             return text;
100147         }
100148         function print(hint, node, sourceFile) {
100149             if (sourceFile) {
100150                 setSourceFile(sourceFile);
100151             }
100152             pipelineEmit(hint, node);
100153         }
100154         function setSourceFile(sourceFile) {
100155             currentSourceFile = sourceFile;
100156             currentLineMap = undefined;
100157             detachedCommentsInfo = undefined;
100158             if (sourceFile) {
100159                 setSourceMapSource(sourceFile);
100160             }
100161         }
100162         function setWriter(_writer, _sourceMapGenerator) {
100163             if (_writer && printerOptions.omitTrailingSemicolon) {
100164                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
100165             }
100166             writer = _writer; // TODO: GH#18217
100167             sourceMapGenerator = _sourceMapGenerator;
100168             sourceMapsDisabled = !writer || !sourceMapGenerator;
100169         }
100170         function reset() {
100171             nodeIdToGeneratedName = [];
100172             autoGeneratedIdToGeneratedName = [];
100173             generatedNames = new ts.Set();
100174             tempFlagsStack = [];
100175             tempFlags = 0 /* Auto */;
100176             reservedNamesStack = [];
100177             currentSourceFile = undefined;
100178             currentLineMap = undefined;
100179             detachedCommentsInfo = undefined;
100180             lastNode = undefined;
100181             lastSubstitution = undefined;
100182             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
100183         }
100184         function getCurrentLineMap() {
100185             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
100186         }
100187         function emit(node) {
100188             if (node === undefined)
100189                 return;
100190             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
100191             var substitute = pipelineEmit(4 /* Unspecified */, node);
100192             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
100193             return substitute;
100194         }
100195         function emitIdentifierName(node) {
100196             if (node === undefined)
100197                 return;
100198             return pipelineEmit(2 /* IdentifierName */, node);
100199         }
100200         function emitExpression(node) {
100201             if (node === undefined)
100202                 return;
100203             return pipelineEmit(1 /* Expression */, node);
100204         }
100205         function emitJsxAttributeValue(node) {
100206             return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
100207         }
100208         function pipelineEmit(emitHint, node) {
100209             var savedLastNode = lastNode;
100210             var savedLastSubstitution = lastSubstitution;
100211             var savedPreserveSourceNewlines = preserveSourceNewlines;
100212             lastNode = node;
100213             lastSubstitution = undefined;
100214             if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
100215                 preserveSourceNewlines = false;
100216             }
100217             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
100218             pipelinePhase(emitHint, node);
100219             ts.Debug.assert(lastNode === node);
100220             var substitute = lastSubstitution;
100221             lastNode = savedLastNode;
100222             lastSubstitution = savedLastSubstitution;
100223             preserveSourceNewlines = savedPreserveSourceNewlines;
100224             return substitute || node;
100225         }
100226         function getPipelinePhase(phase, emitHint, node) {
100227             switch (phase) {
100228                 case 0 /* Notification */:
100229                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
100230                         return pipelineEmitWithNotification;
100231                     }
100232                 // falls through
100233                 case 1 /* Substitution */:
100234                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
100235                         return pipelineEmitWithSubstitution;
100236                     }
100237                 // falls through
100238                 case 2 /* Comments */:
100239                     if (!commentsDisabled && node.kind !== 297 /* SourceFile */) {
100240                         return pipelineEmitWithComments;
100241                     }
100242                 // falls through
100243                 case 3 /* SourceMaps */:
100244                     if (!sourceMapsDisabled && node.kind !== 297 /* SourceFile */ && !ts.isInJsonFile(node)) {
100245                         return pipelineEmitWithSourceMap;
100246                     }
100247                 // falls through
100248                 case 4 /* Emit */:
100249                     return pipelineEmitWithHint;
100250                 default:
100251                     return ts.Debug.assertNever(phase);
100252             }
100253         }
100254         function getNextPipelinePhase(currentPhase, emitHint, node) {
100255             return getPipelinePhase(currentPhase + 1, emitHint, node);
100256         }
100257         function pipelineEmitWithNotification(hint, node) {
100258             ts.Debug.assert(lastNode === node);
100259             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
100260             onEmitNode(hint, node, pipelinePhase);
100261             ts.Debug.assert(lastNode === node);
100262         }
100263         function pipelineEmitWithHint(hint, node) {
100264             ts.Debug.assert(lastNode === node || lastSubstitution === node);
100265             if (hint === 0 /* SourceFile */)
100266                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
100267             if (hint === 2 /* IdentifierName */)
100268                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
100269             if (hint === 6 /* JsxAttributeValue */)
100270                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
100271             if (hint === 3 /* MappedTypeParameter */)
100272                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
100273             if (hint === 5 /* EmbeddedStatement */) {
100274                 ts.Debug.assertNode(node, ts.isEmptyStatement);
100275                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
100276             }
100277             if (hint === 4 /* Unspecified */) {
100278                 if (ts.isKeyword(node.kind))
100279                     return writeTokenNode(node, writeKeyword);
100280                 switch (node.kind) {
100281                     // Pseudo-literals
100282                     case 15 /* TemplateHead */:
100283                     case 16 /* TemplateMiddle */:
100284                     case 17 /* TemplateTail */:
100285                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
100286                     case 299 /* UnparsedSource */:
100287                     case 293 /* UnparsedPrepend */:
100288                         return emitUnparsedSourceOrPrepend(node);
100289                     case 292 /* UnparsedPrologue */:
100290                         return writeUnparsedNode(node);
100291                     case 294 /* UnparsedText */:
100292                     case 295 /* UnparsedInternalText */:
100293                         return emitUnparsedTextLike(node);
100294                     case 296 /* UnparsedSyntheticReference */:
100295                         return emitUnparsedSyntheticReference(node);
100296                     // Identifiers
100297                     case 78 /* Identifier */:
100298                         return emitIdentifier(node);
100299                     // PrivateIdentifiers
100300                     case 79 /* PrivateIdentifier */:
100301                         return emitPrivateIdentifier(node);
100302                     // Parse tree nodes
100303                     // Names
100304                     case 157 /* QualifiedName */:
100305                         return emitQualifiedName(node);
100306                     case 158 /* ComputedPropertyName */:
100307                         return emitComputedPropertyName(node);
100308                     // Signature elements
100309                     case 159 /* TypeParameter */:
100310                         return emitTypeParameter(node);
100311                     case 160 /* Parameter */:
100312                         return emitParameter(node);
100313                     case 161 /* Decorator */:
100314                         return emitDecorator(node);
100315                     // Type members
100316                     case 162 /* PropertySignature */:
100317                         return emitPropertySignature(node);
100318                     case 163 /* PropertyDeclaration */:
100319                         return emitPropertyDeclaration(node);
100320                     case 164 /* MethodSignature */:
100321                         return emitMethodSignature(node);
100322                     case 165 /* MethodDeclaration */:
100323                         return emitMethodDeclaration(node);
100324                     case 166 /* Constructor */:
100325                         return emitConstructor(node);
100326                     case 167 /* GetAccessor */:
100327                     case 168 /* SetAccessor */:
100328                         return emitAccessorDeclaration(node);
100329                     case 169 /* CallSignature */:
100330                         return emitCallSignature(node);
100331                     case 170 /* ConstructSignature */:
100332                         return emitConstructSignature(node);
100333                     case 171 /* IndexSignature */:
100334                         return emitIndexSignature(node);
100335                     case 194 /* TemplateLiteralTypeSpan */:
100336                         return emitTemplateTypeSpan(node);
100337                     // Types
100338                     case 172 /* TypePredicate */:
100339                         return emitTypePredicate(node);
100340                     case 173 /* TypeReference */:
100341                         return emitTypeReference(node);
100342                     case 174 /* FunctionType */:
100343                         return emitFunctionType(node);
100344                     case 308 /* JSDocFunctionType */:
100345                         return emitJSDocFunctionType(node);
100346                     case 175 /* ConstructorType */:
100347                         return emitConstructorType(node);
100348                     case 176 /* TypeQuery */:
100349                         return emitTypeQuery(node);
100350                     case 177 /* TypeLiteral */:
100351                         return emitTypeLiteral(node);
100352                     case 178 /* ArrayType */:
100353                         return emitArrayType(node);
100354                     case 179 /* TupleType */:
100355                         return emitTupleType(node);
100356                     case 180 /* OptionalType */:
100357                         return emitOptionalType(node);
100358                     case 182 /* UnionType */:
100359                         return emitUnionType(node);
100360                     case 183 /* IntersectionType */:
100361                         return emitIntersectionType(node);
100362                     case 184 /* ConditionalType */:
100363                         return emitConditionalType(node);
100364                     case 185 /* InferType */:
100365                         return emitInferType(node);
100366                     case 186 /* ParenthesizedType */:
100367                         return emitParenthesizedType(node);
100368                     case 223 /* ExpressionWithTypeArguments */:
100369                         return emitExpressionWithTypeArguments(node);
100370                     case 187 /* ThisType */:
100371                         return emitThisType();
100372                     case 188 /* TypeOperator */:
100373                         return emitTypeOperator(node);
100374                     case 189 /* IndexedAccessType */:
100375                         return emitIndexedAccessType(node);
100376                     case 190 /* MappedType */:
100377                         return emitMappedType(node);
100378                     case 191 /* LiteralType */:
100379                         return emitLiteralType(node);
100380                     case 193 /* TemplateLiteralType */:
100381                         return emitTemplateType(node);
100382                     case 195 /* ImportType */:
100383                         return emitImportTypeNode(node);
100384                     case 303 /* JSDocAllType */:
100385                         writePunctuation("*");
100386                         return;
100387                     case 304 /* JSDocUnknownType */:
100388                         writePunctuation("?");
100389                         return;
100390                     case 305 /* JSDocNullableType */:
100391                         return emitJSDocNullableType(node);
100392                     case 306 /* JSDocNonNullableType */:
100393                         return emitJSDocNonNullableType(node);
100394                     case 307 /* JSDocOptionalType */:
100395                         return emitJSDocOptionalType(node);
100396                     case 181 /* RestType */:
100397                     case 309 /* JSDocVariadicType */:
100398                         return emitRestOrJSDocVariadicType(node);
100399                     case 192 /* NamedTupleMember */:
100400                         return emitNamedTupleMember(node);
100401                     // Binding patterns
100402                     case 196 /* ObjectBindingPattern */:
100403                         return emitObjectBindingPattern(node);
100404                     case 197 /* ArrayBindingPattern */:
100405                         return emitArrayBindingPattern(node);
100406                     case 198 /* BindingElement */:
100407                         return emitBindingElement(node);
100408                     // Misc
100409                     case 228 /* TemplateSpan */:
100410                         return emitTemplateSpan(node);
100411                     case 229 /* SemicolonClassElement */:
100412                         return emitSemicolonClassElement();
100413                     // Statements
100414                     case 230 /* Block */:
100415                         return emitBlock(node);
100416                     case 232 /* VariableStatement */:
100417                         return emitVariableStatement(node);
100418                     case 231 /* EmptyStatement */:
100419                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
100420                     case 233 /* ExpressionStatement */:
100421                         return emitExpressionStatement(node);
100422                     case 234 /* IfStatement */:
100423                         return emitIfStatement(node);
100424                     case 235 /* DoStatement */:
100425                         return emitDoStatement(node);
100426                     case 236 /* WhileStatement */:
100427                         return emitWhileStatement(node);
100428                     case 237 /* ForStatement */:
100429                         return emitForStatement(node);
100430                     case 238 /* ForInStatement */:
100431                         return emitForInStatement(node);
100432                     case 239 /* ForOfStatement */:
100433                         return emitForOfStatement(node);
100434                     case 240 /* ContinueStatement */:
100435                         return emitContinueStatement(node);
100436                     case 241 /* BreakStatement */:
100437                         return emitBreakStatement(node);
100438                     case 242 /* ReturnStatement */:
100439                         return emitReturnStatement(node);
100440                     case 243 /* WithStatement */:
100441                         return emitWithStatement(node);
100442                     case 244 /* SwitchStatement */:
100443                         return emitSwitchStatement(node);
100444                     case 245 /* LabeledStatement */:
100445                         return emitLabeledStatement(node);
100446                     case 246 /* ThrowStatement */:
100447                         return emitThrowStatement(node);
100448                     case 247 /* TryStatement */:
100449                         return emitTryStatement(node);
100450                     case 248 /* DebuggerStatement */:
100451                         return emitDebuggerStatement(node);
100452                     // Declarations
100453                     case 249 /* VariableDeclaration */:
100454                         return emitVariableDeclaration(node);
100455                     case 250 /* VariableDeclarationList */:
100456                         return emitVariableDeclarationList(node);
100457                     case 251 /* FunctionDeclaration */:
100458                         return emitFunctionDeclaration(node);
100459                     case 252 /* ClassDeclaration */:
100460                         return emitClassDeclaration(node);
100461                     case 253 /* InterfaceDeclaration */:
100462                         return emitInterfaceDeclaration(node);
100463                     case 254 /* TypeAliasDeclaration */:
100464                         return emitTypeAliasDeclaration(node);
100465                     case 255 /* EnumDeclaration */:
100466                         return emitEnumDeclaration(node);
100467                     case 256 /* ModuleDeclaration */:
100468                         return emitModuleDeclaration(node);
100469                     case 257 /* ModuleBlock */:
100470                         return emitModuleBlock(node);
100471                     case 258 /* CaseBlock */:
100472                         return emitCaseBlock(node);
100473                     case 259 /* NamespaceExportDeclaration */:
100474                         return emitNamespaceExportDeclaration(node);
100475                     case 260 /* ImportEqualsDeclaration */:
100476                         return emitImportEqualsDeclaration(node);
100477                     case 261 /* ImportDeclaration */:
100478                         return emitImportDeclaration(node);
100479                     case 262 /* ImportClause */:
100480                         return emitImportClause(node);
100481                     case 263 /* NamespaceImport */:
100482                         return emitNamespaceImport(node);
100483                     case 269 /* NamespaceExport */:
100484                         return emitNamespaceExport(node);
100485                     case 264 /* NamedImports */:
100486                         return emitNamedImports(node);
100487                     case 265 /* ImportSpecifier */:
100488                         return emitImportSpecifier(node);
100489                     case 266 /* ExportAssignment */:
100490                         return emitExportAssignment(node);
100491                     case 267 /* ExportDeclaration */:
100492                         return emitExportDeclaration(node);
100493                     case 268 /* NamedExports */:
100494                         return emitNamedExports(node);
100495                     case 270 /* ExportSpecifier */:
100496                         return emitExportSpecifier(node);
100497                     case 271 /* MissingDeclaration */:
100498                         return;
100499                     // Module references
100500                     case 272 /* ExternalModuleReference */:
100501                         return emitExternalModuleReference(node);
100502                     // JSX (non-expression)
100503                     case 11 /* JsxText */:
100504                         return emitJsxText(node);
100505                     case 275 /* JsxOpeningElement */:
100506                     case 278 /* JsxOpeningFragment */:
100507                         return emitJsxOpeningElementOrFragment(node);
100508                     case 276 /* JsxClosingElement */:
100509                     case 279 /* JsxClosingFragment */:
100510                         return emitJsxClosingElementOrFragment(node);
100511                     case 280 /* JsxAttribute */:
100512                         return emitJsxAttribute(node);
100513                     case 281 /* JsxAttributes */:
100514                         return emitJsxAttributes(node);
100515                     case 282 /* JsxSpreadAttribute */:
100516                         return emitJsxSpreadAttribute(node);
100517                     case 283 /* JsxExpression */:
100518                         return emitJsxExpression(node);
100519                     // Clauses
100520                     case 284 /* CaseClause */:
100521                         return emitCaseClause(node);
100522                     case 285 /* DefaultClause */:
100523                         return emitDefaultClause(node);
100524                     case 286 /* HeritageClause */:
100525                         return emitHeritageClause(node);
100526                     case 287 /* CatchClause */:
100527                         return emitCatchClause(node);
100528                     // Property assignments
100529                     case 288 /* PropertyAssignment */:
100530                         return emitPropertyAssignment(node);
100531                     case 289 /* ShorthandPropertyAssignment */:
100532                         return emitShorthandPropertyAssignment(node);
100533                     case 290 /* SpreadAssignment */:
100534                         return emitSpreadAssignment(node);
100535                     // Enum
100536                     case 291 /* EnumMember */:
100537                         return emitEnumMember(node);
100538                     // JSDoc nodes (only used in codefixes currently)
100539                     case 326 /* JSDocParameterTag */:
100540                     case 333 /* JSDocPropertyTag */:
100541                         return emitJSDocPropertyLikeTag(node);
100542                     case 327 /* JSDocReturnTag */:
100543                     case 329 /* JSDocTypeTag */:
100544                     case 328 /* JSDocThisTag */:
100545                     case 325 /* JSDocEnumTag */:
100546                         return emitJSDocSimpleTypedTag(node);
100547                     case 316 /* JSDocImplementsTag */:
100548                     case 315 /* JSDocAugmentsTag */:
100549                         return emitJSDocHeritageTag(node);
100550                     case 330 /* JSDocTemplateTag */:
100551                         return emitJSDocTemplateTag(node);
100552                     case 331 /* JSDocTypedefTag */:
100553                         return emitJSDocTypedefTag(node);
100554                     case 324 /* JSDocCallbackTag */:
100555                         return emitJSDocCallbackTag(node);
100556                     case 313 /* JSDocSignature */:
100557                         return emitJSDocSignature(node);
100558                     case 312 /* JSDocTypeLiteral */:
100559                         return emitJSDocTypeLiteral(node);
100560                     case 319 /* JSDocClassTag */:
100561                     case 314 /* JSDocTag */:
100562                         return emitJSDocSimpleTag(node);
100563                     case 332 /* JSDocSeeTag */:
100564                         return emitJSDocSeeTag(node);
100565                     case 302 /* JSDocNameReference */:
100566                         return emitJSDocNameReference(node);
100567                     case 311 /* JSDocComment */:
100568                         return emitJSDoc(node);
100569                     // Transformation nodes (ignored)
100570                 }
100571                 if (ts.isExpression(node)) {
100572                     hint = 1 /* Expression */;
100573                     if (substituteNode !== ts.noEmitSubstitution) {
100574                         lastSubstitution = node = substituteNode(hint, node);
100575                     }
100576                 }
100577                 else if (ts.isToken(node)) {
100578                     return writeTokenNode(node, writePunctuation);
100579                 }
100580             }
100581             if (hint === 1 /* Expression */) {
100582                 switch (node.kind) {
100583                     // Literals
100584                     case 8 /* NumericLiteral */:
100585                     case 9 /* BigIntLiteral */:
100586                         return emitNumericOrBigIntLiteral(node);
100587                     case 10 /* StringLiteral */:
100588                     case 13 /* RegularExpressionLiteral */:
100589                     case 14 /* NoSubstitutionTemplateLiteral */:
100590                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
100591                     // Identifiers
100592                     case 78 /* Identifier */:
100593                         return emitIdentifier(node);
100594                     // Reserved words
100595                     case 94 /* FalseKeyword */:
100596                     case 103 /* NullKeyword */:
100597                     case 105 /* SuperKeyword */:
100598                     case 109 /* TrueKeyword */:
100599                     case 107 /* ThisKeyword */:
100600                     case 99 /* ImportKeyword */:
100601                         writeTokenNode(node, writeKeyword);
100602                         return;
100603                     // Expressions
100604                     case 199 /* ArrayLiteralExpression */:
100605                         return emitArrayLiteralExpression(node);
100606                     case 200 /* ObjectLiteralExpression */:
100607                         return emitObjectLiteralExpression(node);
100608                     case 201 /* PropertyAccessExpression */:
100609                         return emitPropertyAccessExpression(node);
100610                     case 202 /* ElementAccessExpression */:
100611                         return emitElementAccessExpression(node);
100612                     case 203 /* CallExpression */:
100613                         return emitCallExpression(node);
100614                     case 204 /* NewExpression */:
100615                         return emitNewExpression(node);
100616                     case 205 /* TaggedTemplateExpression */:
100617                         return emitTaggedTemplateExpression(node);
100618                     case 206 /* TypeAssertionExpression */:
100619                         return emitTypeAssertionExpression(node);
100620                     case 207 /* ParenthesizedExpression */:
100621                         return emitParenthesizedExpression(node);
100622                     case 208 /* FunctionExpression */:
100623                         return emitFunctionExpression(node);
100624                     case 209 /* ArrowFunction */:
100625                         return emitArrowFunction(node);
100626                     case 210 /* DeleteExpression */:
100627                         return emitDeleteExpression(node);
100628                     case 211 /* TypeOfExpression */:
100629                         return emitTypeOfExpression(node);
100630                     case 212 /* VoidExpression */:
100631                         return emitVoidExpression(node);
100632                     case 213 /* AwaitExpression */:
100633                         return emitAwaitExpression(node);
100634                     case 214 /* PrefixUnaryExpression */:
100635                         return emitPrefixUnaryExpression(node);
100636                     case 215 /* PostfixUnaryExpression */:
100637                         return emitPostfixUnaryExpression(node);
100638                     case 216 /* BinaryExpression */:
100639                         return emitBinaryExpression(node);
100640                     case 217 /* ConditionalExpression */:
100641                         return emitConditionalExpression(node);
100642                     case 218 /* TemplateExpression */:
100643                         return emitTemplateExpression(node);
100644                     case 219 /* YieldExpression */:
100645                         return emitYieldExpression(node);
100646                     case 220 /* SpreadElement */:
100647                         return emitSpreadExpression(node);
100648                     case 221 /* ClassExpression */:
100649                         return emitClassExpression(node);
100650                     case 222 /* OmittedExpression */:
100651                         return;
100652                     case 224 /* AsExpression */:
100653                         return emitAsExpression(node);
100654                     case 225 /* NonNullExpression */:
100655                         return emitNonNullExpression(node);
100656                     case 226 /* MetaProperty */:
100657                         return emitMetaProperty(node);
100658                     // JSX
100659                     case 273 /* JsxElement */:
100660                         return emitJsxElement(node);
100661                     case 274 /* JsxSelfClosingElement */:
100662                         return emitJsxSelfClosingElement(node);
100663                     case 277 /* JsxFragment */:
100664                         return emitJsxFragment(node);
100665                     // Transformation nodes
100666                     case 336 /* PartiallyEmittedExpression */:
100667                         return emitPartiallyEmittedExpression(node);
100668                     case 337 /* CommaListExpression */:
100669                         return emitCommaList(node);
100670                 }
100671             }
100672         }
100673         function emitMappedTypeParameter(node) {
100674             emit(node.name);
100675             writeSpace();
100676             writeKeyword("in");
100677             writeSpace();
100678             emit(node.constraint);
100679         }
100680         function pipelineEmitWithSubstitution(hint, node) {
100681             ts.Debug.assert(lastNode === node || lastSubstitution === node);
100682             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
100683             pipelinePhase(hint, lastSubstitution);
100684             ts.Debug.assert(lastNode === node || lastSubstitution === node);
100685         }
100686         function getHelpersFromBundledSourceFiles(bundle) {
100687             var result;
100688             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
100689                 return undefined;
100690             }
100691             var bundledHelpers = new ts.Map();
100692             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
100693                 var sourceFile = _b[_a];
100694                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
100695                 var helpers = getSortedEmitHelpers(sourceFile);
100696                 if (!helpers)
100697                     continue;
100698                 for (var _c = 0, helpers_5 = helpers; _c < helpers_5.length; _c++) {
100699                     var helper = helpers_5[_c];
100700                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
100701                         bundledHelpers.set(helper.name, true);
100702                         (result || (result = [])).push(helper.name);
100703                     }
100704                 }
100705             }
100706             return result;
100707         }
100708         function emitHelpers(node) {
100709             var helpersEmitted = false;
100710             var bundle = node.kind === 298 /* Bundle */ ? node : undefined;
100711             if (bundle && moduleKind === ts.ModuleKind.None) {
100712                 return;
100713             }
100714             var numPrepends = bundle ? bundle.prepends.length : 0;
100715             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
100716             for (var i = 0; i < numNodes; i++) {
100717                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
100718                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
100719                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
100720                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
100721                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
100722                 if (helpers) {
100723                     for (var _a = 0, helpers_6 = helpers; _a < helpers_6.length; _a++) {
100724                         var helper = helpers_6[_a];
100725                         if (!helper.scoped) {
100726                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
100727                             // option is set, or if it can be imported and the importHelpers compiler
100728                             // option is set.
100729                             if (shouldSkip)
100730                                 continue;
100731                             // Skip the helper if it can be bundled but hasn't already been emitted and we
100732                             // are emitting a bundled module.
100733                             if (shouldBundle) {
100734                                 if (bundledHelpers.get(helper.name)) {
100735                                     continue;
100736                                 }
100737                                 bundledHelpers.set(helper.name, true);
100738                             }
100739                         }
100740                         else if (bundle) {
100741                             // Skip the helper if it is scoped and we are emitting bundled helpers
100742                             continue;
100743                         }
100744                         var pos = getTextPosWithWriteLine();
100745                         if (typeof helper.text === "string") {
100746                             writeLines(helper.text);
100747                         }
100748                         else {
100749                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
100750                         }
100751                         if (bundleFileInfo)
100752                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
100753                         helpersEmitted = true;
100754                     }
100755                 }
100756             }
100757             return helpersEmitted;
100758         }
100759         function getSortedEmitHelpers(node) {
100760             var helpers = ts.getEmitHelpers(node);
100761             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
100762         }
100763         //
100764         // Literals/Pseudo-literals
100765         //
100766         // SyntaxKind.NumericLiteral
100767         // SyntaxKind.BigIntLiteral
100768         function emitNumericOrBigIntLiteral(node) {
100769             emitLiteral(node, /*jsxAttributeEscape*/ false);
100770         }
100771         // SyntaxKind.StringLiteral
100772         // SyntaxKind.RegularExpressionLiteral
100773         // SyntaxKind.NoSubstitutionTemplateLiteral
100774         // SyntaxKind.TemplateHead
100775         // SyntaxKind.TemplateMiddle
100776         // SyntaxKind.TemplateTail
100777         function emitLiteral(node, jsxAttributeEscape) {
100778             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
100779             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
100780                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
100781                 writeLiteral(text);
100782             }
100783             else {
100784                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
100785                 writeStringLiteral(text);
100786             }
100787         }
100788         // SyntaxKind.UnparsedSource
100789         // SyntaxKind.UnparsedPrepend
100790         function emitUnparsedSourceOrPrepend(unparsed) {
100791             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
100792                 var text = _b[_a];
100793                 writeLine();
100794                 emit(text);
100795             }
100796         }
100797         // SyntaxKind.UnparsedPrologue
100798         // SyntaxKind.UnparsedText
100799         // SyntaxKind.UnparsedInternal
100800         // SyntaxKind.UnparsedSyntheticReference
100801         function writeUnparsedNode(unparsed) {
100802             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
100803         }
100804         // SyntaxKind.UnparsedText
100805         // SyntaxKind.UnparsedInternal
100806         function emitUnparsedTextLike(unparsed) {
100807             var pos = getTextPosWithWriteLine();
100808             writeUnparsedNode(unparsed);
100809             if (bundleFileInfo) {
100810                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 294 /* UnparsedText */ ?
100811                     "text" /* Text */ :
100812                     "internal" /* Internal */);
100813             }
100814         }
100815         // SyntaxKind.UnparsedSyntheticReference
100816         function emitUnparsedSyntheticReference(unparsed) {
100817             var pos = getTextPosWithWriteLine();
100818             writeUnparsedNode(unparsed);
100819             if (bundleFileInfo) {
100820                 var section = ts.clone(unparsed.section);
100821                 section.pos = pos;
100822                 section.end = writer.getTextPos();
100823                 bundleFileInfo.sections.push(section);
100824             }
100825         }
100826         //
100827         // Identifiers
100828         //
100829         function emitIdentifier(node) {
100830             var writeText = node.symbol ? writeSymbol : write;
100831             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
100832             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
100833         }
100834         //
100835         // Names
100836         //
100837         function emitPrivateIdentifier(node) {
100838             var writeText = node.symbol ? writeSymbol : write;
100839             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
100840         }
100841         function emitQualifiedName(node) {
100842             emitEntityName(node.left);
100843             writePunctuation(".");
100844             emit(node.right);
100845         }
100846         function emitEntityName(node) {
100847             if (node.kind === 78 /* Identifier */) {
100848                 emitExpression(node);
100849             }
100850             else {
100851                 emit(node);
100852             }
100853         }
100854         function emitComputedPropertyName(node) {
100855             writePunctuation("[");
100856             emitExpression(node.expression);
100857             writePunctuation("]");
100858         }
100859         //
100860         // Signature elements
100861         //
100862         function emitTypeParameter(node) {
100863             emit(node.name);
100864             if (node.constraint) {
100865                 writeSpace();
100866                 writeKeyword("extends");
100867                 writeSpace();
100868                 emit(node.constraint);
100869             }
100870             if (node.default) {
100871                 writeSpace();
100872                 writeOperator("=");
100873                 writeSpace();
100874                 emit(node.default);
100875             }
100876         }
100877         function emitParameter(node) {
100878             emitDecorators(node, node.decorators);
100879             emitModifiers(node, node.modifiers);
100880             emit(node.dotDotDotToken);
100881             emitNodeWithWriter(node.name, writeParameter);
100882             emit(node.questionToken);
100883             if (node.parent && node.parent.kind === 308 /* JSDocFunctionType */ && !node.name) {
100884                 emit(node.type);
100885             }
100886             else {
100887                 emitTypeAnnotation(node.type);
100888             }
100889             // 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.
100890             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);
100891         }
100892         function emitDecorator(decorator) {
100893             writePunctuation("@");
100894             emitExpression(decorator.expression);
100895         }
100896         //
100897         // Type members
100898         //
100899         function emitPropertySignature(node) {
100900             emitDecorators(node, node.decorators);
100901             emitModifiers(node, node.modifiers);
100902             emitNodeWithWriter(node.name, writeProperty);
100903             emit(node.questionToken);
100904             emitTypeAnnotation(node.type);
100905             writeTrailingSemicolon();
100906         }
100907         function emitPropertyDeclaration(node) {
100908             emitDecorators(node, node.decorators);
100909             emitModifiers(node, node.modifiers);
100910             emit(node.name);
100911             emit(node.questionToken);
100912             emit(node.exclamationToken);
100913             emitTypeAnnotation(node.type);
100914             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
100915             writeTrailingSemicolon();
100916         }
100917         function emitMethodSignature(node) {
100918             pushNameGenerationScope(node);
100919             emitDecorators(node, node.decorators);
100920             emitModifiers(node, node.modifiers);
100921             emit(node.name);
100922             emit(node.questionToken);
100923             emitTypeParameters(node, node.typeParameters);
100924             emitParameters(node, node.parameters);
100925             emitTypeAnnotation(node.type);
100926             writeTrailingSemicolon();
100927             popNameGenerationScope(node);
100928         }
100929         function emitMethodDeclaration(node) {
100930             emitDecorators(node, node.decorators);
100931             emitModifiers(node, node.modifiers);
100932             emit(node.asteriskToken);
100933             emit(node.name);
100934             emit(node.questionToken);
100935             emitSignatureAndBody(node, emitSignatureHead);
100936         }
100937         function emitConstructor(node) {
100938             emitModifiers(node, node.modifiers);
100939             writeKeyword("constructor");
100940             emitSignatureAndBody(node, emitSignatureHead);
100941         }
100942         function emitAccessorDeclaration(node) {
100943             emitDecorators(node, node.decorators);
100944             emitModifiers(node, node.modifiers);
100945             writeKeyword(node.kind === 167 /* GetAccessor */ ? "get" : "set");
100946             writeSpace();
100947             emit(node.name);
100948             emitSignatureAndBody(node, emitSignatureHead);
100949         }
100950         function emitCallSignature(node) {
100951             pushNameGenerationScope(node);
100952             emitDecorators(node, node.decorators);
100953             emitModifiers(node, node.modifiers);
100954             emitTypeParameters(node, node.typeParameters);
100955             emitParameters(node, node.parameters);
100956             emitTypeAnnotation(node.type);
100957             writeTrailingSemicolon();
100958             popNameGenerationScope(node);
100959         }
100960         function emitConstructSignature(node) {
100961             pushNameGenerationScope(node);
100962             emitDecorators(node, node.decorators);
100963             emitModifiers(node, node.modifiers);
100964             writeKeyword("new");
100965             writeSpace();
100966             emitTypeParameters(node, node.typeParameters);
100967             emitParameters(node, node.parameters);
100968             emitTypeAnnotation(node.type);
100969             writeTrailingSemicolon();
100970             popNameGenerationScope(node);
100971         }
100972         function emitIndexSignature(node) {
100973             emitDecorators(node, node.decorators);
100974             emitModifiers(node, node.modifiers);
100975             emitParametersForIndexSignature(node, node.parameters);
100976             emitTypeAnnotation(node.type);
100977             writeTrailingSemicolon();
100978         }
100979         function emitTemplateTypeSpan(node) {
100980             emit(node.type);
100981             emit(node.literal);
100982         }
100983         function emitSemicolonClassElement() {
100984             writeTrailingSemicolon();
100985         }
100986         //
100987         // Types
100988         //
100989         function emitTypePredicate(node) {
100990             if (node.assertsModifier) {
100991                 emit(node.assertsModifier);
100992                 writeSpace();
100993             }
100994             emit(node.parameterName);
100995             if (node.type) {
100996                 writeSpace();
100997                 writeKeyword("is");
100998                 writeSpace();
100999                 emit(node.type);
101000             }
101001         }
101002         function emitTypeReference(node) {
101003             emit(node.typeName);
101004             emitTypeArguments(node, node.typeArguments);
101005         }
101006         function emitFunctionType(node) {
101007             pushNameGenerationScope(node);
101008             emitTypeParameters(node, node.typeParameters);
101009             emitParametersForArrow(node, node.parameters);
101010             writeSpace();
101011             writePunctuation("=>");
101012             writeSpace();
101013             emit(node.type);
101014             popNameGenerationScope(node);
101015         }
101016         function emitJSDocFunctionType(node) {
101017             writeKeyword("function");
101018             emitParameters(node, node.parameters);
101019             writePunctuation(":");
101020             emit(node.type);
101021         }
101022         function emitJSDocNullableType(node) {
101023             writePunctuation("?");
101024             emit(node.type);
101025         }
101026         function emitJSDocNonNullableType(node) {
101027             writePunctuation("!");
101028             emit(node.type);
101029         }
101030         function emitJSDocOptionalType(node) {
101031             emit(node.type);
101032             writePunctuation("=");
101033         }
101034         function emitConstructorType(node) {
101035             pushNameGenerationScope(node);
101036             writeKeyword("new");
101037             writeSpace();
101038             emitTypeParameters(node, node.typeParameters);
101039             emitParameters(node, node.parameters);
101040             writeSpace();
101041             writePunctuation("=>");
101042             writeSpace();
101043             emit(node.type);
101044             popNameGenerationScope(node);
101045         }
101046         function emitTypeQuery(node) {
101047             writeKeyword("typeof");
101048             writeSpace();
101049             emit(node.exprName);
101050         }
101051         function emitTypeLiteral(node) {
101052             writePunctuation("{");
101053             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
101054             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
101055             writePunctuation("}");
101056         }
101057         function emitArrayType(node) {
101058             emit(node.elementType);
101059             writePunctuation("[");
101060             writePunctuation("]");
101061         }
101062         function emitRestOrJSDocVariadicType(node) {
101063             writePunctuation("...");
101064             emit(node.type);
101065         }
101066         function emitTupleType(node) {
101067             emitTokenWithComment(22 /* OpenBracketToken */, node.pos, writePunctuation, node);
101068             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 528 /* SingleLineTupleTypeElements */ : 657 /* MultiLineTupleTypeElements */;
101069             emitList(node, node.elements, flags | 524288 /* NoSpaceIfEmpty */);
101070             emitTokenWithComment(23 /* CloseBracketToken */, node.elements.end, writePunctuation, node);
101071         }
101072         function emitNamedTupleMember(node) {
101073             emit(node.dotDotDotToken);
101074             emit(node.name);
101075             emit(node.questionToken);
101076             emitTokenWithComment(58 /* ColonToken */, node.name.end, writePunctuation, node);
101077             writeSpace();
101078             emit(node.type);
101079         }
101080         function emitOptionalType(node) {
101081             emit(node.type);
101082             writePunctuation("?");
101083         }
101084         function emitUnionType(node) {
101085             emitList(node, node.types, 516 /* UnionTypeConstituents */);
101086         }
101087         function emitIntersectionType(node) {
101088             emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
101089         }
101090         function emitConditionalType(node) {
101091             emit(node.checkType);
101092             writeSpace();
101093             writeKeyword("extends");
101094             writeSpace();
101095             emit(node.extendsType);
101096             writeSpace();
101097             writePunctuation("?");
101098             writeSpace();
101099             emit(node.trueType);
101100             writeSpace();
101101             writePunctuation(":");
101102             writeSpace();
101103             emit(node.falseType);
101104         }
101105         function emitInferType(node) {
101106             writeKeyword("infer");
101107             writeSpace();
101108             emit(node.typeParameter);
101109         }
101110         function emitParenthesizedType(node) {
101111             writePunctuation("(");
101112             emit(node.type);
101113             writePunctuation(")");
101114         }
101115         function emitThisType() {
101116             writeKeyword("this");
101117         }
101118         function emitTypeOperator(node) {
101119             writeTokenText(node.operator, writeKeyword);
101120             writeSpace();
101121             emit(node.type);
101122         }
101123         function emitIndexedAccessType(node) {
101124             emit(node.objectType);
101125             writePunctuation("[");
101126             emit(node.indexType);
101127             writePunctuation("]");
101128         }
101129         function emitMappedType(node) {
101130             var emitFlags = ts.getEmitFlags(node);
101131             writePunctuation("{");
101132             if (emitFlags & 1 /* SingleLine */) {
101133                 writeSpace();
101134             }
101135             else {
101136                 writeLine();
101137                 increaseIndent();
101138             }
101139             if (node.readonlyToken) {
101140                 emit(node.readonlyToken);
101141                 if (node.readonlyToken.kind !== 142 /* ReadonlyKeyword */) {
101142                     writeKeyword("readonly");
101143                 }
101144                 writeSpace();
101145             }
101146             writePunctuation("[");
101147             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
101148             if (node.nameType) {
101149                 writeSpace();
101150                 writeKeyword("as");
101151                 writeSpace();
101152                 emit(node.nameType);
101153             }
101154             writePunctuation("]");
101155             if (node.questionToken) {
101156                 emit(node.questionToken);
101157                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
101158                     writePunctuation("?");
101159                 }
101160             }
101161             writePunctuation(":");
101162             writeSpace();
101163             emit(node.type);
101164             writeTrailingSemicolon();
101165             if (emitFlags & 1 /* SingleLine */) {
101166                 writeSpace();
101167             }
101168             else {
101169                 writeLine();
101170                 decreaseIndent();
101171             }
101172             writePunctuation("}");
101173         }
101174         function emitLiteralType(node) {
101175             emitExpression(node.literal);
101176         }
101177         function emitTemplateType(node) {
101178             emit(node.head);
101179             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
101180         }
101181         function emitImportTypeNode(node) {
101182             if (node.isTypeOf) {
101183                 writeKeyword("typeof");
101184                 writeSpace();
101185             }
101186             writeKeyword("import");
101187             writePunctuation("(");
101188             emit(node.argument);
101189             writePunctuation(")");
101190             if (node.qualifier) {
101191                 writePunctuation(".");
101192                 emit(node.qualifier);
101193             }
101194             emitTypeArguments(node, node.typeArguments);
101195         }
101196         //
101197         // Binding patterns
101198         //
101199         function emitObjectBindingPattern(node) {
101200             writePunctuation("{");
101201             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
101202             writePunctuation("}");
101203         }
101204         function emitArrayBindingPattern(node) {
101205             writePunctuation("[");
101206             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
101207             writePunctuation("]");
101208         }
101209         function emitBindingElement(node) {
101210             emit(node.dotDotDotToken);
101211             if (node.propertyName) {
101212                 emit(node.propertyName);
101213                 writePunctuation(":");
101214                 writeSpace();
101215             }
101216             emit(node.name);
101217             emitInitializer(node.initializer, node.name.end, node);
101218         }
101219         //
101220         // Expressions
101221         //
101222         function emitArrayLiteralExpression(node) {
101223             var elements = node.elements;
101224             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
101225             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
101226         }
101227         function emitObjectLiteralExpression(node) {
101228             ts.forEach(node.properties, generateMemberNames);
101229             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
101230             if (indentedFlag) {
101231                 increaseIndent();
101232             }
101233             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
101234             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
101235             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
101236             if (indentedFlag) {
101237                 decreaseIndent();
101238             }
101239         }
101240         function emitPropertyAccessExpression(node) {
101241             var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
101242             var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos);
101243             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
101244             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
101245             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
101246             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
101247                 mayNeedDotDotForPropertyAccess(expression) &&
101248                 !writer.hasTrailingComment() &&
101249                 !writer.hasTrailingWhitespace();
101250             if (shouldEmitDotDot) {
101251                 writePunctuation(".");
101252             }
101253             if (node.questionDotToken) {
101254                 emit(token);
101255             }
101256             else {
101257                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
101258             }
101259             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
101260             emit(node.name);
101261             decreaseIndentIf(linesBeforeDot, linesAfterDot);
101262         }
101263         // 1..toString is a valid property access, emit a dot after the literal
101264         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
101265         function mayNeedDotDotForPropertyAccess(expression) {
101266             expression = ts.skipPartiallyEmittedExpressions(expression);
101267             if (ts.isNumericLiteral(expression)) {
101268                 // check if numeric literal is a decimal literal that was originally written with a dot
101269                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
101270                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
101271                 // if the expression doesn't have any comments that will be emitted.
101272                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
101273             }
101274             else if (ts.isAccessExpression(expression)) {
101275                 // check if constant enum value is integer
101276                 var constantValue = ts.getConstantValue(expression);
101277                 // isFinite handles cases when constantValue is undefined
101278                 return typeof constantValue === "number" && isFinite(constantValue)
101279                     && Math.floor(constantValue) === constantValue;
101280             }
101281         }
101282         function emitElementAccessExpression(node) {
101283             emitExpression(node.expression);
101284             emit(node.questionDotToken);
101285             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
101286             emitExpression(node.argumentExpression);
101287             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
101288         }
101289         function emitCallExpression(node) {
101290             emitExpression(node.expression);
101291             emit(node.questionDotToken);
101292             emitTypeArguments(node, node.typeArguments);
101293             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
101294         }
101295         function emitNewExpression(node) {
101296             emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node);
101297             writeSpace();
101298             emitExpression(node.expression);
101299             emitTypeArguments(node, node.typeArguments);
101300             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
101301         }
101302         function emitTaggedTemplateExpression(node) {
101303             emitExpression(node.tag);
101304             emitTypeArguments(node, node.typeArguments);
101305             writeSpace();
101306             emitExpression(node.template);
101307         }
101308         function emitTypeAssertionExpression(node) {
101309             writePunctuation("<");
101310             emit(node.type);
101311             writePunctuation(">");
101312             emitExpression(node.expression);
101313         }
101314         function emitParenthesizedExpression(node) {
101315             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
101316             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
101317             emitExpression(node.expression);
101318             writeLineSeparatorsAfter(node.expression, node);
101319             decreaseIndentIf(indented);
101320             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
101321         }
101322         function emitFunctionExpression(node) {
101323             generateNameIfNeeded(node.name);
101324             emitFunctionDeclarationOrExpression(node);
101325         }
101326         function emitArrowFunction(node) {
101327             emitDecorators(node, node.decorators);
101328             emitModifiers(node, node.modifiers);
101329             emitSignatureAndBody(node, emitArrowFunctionHead);
101330         }
101331         function emitArrowFunctionHead(node) {
101332             emitTypeParameters(node, node.typeParameters);
101333             emitParametersForArrow(node, node.parameters);
101334             emitTypeAnnotation(node.type);
101335             writeSpace();
101336             emit(node.equalsGreaterThanToken);
101337         }
101338         function emitDeleteExpression(node) {
101339             emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node);
101340             writeSpace();
101341             emitExpression(node.expression);
101342         }
101343         function emitTypeOfExpression(node) {
101344             emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node);
101345             writeSpace();
101346             emitExpression(node.expression);
101347         }
101348         function emitVoidExpression(node) {
101349             emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node);
101350             writeSpace();
101351             emitExpression(node.expression);
101352         }
101353         function emitAwaitExpression(node) {
101354             emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node);
101355             writeSpace();
101356             emitExpression(node.expression);
101357         }
101358         function emitPrefixUnaryExpression(node) {
101359             writeTokenText(node.operator, writeOperator);
101360             if (shouldEmitWhitespaceBeforeOperand(node)) {
101361                 writeSpace();
101362             }
101363             emitExpression(node.operand);
101364         }
101365         function shouldEmitWhitespaceBeforeOperand(node) {
101366             // In some cases, we need to emit a space between the operator and the operand. One obvious case
101367             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
101368             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
101369             // are just for clarity of exposition, and not part of the source code):
101370             //
101371             //  (+(+1))
101372             //  (+(++1))
101373             //
101374             // We need to emit a space in both cases. In the first case, the absence of a space will make
101375             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
101376             // expression a prefix increment whose operand is a plus expression - (++(+x))
101377             // The same is true of minus of course.
101378             var operand = node.operand;
101379             return operand.kind === 214 /* PrefixUnaryExpression */
101380                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
101381                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
101382         }
101383         function emitPostfixUnaryExpression(node) {
101384             emitExpression(node.operand);
101385             writeTokenText(node.operator, writeOperator);
101386         }
101387         var EmitBinaryExpressionState;
101388         (function (EmitBinaryExpressionState) {
101389             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
101390             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
101391             EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
101392         })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
101393         /**
101394          * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
101395          * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
101396          * not require notification/substitution/comment/sourcemap decorations.
101397          */
101398         function emitBinaryExpression(node) {
101399             var nodeStack = [node];
101400             var stateStack = [0 /* EmitLeft */];
101401             var stackIndex = 0;
101402             while (stackIndex >= 0) {
101403                 node = nodeStack[stackIndex];
101404                 switch (stateStack[stackIndex]) {
101405                     case 0 /* EmitLeft */: {
101406                         maybePipelineEmitExpression(node.left);
101407                         break;
101408                     }
101409                     case 1 /* EmitRight */: {
101410                         var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
101411                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
101412                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
101413                         writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
101414                         emitLeadingCommentsOfPosition(node.operatorToken.pos);
101415                         writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator);
101416                         emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
101417                         writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
101418                         maybePipelineEmitExpression(node.right);
101419                         break;
101420                     }
101421                     case 2 /* FinishEmit */: {
101422                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
101423                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
101424                         decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
101425                         stackIndex--;
101426                         break;
101427                     }
101428                     default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
101429                 }
101430             }
101431             function maybePipelineEmitExpression(next) {
101432                 // Advance the state of this unit of work,
101433                 stateStack[stackIndex]++;
101434                 // Then actually do the work of emitting the node `next` returned by the prior state
101435                 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
101436                 // binary expression handling, where possible, to the contained work queue
101437                 // #region trampolinePipelineEmit
101438                 var savedLastNode = lastNode;
101439                 var savedLastSubstitution = lastSubstitution;
101440                 lastNode = next;
101441                 lastSubstitution = undefined;
101442                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
101443                 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
101444                     // If the target pipeline phase is emit directly, and the next node's also a binary expression,
101445                     // skip all the intermediate indirection and push the expression directly onto the work stack
101446                     stackIndex++;
101447                     stateStack[stackIndex] = 0 /* EmitLeft */;
101448                     nodeStack[stackIndex] = next;
101449                 }
101450                 else {
101451                     pipelinePhase(1 /* Expression */, next);
101452                 }
101453                 ts.Debug.assert(lastNode === next);
101454                 lastNode = savedLastNode;
101455                 lastSubstitution = savedLastSubstitution;
101456                 // #endregion trampolinePipelineEmit
101457             }
101458         }
101459         function emitConditionalExpression(node) {
101460             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
101461             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
101462             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
101463             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
101464             emitExpression(node.condition);
101465             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
101466             emit(node.questionToken);
101467             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
101468             emitExpression(node.whenTrue);
101469             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
101470             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
101471             emit(node.colonToken);
101472             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
101473             emitExpression(node.whenFalse);
101474             decreaseIndentIf(linesBeforeColon, linesAfterColon);
101475         }
101476         function emitTemplateExpression(node) {
101477             emit(node.head);
101478             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
101479         }
101480         function emitYieldExpression(node) {
101481             emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node);
101482             emit(node.asteriskToken);
101483             emitExpressionWithLeadingSpace(node.expression);
101484         }
101485         function emitSpreadExpression(node) {
101486             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
101487             emitExpression(node.expression);
101488         }
101489         function emitClassExpression(node) {
101490             generateNameIfNeeded(node.name);
101491             emitClassDeclarationOrExpression(node);
101492         }
101493         function emitExpressionWithTypeArguments(node) {
101494             emitExpression(node.expression);
101495             emitTypeArguments(node, node.typeArguments);
101496         }
101497         function emitAsExpression(node) {
101498             emitExpression(node.expression);
101499             if (node.type) {
101500                 writeSpace();
101501                 writeKeyword("as");
101502                 writeSpace();
101503                 emit(node.type);
101504             }
101505         }
101506         function emitNonNullExpression(node) {
101507             emitExpression(node.expression);
101508             writeOperator("!");
101509         }
101510         function emitMetaProperty(node) {
101511             writeToken(node.keywordToken, node.pos, writePunctuation);
101512             writePunctuation(".");
101513             emit(node.name);
101514         }
101515         //
101516         // Misc
101517         //
101518         function emitTemplateSpan(node) {
101519             emitExpression(node.expression);
101520             emit(node.literal);
101521         }
101522         //
101523         // Statements
101524         //
101525         function emitBlock(node) {
101526             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
101527         }
101528         function emitBlockStatements(node, forceSingleLine) {
101529             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
101530             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
101531             emitList(node, node.statements, format);
101532             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
101533         }
101534         function emitVariableStatement(node) {
101535             emitModifiers(node, node.modifiers);
101536             emit(node.declarationList);
101537             writeTrailingSemicolon();
101538         }
101539         function emitEmptyStatement(isEmbeddedStatement) {
101540             // While most trailing semicolons are possibly insignificant, an embedded "empty"
101541             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
101542             if (isEmbeddedStatement) {
101543                 writePunctuation(";");
101544             }
101545             else {
101546                 writeTrailingSemicolon();
101547             }
101548         }
101549         function emitExpressionStatement(node) {
101550             emitExpression(node.expression);
101551             // Emit semicolon in non json files
101552             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
101553             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
101554                 writeTrailingSemicolon();
101555             }
101556         }
101557         function emitIfStatement(node) {
101558             var openParenPos = emitTokenWithComment(98 /* IfKeyword */, node.pos, writeKeyword, node);
101559             writeSpace();
101560             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101561             emitExpression(node.expression);
101562             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101563             emitEmbeddedStatement(node, node.thenStatement);
101564             if (node.elseStatement) {
101565                 writeLineOrSpace(node, node.thenStatement, node.elseStatement);
101566                 emitTokenWithComment(90 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
101567                 if (node.elseStatement.kind === 234 /* IfStatement */) {
101568                     writeSpace();
101569                     emit(node.elseStatement);
101570                 }
101571                 else {
101572                     emitEmbeddedStatement(node, node.elseStatement);
101573                 }
101574             }
101575         }
101576         function emitWhileClause(node, startPos) {
101577             var openParenPos = emitTokenWithComment(114 /* WhileKeyword */, startPos, writeKeyword, node);
101578             writeSpace();
101579             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101580             emitExpression(node.expression);
101581             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101582         }
101583         function emitDoStatement(node) {
101584             emitTokenWithComment(89 /* DoKeyword */, node.pos, writeKeyword, node);
101585             emitEmbeddedStatement(node, node.statement);
101586             if (ts.isBlock(node.statement) && !preserveSourceNewlines) {
101587                 writeSpace();
101588             }
101589             else {
101590                 writeLineOrSpace(node, node.statement, node.expression);
101591             }
101592             emitWhileClause(node, node.statement.end);
101593             writeTrailingSemicolon();
101594         }
101595         function emitWhileStatement(node) {
101596             emitWhileClause(node, node.pos);
101597             emitEmbeddedStatement(node, node.statement);
101598         }
101599         function emitForStatement(node) {
101600             var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
101601             writeSpace();
101602             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
101603             emitForBinding(node.initializer);
101604             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
101605             emitExpressionWithLeadingSpace(node.condition);
101606             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
101607             emitExpressionWithLeadingSpace(node.incrementor);
101608             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
101609             emitEmbeddedStatement(node, node.statement);
101610         }
101611         function emitForInStatement(node) {
101612             var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
101613             writeSpace();
101614             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101615             emitForBinding(node.initializer);
101616             writeSpace();
101617             emitTokenWithComment(100 /* InKeyword */, node.initializer.end, writeKeyword, node);
101618             writeSpace();
101619             emitExpression(node.expression);
101620             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101621             emitEmbeddedStatement(node, node.statement);
101622         }
101623         function emitForOfStatement(node) {
101624             var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
101625             writeSpace();
101626             emitWithTrailingSpace(node.awaitModifier);
101627             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101628             emitForBinding(node.initializer);
101629             writeSpace();
101630             emitTokenWithComment(156 /* OfKeyword */, node.initializer.end, writeKeyword, node);
101631             writeSpace();
101632             emitExpression(node.expression);
101633             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101634             emitEmbeddedStatement(node, node.statement);
101635         }
101636         function emitForBinding(node) {
101637             if (node !== undefined) {
101638                 if (node.kind === 250 /* VariableDeclarationList */) {
101639                     emit(node);
101640                 }
101641                 else {
101642                     emitExpression(node);
101643                 }
101644             }
101645         }
101646         function emitContinueStatement(node) {
101647             emitTokenWithComment(85 /* ContinueKeyword */, node.pos, writeKeyword, node);
101648             emitWithLeadingSpace(node.label);
101649             writeTrailingSemicolon();
101650         }
101651         function emitBreakStatement(node) {
101652             emitTokenWithComment(80 /* BreakKeyword */, node.pos, writeKeyword, node);
101653             emitWithLeadingSpace(node.label);
101654             writeTrailingSemicolon();
101655         }
101656         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
101657             var node = ts.getParseTreeNode(contextNode);
101658             var isSimilarNode = node && node.kind === contextNode.kind;
101659             var startPos = pos;
101660             if (isSimilarNode && currentSourceFile) {
101661                 pos = ts.skipTrivia(currentSourceFile.text, pos);
101662             }
101663             if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
101664                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
101665                 if (needsIndent) {
101666                     increaseIndent();
101667                 }
101668                 emitLeadingCommentsOfPosition(startPos);
101669                 if (needsIndent) {
101670                     decreaseIndent();
101671                 }
101672             }
101673             pos = writeTokenText(token, writer, pos);
101674             if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
101675                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
101676             }
101677             return pos;
101678         }
101679         function emitReturnStatement(node) {
101680             emitTokenWithComment(104 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
101681             emitExpressionWithLeadingSpace(node.expression);
101682             writeTrailingSemicolon();
101683         }
101684         function emitWithStatement(node) {
101685             var openParenPos = emitTokenWithComment(115 /* WithKeyword */, node.pos, writeKeyword, node);
101686             writeSpace();
101687             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101688             emitExpression(node.expression);
101689             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101690             emitEmbeddedStatement(node, node.statement);
101691         }
101692         function emitSwitchStatement(node) {
101693             var openParenPos = emitTokenWithComment(106 /* SwitchKeyword */, node.pos, writeKeyword, node);
101694             writeSpace();
101695             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101696             emitExpression(node.expression);
101697             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101698             writeSpace();
101699             emit(node.caseBlock);
101700         }
101701         function emitLabeledStatement(node) {
101702             emit(node.label);
101703             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
101704             writeSpace();
101705             emit(node.statement);
101706         }
101707         function emitThrowStatement(node) {
101708             emitTokenWithComment(108 /* ThrowKeyword */, node.pos, writeKeyword, node);
101709             emitExpressionWithLeadingSpace(node.expression);
101710             writeTrailingSemicolon();
101711         }
101712         function emitTryStatement(node) {
101713             emitTokenWithComment(110 /* TryKeyword */, node.pos, writeKeyword, node);
101714             writeSpace();
101715             emit(node.tryBlock);
101716             if (node.catchClause) {
101717                 writeLineOrSpace(node, node.tryBlock, node.catchClause);
101718                 emit(node.catchClause);
101719             }
101720             if (node.finallyBlock) {
101721                 writeLineOrSpace(node, node.catchClause || node.tryBlock, node.finallyBlock);
101722                 emitTokenWithComment(95 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
101723                 writeSpace();
101724                 emit(node.finallyBlock);
101725             }
101726         }
101727         function emitDebuggerStatement(node) {
101728             writeToken(86 /* DebuggerKeyword */, node.pos, writeKeyword);
101729             writeTrailingSemicolon();
101730         }
101731         //
101732         // Declarations
101733         //
101734         function emitVariableDeclaration(node) {
101735             emit(node.name);
101736             emit(node.exclamationToken);
101737             emitTypeAnnotation(node.type);
101738             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
101739         }
101740         function emitVariableDeclarationList(node) {
101741             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
101742             writeSpace();
101743             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
101744         }
101745         function emitFunctionDeclaration(node) {
101746             emitFunctionDeclarationOrExpression(node);
101747         }
101748         function emitFunctionDeclarationOrExpression(node) {
101749             emitDecorators(node, node.decorators);
101750             emitModifiers(node, node.modifiers);
101751             writeKeyword("function");
101752             emit(node.asteriskToken);
101753             writeSpace();
101754             emitIdentifierName(node.name);
101755             emitSignatureAndBody(node, emitSignatureHead);
101756         }
101757         function emitBlockCallback(_hint, body) {
101758             emitBlockFunctionBody(body);
101759         }
101760         function emitSignatureAndBody(node, emitSignatureHead) {
101761             var body = node.body;
101762             if (body) {
101763                 if (ts.isBlock(body)) {
101764                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
101765                     if (indentedFlag) {
101766                         increaseIndent();
101767                     }
101768                     pushNameGenerationScope(node);
101769                     ts.forEach(node.parameters, generateNames);
101770                     generateNames(node.body);
101771                     emitSignatureHead(node);
101772                     if (onEmitNode) {
101773                         onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
101774                     }
101775                     else {
101776                         emitBlockFunctionBody(body);
101777                     }
101778                     popNameGenerationScope(node);
101779                     if (indentedFlag) {
101780                         decreaseIndent();
101781                     }
101782                 }
101783                 else {
101784                     emitSignatureHead(node);
101785                     writeSpace();
101786                     emitExpression(body);
101787                 }
101788             }
101789             else {
101790                 emitSignatureHead(node);
101791                 writeTrailingSemicolon();
101792             }
101793         }
101794         function emitSignatureHead(node) {
101795             emitTypeParameters(node, node.typeParameters);
101796             emitParameters(node, node.parameters);
101797             emitTypeAnnotation(node.type);
101798         }
101799         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
101800             // We must emit a function body as a single-line body in the following case:
101801             // * The body has NodeEmitFlags.SingleLine specified.
101802             // We must emit a function body as a multi-line body in the following cases:
101803             // * The body is explicitly marked as multi-line.
101804             // * A non-synthesized body's start and end position are on different lines.
101805             // * Any statement in the body starts on a new line.
101806             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
101807                 return true;
101808             }
101809             if (body.multiLine) {
101810                 return false;
101811             }
101812             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
101813                 return false;
101814             }
101815             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
101816                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
101817                 return false;
101818             }
101819             var previousStatement;
101820             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
101821                 var statement = _b[_a];
101822                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
101823                     return false;
101824                 }
101825                 previousStatement = statement;
101826             }
101827             return true;
101828         }
101829         function emitBlockFunctionBody(body) {
101830             writeSpace();
101831             writePunctuation("{");
101832             increaseIndent();
101833             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
101834                 ? emitBlockFunctionBodyOnSingleLine
101835                 : emitBlockFunctionBodyWorker;
101836             if (emitBodyWithDetachedComments) {
101837                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
101838             }
101839             else {
101840                 emitBlockFunctionBody(body);
101841             }
101842             decreaseIndent();
101843             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
101844         }
101845         function emitBlockFunctionBodyOnSingleLine(body) {
101846             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
101847         }
101848         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
101849             // Emit all the prologue directives (like "use strict").
101850             var statementOffset = emitPrologueDirectives(body.statements);
101851             var pos = writer.getTextPos();
101852             emitHelpers(body);
101853             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
101854                 decreaseIndent();
101855                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
101856                 increaseIndent();
101857             }
101858             else {
101859                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
101860             }
101861         }
101862         function emitClassDeclaration(node) {
101863             emitClassDeclarationOrExpression(node);
101864         }
101865         function emitClassDeclarationOrExpression(node) {
101866             ts.forEach(node.members, generateMemberNames);
101867             emitDecorators(node, node.decorators);
101868             emitModifiers(node, node.modifiers);
101869             writeKeyword("class");
101870             if (node.name) {
101871                 writeSpace();
101872                 emitIdentifierName(node.name);
101873             }
101874             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
101875             if (indentedFlag) {
101876                 increaseIndent();
101877             }
101878             emitTypeParameters(node, node.typeParameters);
101879             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
101880             writeSpace();
101881             writePunctuation("{");
101882             emitList(node, node.members, 129 /* ClassMembers */);
101883             writePunctuation("}");
101884             if (indentedFlag) {
101885                 decreaseIndent();
101886             }
101887         }
101888         function emitInterfaceDeclaration(node) {
101889             emitDecorators(node, node.decorators);
101890             emitModifiers(node, node.modifiers);
101891             writeKeyword("interface");
101892             writeSpace();
101893             emit(node.name);
101894             emitTypeParameters(node, node.typeParameters);
101895             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
101896             writeSpace();
101897             writePunctuation("{");
101898             emitList(node, node.members, 129 /* InterfaceMembers */);
101899             writePunctuation("}");
101900         }
101901         function emitTypeAliasDeclaration(node) {
101902             emitDecorators(node, node.decorators);
101903             emitModifiers(node, node.modifiers);
101904             writeKeyword("type");
101905             writeSpace();
101906             emit(node.name);
101907             emitTypeParameters(node, node.typeParameters);
101908             writeSpace();
101909             writePunctuation("=");
101910             writeSpace();
101911             emit(node.type);
101912             writeTrailingSemicolon();
101913         }
101914         function emitEnumDeclaration(node) {
101915             emitModifiers(node, node.modifiers);
101916             writeKeyword("enum");
101917             writeSpace();
101918             emit(node.name);
101919             writeSpace();
101920             writePunctuation("{");
101921             emitList(node, node.members, 145 /* EnumMembers */);
101922             writePunctuation("}");
101923         }
101924         function emitModuleDeclaration(node) {
101925             emitModifiers(node, node.modifiers);
101926             if (~node.flags & 1024 /* GlobalAugmentation */) {
101927                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
101928                 writeSpace();
101929             }
101930             emit(node.name);
101931             var body = node.body;
101932             if (!body)
101933                 return writeTrailingSemicolon();
101934             while (body.kind === 256 /* ModuleDeclaration */) {
101935                 writePunctuation(".");
101936                 emit(body.name);
101937                 body = body.body;
101938             }
101939             writeSpace();
101940             emit(body);
101941         }
101942         function emitModuleBlock(node) {
101943             pushNameGenerationScope(node);
101944             ts.forEach(node.statements, generateNames);
101945             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
101946             popNameGenerationScope(node);
101947         }
101948         function emitCaseBlock(node) {
101949             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
101950             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
101951             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
101952         }
101953         function emitImportEqualsDeclaration(node) {
101954             emitModifiers(node, node.modifiers);
101955             emitTokenWithComment(99 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
101956             writeSpace();
101957             emit(node.name);
101958             writeSpace();
101959             emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
101960             writeSpace();
101961             emitModuleReference(node.moduleReference);
101962             writeTrailingSemicolon();
101963         }
101964         function emitModuleReference(node) {
101965             if (node.kind === 78 /* Identifier */) {
101966                 emitExpression(node);
101967             }
101968             else {
101969                 emit(node);
101970             }
101971         }
101972         function emitImportDeclaration(node) {
101973             emitModifiers(node, node.modifiers);
101974             emitTokenWithComment(99 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
101975             writeSpace();
101976             if (node.importClause) {
101977                 emit(node.importClause);
101978                 writeSpace();
101979                 emitTokenWithComment(153 /* FromKeyword */, node.importClause.end, writeKeyword, node);
101980                 writeSpace();
101981             }
101982             emitExpression(node.moduleSpecifier);
101983             writeTrailingSemicolon();
101984         }
101985         function emitImportClause(node) {
101986             if (node.isTypeOnly) {
101987                 emitTokenWithComment(149 /* TypeKeyword */, node.pos, writeKeyword, node);
101988                 writeSpace();
101989             }
101990             emit(node.name);
101991             if (node.name && node.namedBindings) {
101992                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
101993                 writeSpace();
101994             }
101995             emit(node.namedBindings);
101996         }
101997         function emitNamespaceImport(node) {
101998             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
101999             writeSpace();
102000             emitTokenWithComment(126 /* AsKeyword */, asPos, writeKeyword, node);
102001             writeSpace();
102002             emit(node.name);
102003         }
102004         function emitNamedImports(node) {
102005             emitNamedImportsOrExports(node);
102006         }
102007         function emitImportSpecifier(node) {
102008             emitImportOrExportSpecifier(node);
102009         }
102010         function emitExportAssignment(node) {
102011             var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
102012             writeSpace();
102013             if (node.isExportEquals) {
102014                 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
102015             }
102016             else {
102017                 emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node);
102018             }
102019             writeSpace();
102020             emitExpression(node.expression);
102021             writeTrailingSemicolon();
102022         }
102023         function emitExportDeclaration(node) {
102024             var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
102025             writeSpace();
102026             if (node.isTypeOnly) {
102027                 nextPos = emitTokenWithComment(149 /* TypeKeyword */, nextPos, writeKeyword, node);
102028                 writeSpace();
102029             }
102030             if (node.exportClause) {
102031                 emit(node.exportClause);
102032             }
102033             else {
102034                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
102035             }
102036             if (node.moduleSpecifier) {
102037                 writeSpace();
102038                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
102039                 emitTokenWithComment(153 /* FromKeyword */, fromPos, writeKeyword, node);
102040                 writeSpace();
102041                 emitExpression(node.moduleSpecifier);
102042             }
102043             writeTrailingSemicolon();
102044         }
102045         function emitNamespaceExportDeclaration(node) {
102046             var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
102047             writeSpace();
102048             nextPos = emitTokenWithComment(126 /* AsKeyword */, nextPos, writeKeyword, node);
102049             writeSpace();
102050             nextPos = emitTokenWithComment(140 /* NamespaceKeyword */, nextPos, writeKeyword, node);
102051             writeSpace();
102052             emit(node.name);
102053             writeTrailingSemicolon();
102054         }
102055         function emitNamespaceExport(node) {
102056             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
102057             writeSpace();
102058             emitTokenWithComment(126 /* AsKeyword */, asPos, writeKeyword, node);
102059             writeSpace();
102060             emit(node.name);
102061         }
102062         function emitNamedExports(node) {
102063             emitNamedImportsOrExports(node);
102064         }
102065         function emitExportSpecifier(node) {
102066             emitImportOrExportSpecifier(node);
102067         }
102068         function emitNamedImportsOrExports(node) {
102069             writePunctuation("{");
102070             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
102071             writePunctuation("}");
102072         }
102073         function emitImportOrExportSpecifier(node) {
102074             if (node.propertyName) {
102075                 emit(node.propertyName);
102076                 writeSpace();
102077                 emitTokenWithComment(126 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
102078                 writeSpace();
102079             }
102080             emit(node.name);
102081         }
102082         //
102083         // Module references
102084         //
102085         function emitExternalModuleReference(node) {
102086             writeKeyword("require");
102087             writePunctuation("(");
102088             emitExpression(node.expression);
102089             writePunctuation(")");
102090         }
102091         //
102092         // JSX
102093         //
102094         function emitJsxElement(node) {
102095             emit(node.openingElement);
102096             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
102097             emit(node.closingElement);
102098         }
102099         function emitJsxSelfClosingElement(node) {
102100             writePunctuation("<");
102101             emitJsxTagName(node.tagName);
102102             emitTypeArguments(node, node.typeArguments);
102103             writeSpace();
102104             emit(node.attributes);
102105             writePunctuation("/>");
102106         }
102107         function emitJsxFragment(node) {
102108             emit(node.openingFragment);
102109             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
102110             emit(node.closingFragment);
102111         }
102112         function emitJsxOpeningElementOrFragment(node) {
102113             writePunctuation("<");
102114             if (ts.isJsxOpeningElement(node)) {
102115                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
102116                 emitJsxTagName(node.tagName);
102117                 emitTypeArguments(node, node.typeArguments);
102118                 if (node.attributes.properties && node.attributes.properties.length > 0) {
102119                     writeSpace();
102120                 }
102121                 emit(node.attributes);
102122                 writeLineSeparatorsAfter(node.attributes, node);
102123                 decreaseIndentIf(indented);
102124             }
102125             writePunctuation(">");
102126         }
102127         function emitJsxText(node) {
102128             writer.writeLiteral(node.text);
102129         }
102130         function emitJsxClosingElementOrFragment(node) {
102131             writePunctuation("</");
102132             if (ts.isJsxClosingElement(node)) {
102133                 emitJsxTagName(node.tagName);
102134             }
102135             writePunctuation(">");
102136         }
102137         function emitJsxAttributes(node) {
102138             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
102139         }
102140         function emitJsxAttribute(node) {
102141             emit(node.name);
102142             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
102143         }
102144         function emitJsxSpreadAttribute(node) {
102145             writePunctuation("{...");
102146             emitExpression(node.expression);
102147             writePunctuation("}");
102148         }
102149         function emitJsxExpression(node) {
102150             if (node.expression) {
102151                 writePunctuation("{");
102152                 emit(node.dotDotDotToken);
102153                 emitExpression(node.expression);
102154                 writePunctuation("}");
102155             }
102156         }
102157         function emitJsxTagName(node) {
102158             if (node.kind === 78 /* Identifier */) {
102159                 emitExpression(node);
102160             }
102161             else {
102162                 emit(node);
102163             }
102164         }
102165         //
102166         // Clauses
102167         //
102168         function emitCaseClause(node) {
102169             emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node);
102170             writeSpace();
102171             emitExpression(node.expression);
102172             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
102173         }
102174         function emitDefaultClause(node) {
102175             var pos = emitTokenWithComment(87 /* DefaultKeyword */, node.pos, writeKeyword, node);
102176             emitCaseOrDefaultClauseRest(node, node.statements, pos);
102177         }
102178         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
102179             var emitAsSingleStatement = statements.length === 1 &&
102180                 (
102181                 // treat synthesized nodes as located on the same line for emit purposes
102182                 ts.nodeIsSynthesized(parentNode) ||
102183                     ts.nodeIsSynthesized(statements[0]) ||
102184                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
102185             var format = 163969 /* CaseOrDefaultClauseStatements */;
102186             if (emitAsSingleStatement) {
102187                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
102188                 writeSpace();
102189                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
102190             }
102191             else {
102192                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
102193             }
102194             emitList(parentNode, statements, format);
102195         }
102196         function emitHeritageClause(node) {
102197             writeSpace();
102198             writeTokenText(node.token, writeKeyword);
102199             writeSpace();
102200             emitList(node, node.types, 528 /* HeritageClauseTypes */);
102201         }
102202         function emitCatchClause(node) {
102203             var openParenPos = emitTokenWithComment(82 /* CatchKeyword */, node.pos, writeKeyword, node);
102204             writeSpace();
102205             if (node.variableDeclaration) {
102206                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
102207                 emit(node.variableDeclaration);
102208                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
102209                 writeSpace();
102210             }
102211             emit(node.block);
102212         }
102213         //
102214         // Property assignments
102215         //
102216         function emitPropertyAssignment(node) {
102217             emit(node.name);
102218             writePunctuation(":");
102219             writeSpace();
102220             // This is to ensure that we emit comment in the following case:
102221             //      For example:
102222             //          obj = {
102223             //              id: /*comment1*/ ()=>void
102224             //          }
102225             // "comment1" is not considered to be leading comment for node.initializer
102226             // but rather a trailing comment on the previous node.
102227             var initializer = node.initializer;
102228             if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
102229                 var commentRange = ts.getCommentRange(initializer);
102230                 emitTrailingCommentsOfPosition(commentRange.pos);
102231             }
102232             emitExpression(initializer);
102233         }
102234         function emitShorthandPropertyAssignment(node) {
102235             emit(node.name);
102236             if (node.objectAssignmentInitializer) {
102237                 writeSpace();
102238                 writePunctuation("=");
102239                 writeSpace();
102240                 emitExpression(node.objectAssignmentInitializer);
102241             }
102242         }
102243         function emitSpreadAssignment(node) {
102244             if (node.expression) {
102245                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
102246                 emitExpression(node.expression);
102247             }
102248         }
102249         //
102250         // Enum
102251         //
102252         function emitEnumMember(node) {
102253             emit(node.name);
102254             emitInitializer(node.initializer, node.name.end, node);
102255         }
102256         //
102257         // JSDoc
102258         //
102259         function emitJSDoc(node) {
102260             write("/**");
102261             if (node.comment) {
102262                 var lines = node.comment.split(/\r\n?|\n/g);
102263                 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
102264                     var line = lines_2[_a];
102265                     writeLine();
102266                     writeSpace();
102267                     writePunctuation("*");
102268                     writeSpace();
102269                     write(line);
102270                 }
102271             }
102272             if (node.tags) {
102273                 if (node.tags.length === 1 && node.tags[0].kind === 329 /* JSDocTypeTag */ && !node.comment) {
102274                     writeSpace();
102275                     emit(node.tags[0]);
102276                 }
102277                 else {
102278                     emitList(node, node.tags, 33 /* JSDocComment */);
102279                 }
102280             }
102281             writeSpace();
102282             write("*/");
102283         }
102284         function emitJSDocSimpleTypedTag(tag) {
102285             emitJSDocTagName(tag.tagName);
102286             emitJSDocTypeExpression(tag.typeExpression);
102287             emitJSDocComment(tag.comment);
102288         }
102289         function emitJSDocSeeTag(tag) {
102290             emitJSDocTagName(tag.tagName);
102291             emit(tag.name);
102292             emitJSDocComment(tag.comment);
102293         }
102294         function emitJSDocNameReference(node) {
102295             writeSpace();
102296             writePunctuation("{");
102297             emit(node.name);
102298             writePunctuation("}");
102299         }
102300         function emitJSDocHeritageTag(tag) {
102301             emitJSDocTagName(tag.tagName);
102302             writeSpace();
102303             writePunctuation("{");
102304             emit(tag.class);
102305             writePunctuation("}");
102306             emitJSDocComment(tag.comment);
102307         }
102308         function emitJSDocTemplateTag(tag) {
102309             emitJSDocTagName(tag.tagName);
102310             emitJSDocTypeExpression(tag.constraint);
102311             writeSpace();
102312             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
102313             emitJSDocComment(tag.comment);
102314         }
102315         function emitJSDocTypedefTag(tag) {
102316             emitJSDocTagName(tag.tagName);
102317             if (tag.typeExpression) {
102318                 if (tag.typeExpression.kind === 301 /* JSDocTypeExpression */) {
102319                     emitJSDocTypeExpression(tag.typeExpression);
102320                 }
102321                 else {
102322                     writeSpace();
102323                     writePunctuation("{");
102324                     write("Object");
102325                     if (tag.typeExpression.isArrayType) {
102326                         writePunctuation("[");
102327                         writePunctuation("]");
102328                     }
102329                     writePunctuation("}");
102330                 }
102331             }
102332             if (tag.fullName) {
102333                 writeSpace();
102334                 emit(tag.fullName);
102335             }
102336             emitJSDocComment(tag.comment);
102337             if (tag.typeExpression && tag.typeExpression.kind === 312 /* JSDocTypeLiteral */) {
102338                 emitJSDocTypeLiteral(tag.typeExpression);
102339             }
102340         }
102341         function emitJSDocCallbackTag(tag) {
102342             emitJSDocTagName(tag.tagName);
102343             if (tag.name) {
102344                 writeSpace();
102345                 emit(tag.name);
102346             }
102347             emitJSDocComment(tag.comment);
102348             emitJSDocSignature(tag.typeExpression);
102349         }
102350         function emitJSDocSimpleTag(tag) {
102351             emitJSDocTagName(tag.tagName);
102352             emitJSDocComment(tag.comment);
102353         }
102354         function emitJSDocTypeLiteral(lit) {
102355             emitList(lit, ts.factory.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
102356         }
102357         function emitJSDocSignature(sig) {
102358             if (sig.typeParameters) {
102359                 emitList(sig, ts.factory.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
102360             }
102361             if (sig.parameters) {
102362                 emitList(sig, ts.factory.createNodeArray(sig.parameters), 33 /* JSDocComment */);
102363             }
102364             if (sig.type) {
102365                 writeLine();
102366                 writeSpace();
102367                 writePunctuation("*");
102368                 writeSpace();
102369                 emit(sig.type);
102370             }
102371         }
102372         function emitJSDocPropertyLikeTag(param) {
102373             emitJSDocTagName(param.tagName);
102374             emitJSDocTypeExpression(param.typeExpression);
102375             writeSpace();
102376             if (param.isBracketed) {
102377                 writePunctuation("[");
102378             }
102379             emit(param.name);
102380             if (param.isBracketed) {
102381                 writePunctuation("]");
102382             }
102383             emitJSDocComment(param.comment);
102384         }
102385         function emitJSDocTagName(tagName) {
102386             writePunctuation("@");
102387             emit(tagName);
102388         }
102389         function emitJSDocComment(comment) {
102390             if (comment) {
102391                 writeSpace();
102392                 write(comment);
102393             }
102394         }
102395         function emitJSDocTypeExpression(typeExpression) {
102396             if (typeExpression) {
102397                 writeSpace();
102398                 writePunctuation("{");
102399                 emit(typeExpression.type);
102400                 writePunctuation("}");
102401             }
102402         }
102403         //
102404         // Top-level nodes
102405         //
102406         function emitSourceFile(node) {
102407             writeLine();
102408             var statements = node.statements;
102409             if (emitBodyWithDetachedComments) {
102410                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
102411                 // The synthesized node will have no leading comment so some comments may be missed.
102412                 var shouldEmitDetachedComment = statements.length === 0 ||
102413                     !ts.isPrologueDirective(statements[0]) ||
102414                     ts.nodeIsSynthesized(statements[0]);
102415                 if (shouldEmitDetachedComment) {
102416                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
102417                     return;
102418                 }
102419             }
102420             emitSourceFileWorker(node);
102421         }
102422         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
102423             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
102424             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
102425                 var prepend = _b[_a];
102426                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
102427                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
102428                         var ref = _d[_c];
102429                         emit(ref);
102430                         writeLine();
102431                     }
102432                 }
102433             }
102434         }
102435         function emitTripleSlashDirectivesIfNeeded(node) {
102436             if (node.isDeclarationFile)
102437                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
102438         }
102439         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
102440             if (hasNoDefaultLib) {
102441                 var pos = writer.getTextPos();
102442                 writeComment("/// <reference no-default-lib=\"true\"/>");
102443                 if (bundleFileInfo)
102444                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
102445                 writeLine();
102446             }
102447             if (currentSourceFile && currentSourceFile.moduleName) {
102448                 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
102449                 writeLine();
102450             }
102451             if (currentSourceFile && currentSourceFile.amdDependencies) {
102452                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
102453                     var dep = _b[_a];
102454                     if (dep.name) {
102455                         writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
102456                     }
102457                     else {
102458                         writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
102459                     }
102460                     writeLine();
102461                 }
102462             }
102463             for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
102464                 var directive = files_1[_c];
102465                 var pos = writer.getTextPos();
102466                 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
102467                 if (bundleFileInfo)
102468                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
102469                 writeLine();
102470             }
102471             for (var _d = 0, types_23 = types; _d < types_23.length; _d++) {
102472                 var directive = types_23[_d];
102473                 var pos = writer.getTextPos();
102474                 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
102475                 if (bundleFileInfo)
102476                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
102477                 writeLine();
102478             }
102479             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
102480                 var directive = libs_1[_e];
102481                 var pos = writer.getTextPos();
102482                 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
102483                 if (bundleFileInfo)
102484                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
102485                 writeLine();
102486             }
102487         }
102488         function emitSourceFileWorker(node) {
102489             var statements = node.statements;
102490             pushNameGenerationScope(node);
102491             ts.forEach(node.statements, generateNames);
102492             emitHelpers(node);
102493             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
102494             emitTripleSlashDirectivesIfNeeded(node);
102495             emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
102496             popNameGenerationScope(node);
102497         }
102498         // Transformation nodes
102499         function emitPartiallyEmittedExpression(node) {
102500             emitExpression(node.expression);
102501         }
102502         function emitCommaList(node) {
102503             emitExpressionList(node, node.elements, 528 /* CommaListElements */);
102504         }
102505         /**
102506          * Emits any prologue directives at the start of a Statement list, returning the
102507          * number of prologue directives written to the output.
102508          */
102509         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
102510             var needsToSetSourceFile = !!sourceFile;
102511             for (var i = 0; i < statements.length; i++) {
102512                 var statement = statements[i];
102513                 if (ts.isPrologueDirective(statement)) {
102514                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
102515                     if (shouldEmitPrologueDirective) {
102516                         if (needsToSetSourceFile) {
102517                             needsToSetSourceFile = false;
102518                             setSourceFile(sourceFile);
102519                         }
102520                         writeLine();
102521                         var pos = writer.getTextPos();
102522                         emit(statement);
102523                         if (recordBundleFileSection && bundleFileInfo)
102524                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
102525                         if (seenPrologueDirectives) {
102526                             seenPrologueDirectives.add(statement.expression.text);
102527                         }
102528                     }
102529                 }
102530                 else {
102531                     // return index of the first non prologue directive
102532                     return i;
102533                 }
102534             }
102535             return statements.length;
102536         }
102537         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
102538             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
102539                 var prologue = prologues_1[_a];
102540                 if (!seenPrologueDirectives.has(prologue.data)) {
102541                     writeLine();
102542                     var pos = writer.getTextPos();
102543                     emit(prologue);
102544                     if (bundleFileInfo)
102545                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
102546                     if (seenPrologueDirectives) {
102547                         seenPrologueDirectives.add(prologue.data);
102548                     }
102549                 }
102550             }
102551         }
102552         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
102553             if (ts.isSourceFile(sourceFileOrBundle)) {
102554                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
102555             }
102556             else {
102557                 var seenPrologueDirectives = new ts.Set();
102558                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
102559                     var prepend = _b[_a];
102560                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
102561                 }
102562                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
102563                     var sourceFile = _d[_c];
102564                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
102565                 }
102566                 setSourceFile(undefined);
102567             }
102568         }
102569         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
102570             var seenPrologueDirectives = new ts.Set();
102571             var prologues;
102572             for (var index = 0; index < bundle.sourceFiles.length; index++) {
102573                 var sourceFile = bundle.sourceFiles[index];
102574                 var directives = void 0;
102575                 var end = 0;
102576                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
102577                     var statement = _b[_a];
102578                     if (!ts.isPrologueDirective(statement))
102579                         break;
102580                     if (seenPrologueDirectives.has(statement.expression.text))
102581                         continue;
102582                     seenPrologueDirectives.add(statement.expression.text);
102583                     (directives || (directives = [])).push({
102584                         pos: statement.pos,
102585                         end: statement.end,
102586                         expression: {
102587                             pos: statement.expression.pos,
102588                             end: statement.expression.end,
102589                             text: statement.expression.text
102590                         }
102591                     });
102592                     end = end < statement.end ? statement.end : end;
102593                 }
102594                 if (directives)
102595                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
102596             }
102597             return prologues;
102598         }
102599         function emitShebangIfNeeded(sourceFileOrBundle) {
102600             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
102601                 var shebang = ts.getShebang(sourceFileOrBundle.text);
102602                 if (shebang) {
102603                     writeComment(shebang);
102604                     writeLine();
102605                     return true;
102606                 }
102607             }
102608             else {
102609                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
102610                     var prepend = _b[_a];
102611                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
102612                     if (emitShebangIfNeeded(prepend)) {
102613                         return true;
102614                     }
102615                 }
102616                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
102617                     var sourceFile = _d[_c];
102618                     // Emit only the first encountered shebang
102619                     if (emitShebangIfNeeded(sourceFile)) {
102620                         return true;
102621                     }
102622                 }
102623             }
102624         }
102625         //
102626         // Helpers
102627         //
102628         function emitNodeWithWriter(node, writer) {
102629             if (!node)
102630                 return;
102631             var savedWrite = write;
102632             write = writer;
102633             emit(node);
102634             write = savedWrite;
102635         }
102636         function emitModifiers(node, modifiers) {
102637             if (modifiers && modifiers.length) {
102638                 emitList(node, modifiers, 262656 /* Modifiers */);
102639                 writeSpace();
102640             }
102641         }
102642         function emitTypeAnnotation(node) {
102643             if (node) {
102644                 writePunctuation(":");
102645                 writeSpace();
102646                 emit(node);
102647             }
102648         }
102649         function emitInitializer(node, equalCommentStartPos, container) {
102650             if (node) {
102651                 writeSpace();
102652                 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
102653                 writeSpace();
102654                 emitExpression(node);
102655             }
102656         }
102657         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
102658             if (node) {
102659                 prefixWriter(prefix);
102660                 emit(node);
102661             }
102662         }
102663         function emitWithLeadingSpace(node) {
102664             if (node) {
102665                 writeSpace();
102666                 emit(node);
102667             }
102668         }
102669         function emitExpressionWithLeadingSpace(node) {
102670             if (node) {
102671                 writeSpace();
102672                 emitExpression(node);
102673             }
102674         }
102675         function emitWithTrailingSpace(node) {
102676             if (node) {
102677                 emit(node);
102678                 writeSpace();
102679             }
102680         }
102681         function emitEmbeddedStatement(parent, node) {
102682             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
102683                 writeSpace();
102684                 emit(node);
102685             }
102686             else {
102687                 writeLine();
102688                 increaseIndent();
102689                 if (ts.isEmptyStatement(node)) {
102690                     pipelineEmit(5 /* EmbeddedStatement */, node);
102691                 }
102692                 else {
102693                     emit(node);
102694                 }
102695                 decreaseIndent();
102696             }
102697         }
102698         function emitDecorators(parentNode, decorators) {
102699             emitList(parentNode, decorators, 2146305 /* Decorators */);
102700         }
102701         function emitTypeArguments(parentNode, typeArguments) {
102702             emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
102703         }
102704         function emitTypeParameters(parentNode, typeParameters) {
102705             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
102706                 return emitTypeArguments(parentNode, parentNode.typeArguments);
102707             }
102708             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
102709         }
102710         function emitParameters(parentNode, parameters) {
102711             emitList(parentNode, parameters, 2576 /* Parameters */);
102712         }
102713         function canEmitSimpleArrowHead(parentNode, parameters) {
102714             var parameter = ts.singleOrUndefined(parameters);
102715             return parameter
102716                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
102717                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
102718                 && !parentNode.type // arrow function may not have return type annotation
102719                 && !ts.some(parentNode.decorators) // parent may not have decorators
102720                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
102721                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
102722                 && !ts.some(parameter.decorators) // parameter may not have decorators
102723                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
102724                 && !parameter.dotDotDotToken // parameter may not be rest
102725                 && !parameter.questionToken // parameter may not be optional
102726                 && !parameter.type // parameter may not have a type annotation
102727                 && !parameter.initializer // parameter may not have an initializer
102728                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
102729         }
102730         function emitParametersForArrow(parentNode, parameters) {
102731             if (canEmitSimpleArrowHead(parentNode, parameters)) {
102732                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
102733             }
102734             else {
102735                 emitParameters(parentNode, parameters);
102736             }
102737         }
102738         function emitParametersForIndexSignature(parentNode, parameters) {
102739             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
102740         }
102741         function emitList(parentNode, children, format, start, count) {
102742             emitNodeList(emit, parentNode, children, format, start, count);
102743         }
102744         function emitExpressionList(parentNode, children, format, start, count) {
102745             emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
102746         }
102747         function writeDelimiter(format) {
102748             switch (format & 60 /* DelimitersMask */) {
102749                 case 0 /* None */:
102750                     break;
102751                 case 16 /* CommaDelimited */:
102752                     writePunctuation(",");
102753                     break;
102754                 case 4 /* BarDelimited */:
102755                     writeSpace();
102756                     writePunctuation("|");
102757                     break;
102758                 case 32 /* AsteriskDelimited */:
102759                     writeSpace();
102760                     writePunctuation("*");
102761                     writeSpace();
102762                     break;
102763                 case 8 /* AmpersandDelimited */:
102764                     writeSpace();
102765                     writePunctuation("&");
102766                     break;
102767             }
102768         }
102769         function emitNodeList(emit, parentNode, children, format, start, count) {
102770             if (start === void 0) { start = 0; }
102771             if (count === void 0) { count = children ? children.length - start : 0; }
102772             var isUndefined = children === undefined;
102773             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
102774                 return;
102775             }
102776             var isEmpty = children === undefined || start >= children.length || count === 0;
102777             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
102778                 if (onBeforeEmitNodeArray) {
102779                     onBeforeEmitNodeArray(children);
102780                 }
102781                 if (onAfterEmitNodeArray) {
102782                     onAfterEmitNodeArray(children);
102783                 }
102784                 return;
102785             }
102786             if (format & 15360 /* BracketsMask */) {
102787                 writePunctuation(getOpeningBracket(format));
102788                 if (isEmpty && !isUndefined) {
102789                     // TODO: GH#18217
102790                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
102791                 }
102792             }
102793             if (onBeforeEmitNodeArray) {
102794                 onBeforeEmitNodeArray(children);
102795             }
102796             if (isEmpty) {
102797                 // Write a line terminator if the parent node was multi-line
102798                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
102799                     writeLine();
102800                 }
102801                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
102802                     writeSpace();
102803                 }
102804             }
102805             else {
102806                 // Write the opening line terminator or leading whitespace.
102807                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
102808                 var shouldEmitInterveningComments = mayEmitInterveningComments;
102809                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
102810                 if (leadingLineTerminatorCount) {
102811                     writeLine(leadingLineTerminatorCount);
102812                     shouldEmitInterveningComments = false;
102813                 }
102814                 else if (format & 256 /* SpaceBetweenBraces */) {
102815                     writeSpace();
102816                 }
102817                 // Increase the indent, if requested.
102818                 if (format & 128 /* Indented */) {
102819                     increaseIndent();
102820                 }
102821                 // Emit each child.
102822                 var previousSibling = void 0;
102823                 var previousSourceFileTextKind = void 0;
102824                 var shouldDecreaseIndentAfterEmit = false;
102825                 for (var i = 0; i < count; i++) {
102826                     var child = children[start + i];
102827                     // Write the delimiter if this is not the first node.
102828                     if (format & 32 /* AsteriskDelimited */) {
102829                         // always write JSDoc in the format "\n *"
102830                         writeLine();
102831                         writeDelimiter(format);
102832                     }
102833                     else if (previousSibling) {
102834                         // i.e
102835                         //      function commentedParameters(
102836                         //          /* Parameter a */
102837                         //          a
102838                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
102839                         //          ,
102840                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
102841                             emitLeadingCommentsOfPosition(previousSibling.end);
102842                         }
102843                         writeDelimiter(format);
102844                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
102845                         // Write either a line terminator or whitespace to separate the elements.
102846                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
102847                         if (separatingLineTerminatorCount > 0) {
102848                             // If a synthesized node in a single-line list starts on a new
102849                             // line, we should increase the indent.
102850                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
102851                                 increaseIndent();
102852                                 shouldDecreaseIndentAfterEmit = true;
102853                             }
102854                             writeLine(separatingLineTerminatorCount);
102855                             shouldEmitInterveningComments = false;
102856                         }
102857                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
102858                             writeSpace();
102859                         }
102860                     }
102861                     // Emit this child.
102862                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
102863                     if (shouldEmitInterveningComments) {
102864                         if (emitTrailingCommentsOfPosition) {
102865                             var commentRange = ts.getCommentRange(child);
102866                             emitTrailingCommentsOfPosition(commentRange.pos);
102867                         }
102868                     }
102869                     else {
102870                         shouldEmitInterveningComments = mayEmitInterveningComments;
102871                     }
102872                     nextListElementPos = child.pos;
102873                     emit(child);
102874                     if (shouldDecreaseIndentAfterEmit) {
102875                         decreaseIndent();
102876                         shouldDecreaseIndentAfterEmit = false;
102877                     }
102878                     previousSibling = child;
102879                 }
102880                 // Write a trailing comma, if requested.
102881                 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
102882                 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
102883                     writePunctuation(",");
102884                 }
102885                 // Emit any trailing comment of the last element in the list
102886                 // i.e
102887                 //       var array = [...
102888                 //          2
102889                 //          /* end of element 2 */
102890                 //       ];
102891                 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
102892                     emitLeadingCommentsOfPosition(previousSibling.end);
102893                 }
102894                 // Decrease the indent, if requested.
102895                 if (format & 128 /* Indented */) {
102896                     decreaseIndent();
102897                 }
102898                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
102899                 // Write the closing line terminator or closing whitespace.
102900                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
102901                 if (closingLineTerminatorCount) {
102902                     writeLine(closingLineTerminatorCount);
102903                 }
102904                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
102905                     writeSpace();
102906                 }
102907             }
102908             if (onAfterEmitNodeArray) {
102909                 onAfterEmitNodeArray(children);
102910             }
102911             if (format & 15360 /* BracketsMask */) {
102912                 if (isEmpty && !isUndefined) {
102913                     // TODO: GH#18217
102914                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
102915                 }
102916                 writePunctuation(getClosingBracket(format));
102917             }
102918         }
102919         // Writers
102920         function writeLiteral(s) {
102921             writer.writeLiteral(s);
102922         }
102923         function writeStringLiteral(s) {
102924             writer.writeStringLiteral(s);
102925         }
102926         function writeBase(s) {
102927             writer.write(s);
102928         }
102929         function writeSymbol(s, sym) {
102930             writer.writeSymbol(s, sym);
102931         }
102932         function writePunctuation(s) {
102933             writer.writePunctuation(s);
102934         }
102935         function writeTrailingSemicolon() {
102936             writer.writeTrailingSemicolon(";");
102937         }
102938         function writeKeyword(s) {
102939             writer.writeKeyword(s);
102940         }
102941         function writeOperator(s) {
102942             writer.writeOperator(s);
102943         }
102944         function writeParameter(s) {
102945             writer.writeParameter(s);
102946         }
102947         function writeComment(s) {
102948             writer.writeComment(s);
102949         }
102950         function writeSpace() {
102951             writer.writeSpace(" ");
102952         }
102953         function writeProperty(s) {
102954             writer.writeProperty(s);
102955         }
102956         function writeLine(count) {
102957             if (count === void 0) { count = 1; }
102958             for (var i = 0; i < count; i++) {
102959                 writer.writeLine(i > 0);
102960             }
102961         }
102962         function increaseIndent() {
102963             writer.increaseIndent();
102964         }
102965         function decreaseIndent() {
102966             writer.decreaseIndent();
102967         }
102968         function writeToken(token, pos, writer, contextNode) {
102969             return !sourceMapsDisabled
102970                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
102971                 : writeTokenText(token, writer, pos);
102972         }
102973         function writeTokenNode(node, writer) {
102974             if (onBeforeEmitToken) {
102975                 onBeforeEmitToken(node);
102976             }
102977             writer(ts.tokenToString(node.kind));
102978             if (onAfterEmitToken) {
102979                 onAfterEmitToken(node);
102980             }
102981         }
102982         function writeTokenText(token, writer, pos) {
102983             var tokenString = ts.tokenToString(token);
102984             writer(tokenString);
102985             return pos < 0 ? pos : pos + tokenString.length;
102986         }
102987         function writeLineOrSpace(parentNode, prevChildNode, nextChildNode) {
102988             if (ts.getEmitFlags(parentNode) & 1 /* SingleLine */) {
102989                 writeSpace();
102990             }
102991             else if (preserveSourceNewlines) {
102992                 var lines = getLinesBetweenNodes(parentNode, prevChildNode, nextChildNode);
102993                 if (lines) {
102994                     writeLine(lines);
102995                 }
102996                 else {
102997                     writeSpace();
102998                 }
102999             }
103000             else {
103001                 writeLine();
103002             }
103003         }
103004         function writeLines(text) {
103005             var lines = text.split(/\r\n?|\n/g);
103006             var indentation = ts.guessIndentation(lines);
103007             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
103008                 var lineText = lines_3[_a];
103009                 var line = indentation ? lineText.slice(indentation) : lineText;
103010                 if (line.length) {
103011                     writeLine();
103012                     write(line);
103013                 }
103014             }
103015         }
103016         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
103017             if (lineCount) {
103018                 increaseIndent();
103019                 writeLine(lineCount);
103020             }
103021             else if (writeSpaceIfNotIndenting) {
103022                 writeSpace();
103023             }
103024         }
103025         // Helper function to decrease the indent if we previously indented.  Allows multiple
103026         // previous indent values to be considered at a time.  This also allows caller to just
103027         // call this once, passing in all their appropriate indent values, instead of needing
103028         // to call this helper function multiple times.
103029         function decreaseIndentIf(value1, value2) {
103030             if (value1) {
103031                 decreaseIndent();
103032             }
103033             if (value2) {
103034                 decreaseIndent();
103035             }
103036         }
103037         function getLeadingLineTerminatorCount(parentNode, children, format) {
103038             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
103039                 if (format & 65536 /* PreferNewLine */) {
103040                     return 1;
103041                 }
103042                 var firstChild_1 = children[0];
103043                 if (firstChild_1 === undefined) {
103044                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
103045                 }
103046                 if (firstChild_1.pos === nextListElementPos) {
103047                     // If this child starts at the beginning of a list item in a parent list, its leading
103048                     // line terminators have already been written as the separating line terminators of the
103049                     // parent list. Example:
103050                     //
103051                     // class Foo {
103052                     //   constructor() {}
103053                     //   public foo() {}
103054                     // }
103055                     //
103056                     // The outer list is the list of class members, with one line terminator between the
103057                     // constructor and the method. The constructor is written, the separating line terminator
103058                     // is written, and then we start emitting the method. Its modifiers ([public]) constitute an inner
103059                     // list, so we look for its leading line terminators. If we didn't know that we had already
103060                     // written a newline as part of the parent list, it would appear that we need to write a
103061                     // leading newline to start the modifiers.
103062                     return 0;
103063                 }
103064                 if (firstChild_1.kind === 11 /* JsxText */) {
103065                     // JsxText will be written with its leading whitespace, so don't add more manually.
103066                     return 0;
103067                 }
103068                 if (!ts.positionIsSynthesized(parentNode.pos) &&
103069                     !ts.nodeIsSynthesized(firstChild_1) &&
103070                     (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) {
103071                     if (preserveSourceNewlines) {
103072                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
103073                     }
103074                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
103075                 }
103076                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
103077                     return 1;
103078                 }
103079             }
103080             return format & 1 /* MultiLine */ ? 1 : 0;
103081         }
103082         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
103083             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
103084                 if (previousNode === undefined || nextNode === undefined) {
103085                     return 0;
103086                 }
103087                 if (nextNode.kind === 11 /* JsxText */) {
103088                     // JsxText will be written with its leading whitespace, so don't add more manually.
103089                     return 0;
103090                 }
103091                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
103092                     if (preserveSourceNewlines) {
103093                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
103094                     }
103095                     return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
103096                 }
103097                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
103098                     return 1;
103099                 }
103100             }
103101             else if (ts.getStartsOnNewLine(nextNode)) {
103102                 return 1;
103103             }
103104             return format & 1 /* MultiLine */ ? 1 : 0;
103105         }
103106         function getClosingLineTerminatorCount(parentNode, children, format) {
103107             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
103108                 if (format & 65536 /* PreferNewLine */) {
103109                     return 1;
103110                 }
103111                 var lastChild = ts.lastOrUndefined(children);
103112                 if (lastChild === undefined) {
103113                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
103114                 }
103115                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) {
103116                     if (preserveSourceNewlines) {
103117                         var end_2 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end;
103118                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_2, parentNode.end, currentSourceFile, includeComments); });
103119                     }
103120                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1;
103121                 }
103122                 if (synthesizedNodeStartsOnNewLine(lastChild, format)) {
103123                     return 1;
103124                 }
103125             }
103126             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
103127                 return 1;
103128             }
103129             return 0;
103130         }
103131         function getEffectiveLines(getLineDifference) {
103132             // If 'preserveSourceNewlines' is disabled, we should never call this function
103133             // because it could be more expensive than alternative approximations.
103134             ts.Debug.assert(!!preserveSourceNewlines);
103135             // We start by measuring the line difference from a position to its adjacent comments,
103136             // so that this is counted as a one-line difference, not two:
103137             //
103138             //   node1;
103139             //   // NODE2 COMMENT
103140             //   node2;
103141             var lines = getLineDifference(/*includeComments*/ true);
103142             if (lines === 0) {
103143                 // However, if the line difference considering comments was 0, we might have this:
103144                 //
103145                 //   node1; // NODE2 COMMENT
103146                 //   node2;
103147                 //
103148                 // in which case we should be ignoring node2's comment, so this too is counted as
103149                 // a one-line difference, not zero.
103150                 return getLineDifference(/*includeComments*/ false);
103151             }
103152             return lines;
103153         }
103154         function writeLineSeparatorsAndIndentBefore(node, parent) {
103155             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
103156             if (leadingNewlines) {
103157                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
103158             }
103159             return !!leadingNewlines;
103160         }
103161         function writeLineSeparatorsAfter(node, parent) {
103162             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
103163             if (trailingNewlines) {
103164                 writeLine(trailingNewlines);
103165             }
103166         }
103167         function synthesizedNodeStartsOnNewLine(node, format) {
103168             if (ts.nodeIsSynthesized(node)) {
103169                 var startsOnNewLine = ts.getStartsOnNewLine(node);
103170                 if (startsOnNewLine === undefined) {
103171                     return (format & 65536 /* PreferNewLine */) !== 0;
103172                 }
103173                 return startsOnNewLine;
103174             }
103175             return (format & 65536 /* PreferNewLine */) !== 0;
103176         }
103177         function getLinesBetweenNodes(parent, node1, node2) {
103178             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
103179                 return 0;
103180             }
103181             parent = skipSynthesizedParentheses(parent);
103182             node1 = skipSynthesizedParentheses(node1);
103183             node2 = skipSynthesizedParentheses(node2);
103184             // Always use a newline for synthesized code if the synthesizer desires it.
103185             if (ts.getStartsOnNewLine(node2)) {
103186                 return 1;
103187             }
103188             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
103189                 if (preserveSourceNewlines) {
103190                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
103191                 }
103192                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
103193             }
103194             return 0;
103195         }
103196         function isEmptyBlock(block) {
103197             return block.statements.length === 0
103198                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
103199         }
103200         function skipSynthesizedParentheses(node) {
103201             while (node.kind === 207 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
103202                 node = node.expression;
103203             }
103204             return node;
103205         }
103206         function getTextOfNode(node, includeTrivia) {
103207             if (ts.isGeneratedIdentifier(node)) {
103208                 return generateName(node);
103209             }
103210             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
103211                 return ts.idText(node);
103212             }
103213             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
103214                 return getTextOfNode(node.textSourceNode, includeTrivia);
103215             }
103216             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
103217                 return node.text;
103218             }
103219             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
103220         }
103221         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
103222             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
103223                 var textSourceNode = node.textSourceNode;
103224                 if (ts.isIdentifier(textSourceNode) || ts.isNumericLiteral(textSourceNode)) {
103225                     var text = ts.isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode);
103226                     return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(text) + "\"" :
103227                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(text) + "\"" :
103228                             "\"" + ts.escapeNonAsciiString(text) + "\"";
103229                 }
103230                 else {
103231                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
103232                 }
103233             }
103234             var flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0)
103235                 | (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0)
103236                 | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0);
103237             return ts.getLiteralText(node, currentSourceFile, flags);
103238         }
103239         /**
103240          * Push a new name generation scope.
103241          */
103242         function pushNameGenerationScope(node) {
103243             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
103244                 return;
103245             }
103246             tempFlagsStack.push(tempFlags);
103247             tempFlags = 0;
103248             reservedNamesStack.push(reservedNames);
103249         }
103250         /**
103251          * Pop the current name generation scope.
103252          */
103253         function popNameGenerationScope(node) {
103254             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
103255                 return;
103256             }
103257             tempFlags = tempFlagsStack.pop();
103258             reservedNames = reservedNamesStack.pop();
103259         }
103260         function reserveNameInNestedScopes(name) {
103261             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
103262                 reservedNames = new ts.Set();
103263             }
103264             reservedNames.add(name);
103265         }
103266         function generateNames(node) {
103267             if (!node)
103268                 return;
103269             switch (node.kind) {
103270                 case 230 /* Block */:
103271                     ts.forEach(node.statements, generateNames);
103272                     break;
103273                 case 245 /* LabeledStatement */:
103274                 case 243 /* WithStatement */:
103275                 case 235 /* DoStatement */:
103276                 case 236 /* WhileStatement */:
103277                     generateNames(node.statement);
103278                     break;
103279                 case 234 /* IfStatement */:
103280                     generateNames(node.thenStatement);
103281                     generateNames(node.elseStatement);
103282                     break;
103283                 case 237 /* ForStatement */:
103284                 case 239 /* ForOfStatement */:
103285                 case 238 /* ForInStatement */:
103286                     generateNames(node.initializer);
103287                     generateNames(node.statement);
103288                     break;
103289                 case 244 /* SwitchStatement */:
103290                     generateNames(node.caseBlock);
103291                     break;
103292                 case 258 /* CaseBlock */:
103293                     ts.forEach(node.clauses, generateNames);
103294                     break;
103295                 case 284 /* CaseClause */:
103296                 case 285 /* DefaultClause */:
103297                     ts.forEach(node.statements, generateNames);
103298                     break;
103299                 case 247 /* TryStatement */:
103300                     generateNames(node.tryBlock);
103301                     generateNames(node.catchClause);
103302                     generateNames(node.finallyBlock);
103303                     break;
103304                 case 287 /* CatchClause */:
103305                     generateNames(node.variableDeclaration);
103306                     generateNames(node.block);
103307                     break;
103308                 case 232 /* VariableStatement */:
103309                     generateNames(node.declarationList);
103310                     break;
103311                 case 250 /* VariableDeclarationList */:
103312                     ts.forEach(node.declarations, generateNames);
103313                     break;
103314                 case 249 /* VariableDeclaration */:
103315                 case 160 /* Parameter */:
103316                 case 198 /* BindingElement */:
103317                 case 252 /* ClassDeclaration */:
103318                     generateNameIfNeeded(node.name);
103319                     break;
103320                 case 251 /* FunctionDeclaration */:
103321                     generateNameIfNeeded(node.name);
103322                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
103323                         ts.forEach(node.parameters, generateNames);
103324                         generateNames(node.body);
103325                     }
103326                     break;
103327                 case 196 /* ObjectBindingPattern */:
103328                 case 197 /* ArrayBindingPattern */:
103329                     ts.forEach(node.elements, generateNames);
103330                     break;
103331                 case 261 /* ImportDeclaration */:
103332                     generateNames(node.importClause);
103333                     break;
103334                 case 262 /* ImportClause */:
103335                     generateNameIfNeeded(node.name);
103336                     generateNames(node.namedBindings);
103337                     break;
103338                 case 263 /* NamespaceImport */:
103339                     generateNameIfNeeded(node.name);
103340                     break;
103341                 case 269 /* NamespaceExport */:
103342                     generateNameIfNeeded(node.name);
103343                     break;
103344                 case 264 /* NamedImports */:
103345                     ts.forEach(node.elements, generateNames);
103346                     break;
103347                 case 265 /* ImportSpecifier */:
103348                     generateNameIfNeeded(node.propertyName || node.name);
103349                     break;
103350             }
103351         }
103352         function generateMemberNames(node) {
103353             if (!node)
103354                 return;
103355             switch (node.kind) {
103356                 case 288 /* PropertyAssignment */:
103357                 case 289 /* ShorthandPropertyAssignment */:
103358                 case 163 /* PropertyDeclaration */:
103359                 case 165 /* MethodDeclaration */:
103360                 case 167 /* GetAccessor */:
103361                 case 168 /* SetAccessor */:
103362                     generateNameIfNeeded(node.name);
103363                     break;
103364             }
103365         }
103366         function generateNameIfNeeded(name) {
103367             if (name) {
103368                 if (ts.isGeneratedIdentifier(name)) {
103369                     generateName(name);
103370                 }
103371                 else if (ts.isBindingPattern(name)) {
103372                     generateNames(name);
103373                 }
103374             }
103375         }
103376         /**
103377          * Generate the text for a generated identifier.
103378          */
103379         function generateName(name) {
103380             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
103381                 // Node names generate unique names based on their original node
103382                 // and are cached based on that node's id.
103383                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
103384             }
103385             else {
103386                 // Auto, Loop, and Unique names are cached based on their unique
103387                 // autoGenerateId.
103388                 var autoGenerateId = name.autoGenerateId;
103389                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
103390             }
103391         }
103392         function generateNameCached(node, flags) {
103393             var nodeId = ts.getNodeId(node);
103394             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
103395         }
103396         /**
103397          * Returns a value indicating whether a name is unique globally, within the current file,
103398          * or within the NameGenerator.
103399          */
103400         function isUniqueName(name) {
103401             return isFileLevelUniqueName(name)
103402                 && !generatedNames.has(name)
103403                 && !(reservedNames && reservedNames.has(name));
103404         }
103405         /**
103406          * Returns a value indicating whether a name is unique globally or within the current file.
103407          */
103408         function isFileLevelUniqueName(name) {
103409             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
103410         }
103411         /**
103412          * Returns a value indicating whether a name is unique within a container.
103413          */
103414         function isUniqueLocalName(name, container) {
103415             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
103416                 if (node.locals) {
103417                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
103418                     // We conservatively include alias symbols to cover cases where they're emitted as locals
103419                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
103420                         return false;
103421                     }
103422                 }
103423             }
103424             return true;
103425         }
103426         /**
103427          * Return the next available name in the pattern _a ... _z, _0, _1, ...
103428          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
103429          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
103430          */
103431         function makeTempVariableName(flags, reservedInNestedScopes) {
103432             if (flags && !(tempFlags & flags)) {
103433                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
103434                 if (isUniqueName(name)) {
103435                     tempFlags |= flags;
103436                     if (reservedInNestedScopes) {
103437                         reserveNameInNestedScopes(name);
103438                     }
103439                     return name;
103440                 }
103441             }
103442             while (true) {
103443                 var count = tempFlags & 268435455 /* CountMask */;
103444                 tempFlags++;
103445                 // Skip over 'i' and 'n'
103446                 if (count !== 8 && count !== 13) {
103447                     var name = count < 26
103448                         ? "_" + String.fromCharCode(97 /* a */ + count)
103449                         : "_" + (count - 26);
103450                     if (isUniqueName(name)) {
103451                         if (reservedInNestedScopes) {
103452                             reserveNameInNestedScopes(name);
103453                         }
103454                         return name;
103455                     }
103456                 }
103457             }
103458         }
103459         /**
103460          * Generate a name that is unique within the current file and doesn't conflict with any names
103461          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
103462          * where n is a positive integer. Note that names generated by makeTempVariableName and
103463          * makeUniqueName are guaranteed to never conflict.
103464          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
103465          */
103466         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
103467             if (checkFn === void 0) { checkFn = isUniqueName; }
103468             if (optimistic) {
103469                 if (checkFn(baseName)) {
103470                     if (scoped) {
103471                         reserveNameInNestedScopes(baseName);
103472                     }
103473                     else {
103474                         generatedNames.add(baseName);
103475                     }
103476                     return baseName;
103477                 }
103478             }
103479             // Find the first unique 'name_n', where n is a positive number
103480             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
103481                 baseName += "_";
103482             }
103483             var i = 1;
103484             while (true) {
103485                 var generatedName = baseName + i;
103486                 if (checkFn(generatedName)) {
103487                     if (scoped) {
103488                         reserveNameInNestedScopes(generatedName);
103489                     }
103490                     else {
103491                         generatedNames.add(generatedName);
103492                     }
103493                     return generatedName;
103494                 }
103495                 i++;
103496             }
103497         }
103498         function makeFileLevelOptimisticUniqueName(name) {
103499             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
103500         }
103501         /**
103502          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
103503          */
103504         function generateNameForModuleOrEnum(node) {
103505             var name = getTextOfNode(node.name);
103506             // Use module/enum name itself if it is unique, otherwise make a unique variation
103507             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
103508         }
103509         /**
103510          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
103511          */
103512         function generateNameForImportOrExportDeclaration(node) {
103513             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
103514             var baseName = ts.isStringLiteral(expr) ?
103515                 ts.makeIdentifierFromModuleName(expr.text) : "module";
103516             return makeUniqueName(baseName);
103517         }
103518         /**
103519          * Generates a unique name for a default export.
103520          */
103521         function generateNameForExportDefault() {
103522             return makeUniqueName("default");
103523         }
103524         /**
103525          * Generates a unique name for a class expression.
103526          */
103527         function generateNameForClassExpression() {
103528             return makeUniqueName("class");
103529         }
103530         function generateNameForMethodOrAccessor(node) {
103531             if (ts.isIdentifier(node.name)) {
103532                 return generateNameCached(node.name);
103533             }
103534             return makeTempVariableName(0 /* Auto */);
103535         }
103536         /**
103537          * Generates a unique name from a node.
103538          */
103539         function generateNameForNode(node, flags) {
103540             switch (node.kind) {
103541                 case 78 /* Identifier */:
103542                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
103543                 case 256 /* ModuleDeclaration */:
103544                 case 255 /* EnumDeclaration */:
103545                     return generateNameForModuleOrEnum(node);
103546                 case 261 /* ImportDeclaration */:
103547                 case 267 /* ExportDeclaration */:
103548                     return generateNameForImportOrExportDeclaration(node);
103549                 case 251 /* FunctionDeclaration */:
103550                 case 252 /* ClassDeclaration */:
103551                 case 266 /* ExportAssignment */:
103552                     return generateNameForExportDefault();
103553                 case 221 /* ClassExpression */:
103554                     return generateNameForClassExpression();
103555                 case 165 /* MethodDeclaration */:
103556                 case 167 /* GetAccessor */:
103557                 case 168 /* SetAccessor */:
103558                     return generateNameForMethodOrAccessor(node);
103559                 case 158 /* ComputedPropertyName */:
103560                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
103561                 default:
103562                     return makeTempVariableName(0 /* Auto */);
103563             }
103564         }
103565         /**
103566          * Generates a unique identifier for a node.
103567          */
103568         function makeName(name) {
103569             switch (name.autoGenerateFlags & 7 /* KindMask */) {
103570                 case 1 /* Auto */:
103571                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
103572                 case 2 /* Loop */:
103573                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
103574                 case 3 /* Unique */:
103575                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
103576             }
103577             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
103578         }
103579         /**
103580          * Gets the node from which a name should be generated.
103581          */
103582         function getNodeForGeneratedName(name) {
103583             var autoGenerateId = name.autoGenerateId;
103584             var node = name;
103585             var original = node.original;
103586             while (original) {
103587                 node = original;
103588                 // if "node" is a different generated name (having a different
103589                 // "autoGenerateId"), use it and stop traversing.
103590                 if (ts.isIdentifier(node)
103591                     && !!(node.autoGenerateFlags & 4 /* Node */)
103592                     && node.autoGenerateId !== autoGenerateId) {
103593                     break;
103594                 }
103595                 original = node.original;
103596             }
103597             // otherwise, return the original node for the source;
103598             return node;
103599         }
103600         // Comments
103601         function pipelineEmitWithComments(hint, node) {
103602             ts.Debug.assert(lastNode === node || lastSubstitution === node);
103603             enterComment();
103604             hasWrittenComment = false;
103605             var emitFlags = ts.getEmitFlags(node);
103606             var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
103607             var isEmittedNode = node.kind !== 335 /* NotEmittedStatement */;
103608             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
103609             // It is expensive to walk entire tree just to set one kind of node to have no comments.
103610             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
103611             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
103612             // Save current container state on the stack.
103613             var savedContainerPos = containerPos;
103614             var savedContainerEnd = containerEnd;
103615             var savedDeclarationListContainerEnd = declarationListContainerEnd;
103616             if ((pos > 0 || end > 0) && pos !== end) {
103617                 // Emit leading comments if the position is not synthesized and the node
103618                 // has not opted out from emitting leading comments.
103619                 if (!skipLeadingComments) {
103620                     emitLeadingComments(pos, isEmittedNode);
103621                 }
103622                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
103623                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
103624                     containerPos = pos;
103625                 }
103626                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
103627                     // As above.
103628                     containerEnd = end;
103629                     // To avoid invalid comment emit in a down-level binding pattern, we
103630                     // keep track of the last declaration list container's end
103631                     if (node.kind === 250 /* VariableDeclarationList */) {
103632                         declarationListContainerEnd = end;
103633                     }
103634                 }
103635             }
103636             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
103637             exitComment();
103638             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
103639             if (emitFlags & 2048 /* NoNestedComments */) {
103640                 commentsDisabled = true;
103641                 pipelinePhase(hint, node);
103642                 commentsDisabled = false;
103643             }
103644             else {
103645                 pipelinePhase(hint, node);
103646             }
103647             enterComment();
103648             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
103649             if ((pos > 0 || end > 0) && pos !== end) {
103650                 // Restore previous container state.
103651                 containerPos = savedContainerPos;
103652                 containerEnd = savedContainerEnd;
103653                 declarationListContainerEnd = savedDeclarationListContainerEnd;
103654                 // Emit trailing comments if the position is not synthesized and the node
103655                 // has not opted out from emitting leading comments and is an emitted node.
103656                 if (!skipTrailingComments && isEmittedNode) {
103657                     emitTrailingComments(end);
103658                 }
103659             }
103660             exitComment();
103661             ts.Debug.assert(lastNode === node || lastSubstitution === node);
103662         }
103663         function emitLeadingSynthesizedComment(comment) {
103664             if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) {
103665                 writer.writeLine();
103666             }
103667             writeSynthesizedComment(comment);
103668             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
103669                 writer.writeLine();
103670             }
103671             else {
103672                 writer.writeSpace(" ");
103673             }
103674         }
103675         function emitTrailingSynthesizedComment(comment) {
103676             if (!writer.isAtStartOfLine()) {
103677                 writer.writeSpace(" ");
103678             }
103679             writeSynthesizedComment(comment);
103680             if (comment.hasTrailingNewLine) {
103681                 writer.writeLine();
103682             }
103683         }
103684         function writeSynthesizedComment(comment) {
103685             var text = formatSynthesizedComment(comment);
103686             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
103687             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
103688         }
103689         function formatSynthesizedComment(comment) {
103690             return comment.kind === 3 /* MultiLineCommentTrivia */
103691                 ? "/*" + comment.text + "*/"
103692                 : "//" + comment.text;
103693         }
103694         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
103695             enterComment();
103696             var pos = detachedRange.pos, end = detachedRange.end;
103697             var emitFlags = ts.getEmitFlags(node);
103698             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
103699             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
103700             if (!skipLeadingComments) {
103701                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
103702             }
103703             exitComment();
103704             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
103705                 commentsDisabled = true;
103706                 emitCallback(node);
103707                 commentsDisabled = false;
103708             }
103709             else {
103710                 emitCallback(node);
103711             }
103712             enterComment();
103713             if (!skipTrailingComments) {
103714                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
103715                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
103716                     writer.writeLine();
103717                 }
103718             }
103719             exitComment();
103720         }
103721         function emitLeadingComments(pos, isEmittedNode) {
103722             hasWrittenComment = false;
103723             if (isEmittedNode) {
103724                 if (pos === 0 && (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.isDeclarationFile)) {
103725                     forEachLeadingCommentToEmit(pos, emitNonTripleSlashLeadingComment);
103726                 }
103727                 else {
103728                     forEachLeadingCommentToEmit(pos, emitLeadingComment);
103729                 }
103730             }
103731             else if (pos === 0) {
103732                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
103733                 // unless it is a triple slash comment at the top of the file.
103734                 // For Example:
103735                 //      /// <reference-path ...>
103736                 //      declare var x;
103737                 //      /// <reference-path ...>
103738                 //      interface F {}
103739                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
103740                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
103741             }
103742         }
103743         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
103744             if (isTripleSlashComment(commentPos, commentEnd)) {
103745                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
103746             }
103747         }
103748         function emitNonTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
103749             if (!isTripleSlashComment(commentPos, commentEnd)) {
103750                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
103751             }
103752         }
103753         function shouldWriteComment(text, pos) {
103754             if (printerOptions.onlyPrintJsDocStyle) {
103755                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
103756             }
103757             return true;
103758         }
103759         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
103760             if (!shouldWriteComment(currentSourceFile.text, commentPos))
103761                 return;
103762             if (!hasWrittenComment) {
103763                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
103764                 hasWrittenComment = true;
103765             }
103766             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
103767             emitPos(commentPos);
103768             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
103769             emitPos(commentEnd);
103770             if (hasTrailingNewLine) {
103771                 writer.writeLine();
103772             }
103773             else if (kind === 3 /* MultiLineCommentTrivia */) {
103774                 writer.writeSpace(" ");
103775             }
103776         }
103777         function emitLeadingCommentsOfPosition(pos) {
103778             if (commentsDisabled || pos === -1) {
103779                 return;
103780             }
103781             emitLeadingComments(pos, /*isEmittedNode*/ true);
103782         }
103783         function emitTrailingComments(pos) {
103784             forEachTrailingCommentToEmit(pos, emitTrailingComment);
103785         }
103786         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
103787             if (!shouldWriteComment(currentSourceFile.text, commentPos))
103788                 return;
103789             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
103790             if (!writer.isAtStartOfLine()) {
103791                 writer.writeSpace(" ");
103792             }
103793             emitPos(commentPos);
103794             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
103795             emitPos(commentEnd);
103796             if (hasTrailingNewLine) {
103797                 writer.writeLine();
103798             }
103799         }
103800         function emitTrailingCommentsOfPosition(pos, prefixSpace) {
103801             if (commentsDisabled) {
103802                 return;
103803             }
103804             enterComment();
103805             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
103806             exitComment();
103807         }
103808         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
103809             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
103810             emitPos(commentPos);
103811             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
103812             emitPos(commentEnd);
103813             if (hasTrailingNewLine) {
103814                 writer.writeLine();
103815             }
103816             else {
103817                 writer.writeSpace(" ");
103818             }
103819         }
103820         function forEachLeadingCommentToEmit(pos, cb) {
103821             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
103822             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
103823                 if (hasDetachedComments(pos)) {
103824                     forEachLeadingCommentWithoutDetachedComments(cb);
103825                 }
103826                 else {
103827                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
103828                 }
103829             }
103830         }
103831         function forEachTrailingCommentToEmit(end, cb) {
103832             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
103833             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
103834                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
103835             }
103836         }
103837         function hasDetachedComments(pos) {
103838             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
103839         }
103840         function forEachLeadingCommentWithoutDetachedComments(cb) {
103841             // get the leading comments from detachedPos
103842             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
103843             if (detachedCommentsInfo.length - 1) {
103844                 detachedCommentsInfo.pop();
103845             }
103846             else {
103847                 detachedCommentsInfo = undefined;
103848             }
103849             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
103850         }
103851         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
103852             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
103853             if (currentDetachedCommentInfo) {
103854                 if (detachedCommentsInfo) {
103855                     detachedCommentsInfo.push(currentDetachedCommentInfo);
103856                 }
103857                 else {
103858                     detachedCommentsInfo = [currentDetachedCommentInfo];
103859                 }
103860             }
103861         }
103862         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
103863             if (!shouldWriteComment(currentSourceFile.text, commentPos))
103864                 return;
103865             emitPos(commentPos);
103866             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
103867             emitPos(commentEnd);
103868         }
103869         /**
103870          * Determine if the given comment is a triple-slash
103871          *
103872          * @return true if the comment is a triple-slash comment else false
103873          */
103874         function isTripleSlashComment(commentPos, commentEnd) {
103875             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
103876         }
103877         // Source Maps
103878         function getParsedSourceMap(node) {
103879             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
103880                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
103881             }
103882             return node.parsedSourceMap || undefined;
103883         }
103884         function pipelineEmitWithSourceMap(hint, node) {
103885             ts.Debug.assert(lastNode === node || lastSubstitution === node);
103886             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
103887             if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
103888                 pipelinePhase(hint, node);
103889             }
103890             else if (ts.isUnparsedNode(node)) {
103891                 var parsed = getParsedSourceMap(node.parent);
103892                 if (parsed && sourceMapGenerator) {
103893                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
103894                 }
103895                 pipelinePhase(hint, node);
103896             }
103897             else {
103898                 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
103899                 var emitFlags = ts.getEmitFlags(node);
103900                 if (node.kind !== 335 /* NotEmittedStatement */
103901                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
103902                     && pos >= 0) {
103903                     emitSourcePos(source, skipSourceTrivia(source, pos));
103904                 }
103905                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
103906                     sourceMapsDisabled = true;
103907                     pipelinePhase(hint, node);
103908                     sourceMapsDisabled = false;
103909                 }
103910                 else {
103911                     pipelinePhase(hint, node);
103912                 }
103913                 if (node.kind !== 335 /* NotEmittedStatement */
103914                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
103915                     && end >= 0) {
103916                     emitSourcePos(source, end);
103917                 }
103918             }
103919             ts.Debug.assert(lastNode === node || lastSubstitution === node);
103920         }
103921         /**
103922          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
103923          */
103924         function skipSourceTrivia(source, pos) {
103925             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
103926         }
103927         /**
103928          * Emits a mapping.
103929          *
103930          * If the position is synthetic (undefined or a negative value), no mapping will be
103931          * created.
103932          *
103933          * @param pos The position.
103934          */
103935         function emitPos(pos) {
103936             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
103937                 return;
103938             }
103939             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
103940             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
103941             /*nameIndex*/ undefined);
103942         }
103943         function emitSourcePos(source, pos) {
103944             if (source !== sourceMapSource) {
103945                 var savedSourceMapSource = sourceMapSource;
103946                 var savedSourceMapSourceIndex = sourceMapSourceIndex;
103947                 setSourceMapSource(source);
103948                 emitPos(pos);
103949                 resetSourceMapSource(savedSourceMapSource, savedSourceMapSourceIndex);
103950             }
103951             else {
103952                 emitPos(pos);
103953             }
103954         }
103955         /**
103956          * Emits a token of a node with possible leading and trailing source maps.
103957          *
103958          * @param node The node containing the token.
103959          * @param token The token to emit.
103960          * @param tokenStartPos The start pos of the token.
103961          * @param emitCallback The callback used to emit the token.
103962          */
103963         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
103964             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
103965                 return emitCallback(token, writer, tokenPos);
103966             }
103967             var emitNode = node && node.emitNode;
103968             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
103969             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
103970             var source = range && range.source || sourceMapSource;
103971             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
103972             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
103973                 emitSourcePos(source, tokenPos);
103974             }
103975             tokenPos = emitCallback(token, writer, tokenPos);
103976             if (range)
103977                 tokenPos = range.end;
103978             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
103979                 emitSourcePos(source, tokenPos);
103980             }
103981             return tokenPos;
103982         }
103983         function setSourceMapSource(source) {
103984             if (sourceMapsDisabled) {
103985                 return;
103986             }
103987             sourceMapSource = source;
103988             if (source === mostRecentlyAddedSourceMapSource) {
103989                 // Fast path for when the new source map is the most recently added, in which case
103990                 // we use its captured index without going through the source map generator.
103991                 sourceMapSourceIndex = mostRecentlyAddedSourceMapSourceIndex;
103992                 return;
103993             }
103994             if (isJsonSourceMapSource(source)) {
103995                 return;
103996             }
103997             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
103998             if (printerOptions.inlineSources) {
103999                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
104000             }
104001             mostRecentlyAddedSourceMapSource = source;
104002             mostRecentlyAddedSourceMapSourceIndex = sourceMapSourceIndex;
104003         }
104004         function resetSourceMapSource(source, sourceIndex) {
104005             sourceMapSource = source;
104006             sourceMapSourceIndex = sourceIndex;
104007         }
104008         function isJsonSourceMapSource(sourceFile) {
104009             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
104010         }
104011     }
104012     ts.createPrinter = createPrinter;
104013     function createBracketsMap() {
104014         var brackets = [];
104015         brackets[1024 /* Braces */] = ["{", "}"];
104016         brackets[2048 /* Parenthesis */] = ["(", ")"];
104017         brackets[4096 /* AngleBrackets */] = ["<", ">"];
104018         brackets[8192 /* SquareBrackets */] = ["[", "]"];
104019         return brackets;
104020     }
104021     function getOpeningBracket(format) {
104022         return brackets[format & 15360 /* BracketsMask */][0];
104023     }
104024     function getClosingBracket(format) {
104025         return brackets[format & 15360 /* BracketsMask */][1];
104026     }
104027     // Flags enum to track count of temp variables and a few dedicated names
104028     var TempFlags;
104029     (function (TempFlags) {
104030         TempFlags[TempFlags["Auto"] = 0] = "Auto";
104031         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
104032         TempFlags[TempFlags["_i"] = 268435456] = "_i";
104033     })(TempFlags || (TempFlags = {}));
104034 })(ts || (ts = {}));
104035 /* @internal */
104036 var ts;
104037 (function (ts) {
104038     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
104039         if (!host.getDirectories || !host.readDirectory) {
104040             return undefined;
104041         }
104042         var cachedReadDirectoryResult = new ts.Map();
104043         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
104044         return {
104045             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
104046             fileExists: fileExists,
104047             readFile: function (path, encoding) { return host.readFile(path, encoding); },
104048             directoryExists: host.directoryExists && directoryExists,
104049             getDirectories: getDirectories,
104050             readDirectory: readDirectory,
104051             createDirectory: host.createDirectory && createDirectory,
104052             writeFile: host.writeFile && writeFile,
104053             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
104054             addOrDeleteFile: addOrDeleteFile,
104055             clearCache: clearCache,
104056             realpath: host.realpath && realpath
104057         };
104058         function toPath(fileName) {
104059             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
104060         }
104061         function getCachedFileSystemEntries(rootDirPath) {
104062             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
104063         }
104064         function getCachedFileSystemEntriesForBaseDir(path) {
104065             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
104066         }
104067         function getBaseNameOfFileName(fileName) {
104068             return ts.getBaseFileName(ts.normalizePath(fileName));
104069         }
104070         function createCachedFileSystemEntries(rootDir, rootDirPath) {
104071             var resultFromHost = {
104072                 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
104073                 directories: host.getDirectories(rootDir) || []
104074             };
104075             cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
104076             return resultFromHost;
104077         }
104078         /**
104079          * If the readDirectory result was already cached, it returns that
104080          * Otherwise gets result from host and caches it.
104081          * The host request is done under try catch block to avoid caching incorrect result
104082          */
104083         function tryReadDirectory(rootDir, rootDirPath) {
104084             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
104085             var cachedResult = getCachedFileSystemEntries(rootDirPath);
104086             if (cachedResult) {
104087                 return cachedResult;
104088             }
104089             try {
104090                 return createCachedFileSystemEntries(rootDir, rootDirPath);
104091             }
104092             catch (_e) {
104093                 // If there is exception to read directories, dont cache the result and direct the calls to host
104094                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
104095                 return undefined;
104096             }
104097         }
104098         function fileNameEqual(name1, name2) {
104099             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
104100         }
104101         function hasEntry(entries, name) {
104102             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
104103         }
104104         function updateFileSystemEntry(entries, baseName, isValid) {
104105             if (hasEntry(entries, baseName)) {
104106                 if (!isValid) {
104107                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
104108                 }
104109             }
104110             else if (isValid) {
104111                 return entries.push(baseName);
104112             }
104113         }
104114         function writeFile(fileName, data, writeByteOrderMark) {
104115             var path = toPath(fileName);
104116             var result = getCachedFileSystemEntriesForBaseDir(path);
104117             if (result) {
104118                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
104119             }
104120             return host.writeFile(fileName, data, writeByteOrderMark);
104121         }
104122         function fileExists(fileName) {
104123             var path = toPath(fileName);
104124             var result = getCachedFileSystemEntriesForBaseDir(path);
104125             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
104126                 host.fileExists(fileName);
104127         }
104128         function directoryExists(dirPath) {
104129             var path = toPath(dirPath);
104130             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
104131         }
104132         function createDirectory(dirPath) {
104133             var path = toPath(dirPath);
104134             var result = getCachedFileSystemEntriesForBaseDir(path);
104135             var baseFileName = getBaseNameOfFileName(dirPath);
104136             if (result) {
104137                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
104138             }
104139             host.createDirectory(dirPath);
104140         }
104141         function getDirectories(rootDir) {
104142             var rootDirPath = toPath(rootDir);
104143             var result = tryReadDirectory(rootDir, rootDirPath);
104144             if (result) {
104145                 return result.directories.slice();
104146             }
104147             return host.getDirectories(rootDir);
104148         }
104149         function readDirectory(rootDir, extensions, excludes, includes, depth) {
104150             var rootDirPath = toPath(rootDir);
104151             var result = tryReadDirectory(rootDir, rootDirPath);
104152             if (result) {
104153                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
104154             }
104155             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
104156             function getFileSystemEntries(dir) {
104157                 var path = toPath(dir);
104158                 if (path === rootDirPath) {
104159                     return result;
104160                 }
104161                 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
104162             }
104163         }
104164         function realpath(s) {
104165             return host.realpath ? host.realpath(s) : s;
104166         }
104167         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
104168             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
104169             if (existingResult) {
104170                 // Just clear the cache for now
104171                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
104172                 clearCache();
104173                 return undefined;
104174             }
104175             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
104176             if (!parentResult) {
104177                 return undefined;
104178             }
104179             // This was earlier a file (hence not in cached directory contents)
104180             // or we never cached the directory containing it
104181             if (!host.directoryExists) {
104182                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
104183                 clearCache();
104184                 return undefined;
104185             }
104186             var baseName = getBaseNameOfFileName(fileOrDirectory);
104187             var fsQueryResult = {
104188                 fileExists: host.fileExists(fileOrDirectoryPath),
104189                 directoryExists: host.directoryExists(fileOrDirectoryPath)
104190             };
104191             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
104192                 // Folder added or removed, clear the cache instead of updating the folder and its structure
104193                 clearCache();
104194             }
104195             else {
104196                 // No need to update the directory structure, just files
104197                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
104198             }
104199             return fsQueryResult;
104200         }
104201         function addOrDeleteFile(fileName, filePath, eventKind) {
104202             if (eventKind === ts.FileWatcherEventKind.Changed) {
104203                 return;
104204             }
104205             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
104206             if (parentResult) {
104207                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
104208             }
104209         }
104210         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
104211             updateFileSystemEntry(parentResult.files, baseName, fileExists);
104212         }
104213         function clearCache() {
104214             cachedReadDirectoryResult.clear();
104215         }
104216     }
104217     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
104218     var ConfigFileProgramReloadLevel;
104219     (function (ConfigFileProgramReloadLevel) {
104220         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
104221         /** Update the file name list from the disk */
104222         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
104223         /** Reload completely by re-reading contents of config file from disk and updating program */
104224         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
104225     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
104226     /**
104227      * Updates the existing missing file watches with the new set of missing files after new program is created
104228      */
104229     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
104230         var missingFilePaths = program.getMissingFilePaths();
104231         // TODO(rbuckton): Should be a `Set` but that requires changing the below code that uses `mutateMap`
104232         var newMissingFilePathMap = ts.arrayToMap(missingFilePaths, ts.identity, ts.returnTrue);
104233         // Update the missing file paths watcher
104234         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
104235             // Watch the missing files
104236             createNewValue: createMissingFileWatch,
104237             // Files that are no longer missing (e.g. because they are no longer required)
104238             // should no longer be watched.
104239             onDeleteValue: ts.closeFileWatcher
104240         });
104241     }
104242     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
104243     /**
104244      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
104245      * after new program is created because the config file was reloaded or program was created first time from the config file
104246      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
104247      * as wildcard directories wont change unless reloading config file
104248      */
104249     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
104250         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
104251             // Create new watch and recursive info
104252             createNewValue: createWildcardDirectoryWatcher,
104253             // Close existing watch thats not needed any more
104254             onDeleteValue: closeFileWatcherOf,
104255             // Close existing watch that doesnt match in the flags
104256             onExistingValue: updateWildcardDirectoryWatcher
104257         });
104258         function createWildcardDirectoryWatcher(directory, flags) {
104259             // Create new watch and recursive info
104260             return {
104261                 watcher: watchDirectory(directory, flags),
104262                 flags: flags
104263             };
104264         }
104265         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
104266             // Watcher needs to be updated if the recursive flags dont match
104267             if (existingWatcher.flags === flags) {
104268                 return;
104269             }
104270             existingWatcher.watcher.close();
104271             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
104272         }
104273     }
104274     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
104275     /* @internal */
104276     function isIgnoredFileFromWildCardWatching(_a) {
104277         var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, configFileSpecs = _a.configFileSpecs, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog;
104278         var newPath = ts.removeIgnoredPath(fileOrDirectoryPath);
104279         if (!newPath) {
104280             writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory);
104281             return true;
104282         }
104283         fileOrDirectoryPath = newPath;
104284         if (fileOrDirectoryPath === watchedDirPath)
104285             return false;
104286         // If the the added or created file or directory is not supported file name, ignore the file
104287         // But when watched directory is added/removed, we need to reload the file list
104288         if (ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions)) {
104289             writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
104290             return true;
104291         }
104292         if (ts.isExcludedFile(fileOrDirectory, configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) {
104293             writeLog("Project: " + configFileName + " Detected excluded file: " + fileOrDirectory);
104294             return true;
104295         }
104296         if (!program)
104297             return false;
104298         // We want to ignore emit file check if file is not going to be emitted next to source file
104299         // In that case we follow config file inclusion rules
104300         if (options.outFile || options.outDir)
104301             return false;
104302         // File if emitted next to input needs to be ignored
104303         if (ts.fileExtensionIs(fileOrDirectoryPath, ".d.ts" /* Dts */)) {
104304             // If its declaration directory: its not ignored if not excluded by config
104305             if (options.declarationDir)
104306                 return false;
104307         }
104308         else if (!ts.fileExtensionIsOneOf(fileOrDirectoryPath, ts.supportedJSExtensions)) {
104309             return false;
104310         }
104311         // just check if sourceFile with the name exists
104312         var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath);
104313         var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program;
104314         if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) ||
104315             hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) {
104316             writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory);
104317             return true;
104318         }
104319         return false;
104320         function hasSourceFile(file) {
104321             return realProgram ?
104322                 !!realProgram.getSourceFileByPath(file) :
104323                 program.getState().fileInfos.has(file);
104324         }
104325     }
104326     ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching;
104327     function isBuilderProgram(program) {
104328         return !!program.getState;
104329     }
104330     function isEmittedFileOfProgram(program, file) {
104331         if (!program) {
104332             return false;
104333         }
104334         return program.isEmittedFile(file);
104335     }
104336     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
104337     var WatchLogLevel;
104338     (function (WatchLogLevel) {
104339         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
104340         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
104341         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
104342     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
104343     function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
104344         return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
104345     }
104346     ts.getWatchFactory = getWatchFactory;
104347     function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
104348         var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
104349         var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
104350         var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
104351         if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
104352             ts.setSysLog(function (s) { return log(s); });
104353         }
104354         return {
104355             watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
104356                 return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
104357             },
104358             watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
104359                 return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
104360             },
104361             watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
104362                 return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
104363             }
104364         };
104365     }
104366     function watchFile(host, file, callback, pollingInterval, options) {
104367         return host.watchFile(file, callback, pollingInterval, options);
104368     }
104369     function watchFilePath(host, file, callback, pollingInterval, options, path) {
104370         return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
104371     }
104372     function watchDirectory(host, directory, callback, flags, options) {
104373         return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
104374     }
104375     function getCreateFileWatcher(watchLogLevel, addWatch) {
104376         switch (watchLogLevel) {
104377             case WatchLogLevel.None:
104378                 return addWatch;
104379             case WatchLogLevel.TriggerOnly:
104380                 return createFileWatcherWithTriggerLogging;
104381             case WatchLogLevel.Verbose:
104382                 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
104383         }
104384     }
104385     function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
104386         log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
104387         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
104388         return {
104389             close: function () {
104390                 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
104391                 watcher.close();
104392             }
104393         };
104394     }
104395     function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
104396         var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
104397         log(watchInfo);
104398         var start = ts.timestamp();
104399         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
104400         var elapsed = ts.timestamp() - start;
104401         log("Elapsed:: " + elapsed + "ms " + watchInfo);
104402         return {
104403             close: function () {
104404                 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
104405                 log(watchInfo);
104406                 var start = ts.timestamp();
104407                 watcher.close();
104408                 var elapsed = ts.timestamp() - start;
104409                 log("Elapsed:: " + elapsed + "ms " + watchInfo);
104410             }
104411         };
104412     }
104413     function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
104414         return addWatch(host, file, function (fileName, cbOptional) {
104415             var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
104416             log(triggerredInfo);
104417             var start = ts.timestamp();
104418             cb(fileName, cbOptional, passThrough);
104419             var elapsed = ts.timestamp() - start;
104420             log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
104421         }, flags, options);
104422     }
104423     function getFallbackOptions(options) {
104424         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
104425         return {
104426             watchFile: fallbackPolling !== undefined ?
104427                 fallbackPolling :
104428                 ts.WatchFileKind.PriorityPollingInterval
104429         };
104430     }
104431     ts.getFallbackOptions = getFallbackOptions;
104432     function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
104433         return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
104434     }
104435     function closeFileWatcherOf(objWithWatcher) {
104436         objWithWatcher.watcher.close();
104437     }
104438     ts.closeFileWatcherOf = closeFileWatcherOf;
104439 })(ts || (ts = {}));
104440 var ts;
104441 (function (ts) {
104442     function findConfigFile(searchPath, fileExists, configName) {
104443         if (configName === void 0) { configName = "tsconfig.json"; }
104444         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
104445             var fileName = ts.combinePaths(ancestor, configName);
104446             return fileExists(fileName) ? fileName : undefined;
104447         });
104448     }
104449     ts.findConfigFile = findConfigFile;
104450     function resolveTripleslashReference(moduleName, containingFile) {
104451         var basePath = ts.getDirectoryPath(containingFile);
104452         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
104453         return ts.normalizePath(referencedFileName);
104454     }
104455     ts.resolveTripleslashReference = resolveTripleslashReference;
104456     /* @internal */
104457     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
104458         var commonPathComponents;
104459         var failed = ts.forEach(fileNames, function (sourceFile) {
104460             // Each file contributes into common source file path
104461             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
104462             sourcePathComponents.pop(); // The base file name is not part of the common directory path
104463             if (!commonPathComponents) {
104464                 // first file
104465                 commonPathComponents = sourcePathComponents;
104466                 return;
104467             }
104468             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
104469             for (var i = 0; i < n; i++) {
104470                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
104471                     if (i === 0) {
104472                         // Failed to find any common path component
104473                         return true;
104474                     }
104475                     // New common path found that is 0 -> i-1
104476                     commonPathComponents.length = i;
104477                     break;
104478                 }
104479             }
104480             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
104481             if (sourcePathComponents.length < commonPathComponents.length) {
104482                 commonPathComponents.length = sourcePathComponents.length;
104483             }
104484         });
104485         // A common path can not be found when paths span multiple drives on windows, for example
104486         if (failed) {
104487             return "";
104488         }
104489         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
104490             return currentDirectory;
104491         }
104492         return ts.getPathFromPathComponents(commonPathComponents);
104493     }
104494     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
104495     function createCompilerHost(options, setParentNodes) {
104496         return createCompilerHostWorker(options, setParentNodes);
104497     }
104498     ts.createCompilerHost = createCompilerHost;
104499     /*@internal*/
104500     // TODO(shkamat): update this after reworking ts build API
104501     function createCompilerHostWorker(options, setParentNodes, system) {
104502         if (system === void 0) { system = ts.sys; }
104503         var existingDirectories = new ts.Map();
104504         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
104505         var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash;
104506         function getSourceFile(fileName, languageVersion, onError) {
104507             var text;
104508             try {
104509                 ts.performance.mark("beforeIORead");
104510                 text = compilerHost.readFile(fileName);
104511                 ts.performance.mark("afterIORead");
104512                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
104513             }
104514             catch (e) {
104515                 if (onError) {
104516                     onError(e.message);
104517                 }
104518                 text = "";
104519             }
104520             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
104521         }
104522         function directoryExists(directoryPath) {
104523             if (existingDirectories.has(directoryPath)) {
104524                 return true;
104525             }
104526             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
104527                 existingDirectories.set(directoryPath, true);
104528                 return true;
104529             }
104530             return false;
104531         }
104532         function writeFile(fileName, data, writeByteOrderMark, onError) {
104533             try {
104534                 ts.performance.mark("beforeIOWrite");
104535                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
104536                 // the system.writeFile will do its own directory creation and
104537                 // the ensureDirectoriesExist call will always be redundant.
104538                 ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); });
104539                 ts.performance.mark("afterIOWrite");
104540                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
104541             }
104542             catch (e) {
104543                 if (onError) {
104544                     onError(e.message);
104545                 }
104546             }
104547         }
104548         var outputFingerprints;
104549         function writeFileWorker(fileName, data, writeByteOrderMark) {
104550             if (!ts.isWatchSet(options) || !system.getModifiedTime) {
104551                 system.writeFile(fileName, data, writeByteOrderMark);
104552                 return;
104553             }
104554             if (!outputFingerprints) {
104555                 outputFingerprints = new ts.Map();
104556             }
104557             var hash = computeHash(data);
104558             var mtimeBefore = system.getModifiedTime(fileName);
104559             if (mtimeBefore) {
104560                 var fingerprint = outputFingerprints.get(fileName);
104561                 // If output has not been changed, and the file has no external modification
104562                 if (fingerprint &&
104563                     fingerprint.byteOrderMark === writeByteOrderMark &&
104564                     fingerprint.hash === hash &&
104565                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
104566                     return;
104567                 }
104568             }
104569             system.writeFile(fileName, data, writeByteOrderMark);
104570             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
104571             outputFingerprints.set(fileName, {
104572                 hash: hash,
104573                 byteOrderMark: writeByteOrderMark,
104574                 mtime: mtimeAfter
104575             });
104576         }
104577         function getDefaultLibLocation() {
104578             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
104579         }
104580         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
104581         var realpath = system.realpath && (function (path) { return system.realpath(path); });
104582         var compilerHost = {
104583             getSourceFile: getSourceFile,
104584             getDefaultLibLocation: getDefaultLibLocation,
104585             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
104586             writeFile: writeFile,
104587             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
104588             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
104589             getCanonicalFileName: getCanonicalFileName,
104590             getNewLine: function () { return newLine; },
104591             fileExists: function (fileName) { return system.fileExists(fileName); },
104592             readFile: function (fileName) { return system.readFile(fileName); },
104593             trace: function (s) { return system.write(s + newLine); },
104594             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
104595             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
104596             getDirectories: function (path) { return system.getDirectories(path); },
104597             realpath: realpath,
104598             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
104599             createDirectory: function (d) { return system.createDirectory(d); },
104600             createHash: ts.maybeBind(system, system.createHash)
104601         };
104602         return compilerHost;
104603     }
104604     ts.createCompilerHostWorker = createCompilerHostWorker;
104605     /*@internal*/
104606     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
104607         var originalReadFile = host.readFile;
104608         var originalFileExists = host.fileExists;
104609         var originalDirectoryExists = host.directoryExists;
104610         var originalCreateDirectory = host.createDirectory;
104611         var originalWriteFile = host.writeFile;
104612         var readFileCache = new ts.Map();
104613         var fileExistsCache = new ts.Map();
104614         var directoryExistsCache = new ts.Map();
104615         var sourceFileCache = new ts.Map();
104616         var readFileWithCache = function (fileName) {
104617             var key = toPath(fileName);
104618             var value = readFileCache.get(key);
104619             if (value !== undefined)
104620                 return value !== false ? value : undefined;
104621             return setReadFileCache(key, fileName);
104622         };
104623         var setReadFileCache = function (key, fileName) {
104624             var newValue = originalReadFile.call(host, fileName);
104625             readFileCache.set(key, newValue !== undefined ? newValue : false);
104626             return newValue;
104627         };
104628         host.readFile = function (fileName) {
104629             var key = toPath(fileName);
104630             var value = readFileCache.get(key);
104631             if (value !== undefined)
104632                 return value !== false ? value : undefined; // could be .d.ts from output
104633             // Cache json or buildInfo
104634             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
104635                 return originalReadFile.call(host, fileName);
104636             }
104637             return setReadFileCache(key, fileName);
104638         };
104639         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
104640             var key = toPath(fileName);
104641             var value = sourceFileCache.get(key);
104642             if (value)
104643                 return value;
104644             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
104645             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
104646                 sourceFileCache.set(key, sourceFile);
104647             }
104648             return sourceFile;
104649         } : undefined;
104650         // fileExists for any kind of extension
104651         host.fileExists = function (fileName) {
104652             var key = toPath(fileName);
104653             var value = fileExistsCache.get(key);
104654             if (value !== undefined)
104655                 return value;
104656             var newValue = originalFileExists.call(host, fileName);
104657             fileExistsCache.set(key, !!newValue);
104658             return newValue;
104659         };
104660         if (originalWriteFile) {
104661             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
104662                 var key = toPath(fileName);
104663                 fileExistsCache.delete(key);
104664                 var value = readFileCache.get(key);
104665                 if (value !== undefined && value !== data) {
104666                     readFileCache.delete(key);
104667                     sourceFileCache.delete(key);
104668                 }
104669                 else if (getSourceFileWithCache) {
104670                     var sourceFile = sourceFileCache.get(key);
104671                     if (sourceFile && sourceFile.text !== data) {
104672                         sourceFileCache.delete(key);
104673                     }
104674                 }
104675                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
104676             };
104677         }
104678         // directoryExists
104679         if (originalDirectoryExists && originalCreateDirectory) {
104680             host.directoryExists = function (directory) {
104681                 var key = toPath(directory);
104682                 var value = directoryExistsCache.get(key);
104683                 if (value !== undefined)
104684                     return value;
104685                 var newValue = originalDirectoryExists.call(host, directory);
104686                 directoryExistsCache.set(key, !!newValue);
104687                 return newValue;
104688             };
104689             host.createDirectory = function (directory) {
104690                 var key = toPath(directory);
104691                 directoryExistsCache.delete(key);
104692                 originalCreateDirectory.call(host, directory);
104693             };
104694         }
104695         return {
104696             originalReadFile: originalReadFile,
104697             originalFileExists: originalFileExists,
104698             originalDirectoryExists: originalDirectoryExists,
104699             originalCreateDirectory: originalCreateDirectory,
104700             originalWriteFile: originalWriteFile,
104701             getSourceFileWithCache: getSourceFileWithCache,
104702             readFileWithCache: readFileWithCache
104703         };
104704     }
104705     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
104706     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
104707         var diagnostics;
104708         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
104709         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
104710         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
104711         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
104712         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
104713         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
104714             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
104715         }
104716         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
104717     }
104718     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
104719     function formatDiagnostics(diagnostics, host) {
104720         var output = "";
104721         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
104722             var diagnostic = diagnostics_3[_i];
104723             output += formatDiagnostic(diagnostic, host);
104724         }
104725         return output;
104726     }
104727     ts.formatDiagnostics = formatDiagnostics;
104728     function formatDiagnostic(diagnostic, host) {
104729         var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
104730         if (diagnostic.file) {
104731             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
104732             var fileName = diagnostic.file.fileName;
104733             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
104734             return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
104735         }
104736         return errorMessage;
104737     }
104738     ts.formatDiagnostic = formatDiagnostic;
104739     /** @internal */
104740     var ForegroundColorEscapeSequences;
104741     (function (ForegroundColorEscapeSequences) {
104742         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
104743         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
104744         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
104745         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
104746         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
104747     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
104748     var gutterStyleSequence = "\u001b[7m";
104749     var gutterSeparator = " ";
104750     var resetEscapeSequence = "\u001b[0m";
104751     var ellipsis = "...";
104752     var halfIndent = "  ";
104753     var indent = "    ";
104754     function getCategoryFormat(category) {
104755         switch (category) {
104756             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
104757             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
104758             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
104759             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
104760         }
104761     }
104762     /** @internal */
104763     function formatColorAndReset(text, formatStyle) {
104764         return formatStyle + text + resetEscapeSequence;
104765     }
104766     ts.formatColorAndReset = formatColorAndReset;
104767     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
104768         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
104769         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
104770         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
104771         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
104772         var gutterWidth = (lastLine + 1 + "").length;
104773         if (hasMoreThanFiveLines) {
104774             gutterWidth = Math.max(ellipsis.length, gutterWidth);
104775         }
104776         var context = "";
104777         for (var i = firstLine; i <= lastLine; i++) {
104778             context += host.getNewLine();
104779             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
104780             // so we'll skip ahead to the second-to-last line.
104781             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
104782                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
104783                 i = lastLine - 1;
104784             }
104785             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
104786             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
104787             var lineContent = file.text.slice(lineStart, lineEnd);
104788             lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
104789             lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
104790             // Output the gutter and the actual contents of the line.
104791             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
104792             context += lineContent + host.getNewLine();
104793             // Output the gutter and the error span for the line using tildes.
104794             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
104795             context += squiggleColor;
104796             if (i === firstLine) {
104797                 // If we're on the last line, then limit it to the last character of the last line.
104798                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
104799                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
104800                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
104801                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
104802             }
104803             else if (i === lastLine) {
104804                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
104805             }
104806             else {
104807                 // Squiggle the entire line.
104808                 context += lineContent.replace(/./g, "~");
104809             }
104810             context += resetEscapeSequence;
104811         }
104812         return context;
104813     }
104814     /* @internal */
104815     function formatLocation(file, start, host, color) {
104816         if (color === void 0) { color = formatColorAndReset; }
104817         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
104818         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
104819         var output = "";
104820         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
104821         output += ":";
104822         output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
104823         output += ":";
104824         output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
104825         return output;
104826     }
104827     ts.formatLocation = formatLocation;
104828     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
104829         var output = "";
104830         for (var _i = 0, diagnostics_4 = diagnostics; _i < diagnostics_4.length; _i++) {
104831             var diagnostic = diagnostics_4[_i];
104832             if (diagnostic.file) {
104833                 var file = diagnostic.file, start = diagnostic.start;
104834                 output += formatLocation(file, start, host); // TODO: GH#18217
104835                 output += " - ";
104836             }
104837             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
104838             output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
104839             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
104840             if (diagnostic.file) {
104841                 output += host.getNewLine();
104842                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
104843                 if (diagnostic.relatedInformation) {
104844                     output += host.getNewLine();
104845                     for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
104846                         var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
104847                         if (file) {
104848                             output += host.getNewLine();
104849                             output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
104850                             output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
104851                         }
104852                         output += host.getNewLine();
104853                         output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
104854                     }
104855                 }
104856             }
104857             output += host.getNewLine();
104858         }
104859         return output;
104860     }
104861     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
104862     function flattenDiagnosticMessageText(diag, newLine, indent) {
104863         if (indent === void 0) { indent = 0; }
104864         if (ts.isString(diag)) {
104865             return diag;
104866         }
104867         else if (diag === undefined) {
104868             return "";
104869         }
104870         var result = "";
104871         if (indent) {
104872             result += newLine;
104873             for (var i = 0; i < indent; i++) {
104874                 result += "  ";
104875             }
104876         }
104877         result += diag.messageText;
104878         indent++;
104879         if (diag.next) {
104880             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
104881                 var kid = _a[_i];
104882                 result += flattenDiagnosticMessageText(kid, newLine, indent);
104883             }
104884         }
104885         return result;
104886     }
104887     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
104888     /* @internal */
104889     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
104890         if (names.length === 0) {
104891             return [];
104892         }
104893         var resolutions = [];
104894         var cache = new ts.Map();
104895         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
104896             var name = names_2[_i];
104897             var result = void 0;
104898             if (cache.has(name)) {
104899                 result = cache.get(name);
104900             }
104901             else {
104902                 cache.set(name, result = loader(name, containingFile, redirectedReference));
104903             }
104904             resolutions.push(result);
104905         }
104906         return resolutions;
104907     }
104908     ts.loadWithLocalCache = loadWithLocalCache;
104909     /* @internal */
104910     function forEachResolvedProjectReference(resolvedProjectReferences, cb) {
104911         return forEachProjectReference(/*projectReferences*/ undefined, resolvedProjectReferences, function (resolvedRef, parent) { return resolvedRef && cb(resolvedRef, parent); });
104912     }
104913     ts.forEachResolvedProjectReference = forEachResolvedProjectReference;
104914     function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
104915         var seenResolvedRefs;
104916         return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined);
104917         function worker(projectReferences, resolvedProjectReferences, parent) {
104918             // Visit project references first
104919             if (cbRef) {
104920                 var result = cbRef(projectReferences, parent);
104921                 if (result) {
104922                     return result;
104923                 }
104924             }
104925             return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
104926                 if (resolvedRef && (seenResolvedRefs === null || seenResolvedRefs === void 0 ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) {
104927                     // ignore recursives
104928                     return undefined;
104929                 }
104930                 var result = cbResolvedRef(resolvedRef, parent, index);
104931                 if (result || !resolvedRef)
104932                     return result;
104933                 (seenResolvedRefs || (seenResolvedRefs = new ts.Set())).add(resolvedRef.sourceFile.path);
104934                 return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef);
104935             });
104936         }
104937     }
104938     /* @internal */
104939     ts.inferredTypesContainingFile = "__inferred type names__.ts";
104940     /**
104941      * Determines if program structure is upto date or needs to be recreated
104942      */
104943     /* @internal */
104944     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
104945         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
104946         if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) {
104947             return false;
104948         }
104949         // If root file names don't match
104950         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
104951             return false;
104952         }
104953         var seenResolvedRefs;
104954         // If project references don't match
104955         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
104956             return false;
104957         }
104958         // If any file is not up-to-date, then the whole program is not up-to-date
104959         if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
104960             return false;
104961         }
104962         // If any of the missing file paths are now created
104963         if (program.getMissingFilePaths().some(fileExists)) {
104964             return false;
104965         }
104966         var currentOptions = program.getCompilerOptions();
104967         // If the compilation settings do no match, then the program is not up-to-date
104968         if (!ts.compareDataObjects(currentOptions, newOptions)) {
104969             return false;
104970         }
104971         // If everything matches but the text of config file is changed,
104972         // error locations can change for program options, so update the program
104973         if (currentOptions.configFile && newOptions.configFile) {
104974             return currentOptions.configFile.text === newOptions.configFile.text;
104975         }
104976         return true;
104977         function sourceFileNotUptoDate(sourceFile) {
104978             return !sourceFileVersionUptoDate(sourceFile) ||
104979                 hasInvalidatedResolution(sourceFile.path);
104980         }
104981         function sourceFileVersionUptoDate(sourceFile) {
104982             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
104983         }
104984         function projectReferenceUptoDate(oldRef, newRef, index) {
104985             if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
104986                 return false;
104987             }
104988             return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
104989         }
104990         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
104991             if (oldResolvedRef) {
104992                 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
104993                     // Assume true
104994                     return true;
104995                 }
104996                 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
104997                 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
104998                     return false;
104999                 }
105000                 // Add to seen before checking the referenced paths of this config file
105001                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
105002                 // If child project references are upto date, this project reference is uptodate
105003                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
105004                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
105005                 });
105006             }
105007             // In old program, not able to resolve project reference path,
105008             // so if config file doesnt exist, it is uptodate.
105009             return !fileExists(resolveProjectReferencePath(oldRef));
105010         }
105011     }
105012     ts.isProgramUptoDate = isProgramUptoDate;
105013     function getConfigFileParsingDiagnostics(configFileParseResult) {
105014         return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
105015             configFileParseResult.errors;
105016     }
105017     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
105018     /**
105019      * Determine if source file needs to be re-created even if its text hasn't changed
105020      */
105021     function shouldProgramCreateNewSourceFiles(program, newOptions) {
105022         if (!program)
105023             return false;
105024         // If any compiler options change, we can't reuse old source file even if version match
105025         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
105026         var oldOptions = program.getCompilerOptions();
105027         return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
105028             return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
105029         });
105030     }
105031     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
105032         return {
105033             rootNames: rootNames,
105034             options: options,
105035             host: host,
105036             oldProgram: oldProgram,
105037             configFileParsingDiagnostics: configFileParsingDiagnostics
105038         };
105039     }
105040     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
105041         var _a, _b;
105042         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
105043         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
105044         var oldProgram = createProgramOptions.oldProgram;
105045         var processingDefaultLibFiles;
105046         var processingOtherFiles;
105047         var files;
105048         var symlinks;
105049         var commonSourceDirectory;
105050         var diagnosticsProducingTypeChecker;
105051         var noDiagnosticsTypeChecker;
105052         var classifiableNames;
105053         var ambientModuleNameToUnmodifiedFileName = new ts.Map();
105054         // Todo:: Use this to report why file was included in --extendedDiagnostics
105055         var refFileMap;
105056         var cachedBindAndCheckDiagnosticsForFile = {};
105057         var cachedDeclarationDiagnosticsForFile = {};
105058         var resolvedTypeReferenceDirectives = new ts.Map();
105059         var fileProcessingDiagnostics = ts.createDiagnosticCollection();
105060         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
105061         // This works as imported modules are discovered recursively in a depth first manner, specifically:
105062         // - For each root file, findSourceFile is called.
105063         // - This calls processImportedModules for each module imported in the source file.
105064         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
105065         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
105066         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
105067         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
105068         var currentNodeModulesDepth = 0;
105069         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
105070         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
105071         var modulesWithElidedImports = new ts.Map();
105072         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
105073         var sourceFilesFoundSearchingNodeModules = new ts.Map();
105074         var tracingData = ["program" /* Program */, "createProgram"];
105075         ts.tracing.begin.apply(ts.tracing, tracingData);
105076         ts.performance.mark("beforeProgram");
105077         var host = createProgramOptions.host || createCompilerHost(options);
105078         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
105079         var skipDefaultLib = options.noLib;
105080         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
105081         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
105082         var programDiagnostics = ts.createDiagnosticCollection();
105083         var currentDirectory = host.getCurrentDirectory();
105084         var supportedExtensions = ts.getSupportedExtensions(options);
105085         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
105086         // Map storing if there is emit blocking diagnostics for given input
105087         var hasEmitBlockingDiagnostics = new ts.Map();
105088         var _compilerOptionsObjectLiteralSyntax;
105089         var moduleResolutionCache;
105090         var actualResolveModuleNamesWorker;
105091         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
105092         if (host.resolveModuleNames) {
105093             actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
105094                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
105095                 if (!resolved || resolved.extension !== undefined) {
105096                     return resolved;
105097                 }
105098                 var withExtension = ts.clone(resolved);
105099                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
105100                 return withExtension;
105101             }); };
105102         }
105103         else {
105104             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
105105             var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
105106             actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
105107         }
105108         var actualResolveTypeReferenceDirectiveNamesWorker;
105109         if (host.resolveTypeReferenceDirectives) {
105110             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
105111         }
105112         else {
105113             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
105114             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
105115         }
105116         // Map from a stringified PackageId to the source file with that id.
105117         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
105118         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
105119         var packageIdToSourceFile = new ts.Map();
105120         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
105121         var sourceFileToPackageName = new ts.Map();
105122         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
105123         var redirectTargetsMap = ts.createMultiMap();
105124         /**
105125          * map with
105126          * - SourceFile if present
105127          * - false if sourceFile missing for source of project reference redirect
105128          * - undefined otherwise
105129          */
105130         var filesByName = new ts.Map();
105131         var missingFilePaths;
105132         // stores 'filename -> file association' ignoring case
105133         // used to track cases when two file names differ only in casing
105134         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? new ts.Map() : undefined;
105135         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
105136         var resolvedProjectReferences;
105137         var projectReferenceRedirects;
105138         var mapFromFileToProjectReferenceRedirects;
105139         var mapFromToProjectReferenceRedirectSource;
105140         var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
105141             !options.disableSourceOfProjectReferenceRedirect;
105142         var _c = updateHostForUseSourceOfProjectReferenceRedirect({
105143             compilerHost: host,
105144             getSymlinkCache: getSymlinkCache,
105145             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
105146             toPath: toPath,
105147             getResolvedProjectReferences: getResolvedProjectReferences,
105148             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
105149             forEachResolvedProjectReference: forEachResolvedProjectReference
105150         }), onProgramCreateComplete = _c.onProgramCreateComplete, fileExists = _c.fileExists, directoryExists = _c.directoryExists;
105151         ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
105152         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
105153         ts.tracing.pop();
105154         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
105155         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
105156         var structureIsReused;
105157         ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {});
105158         structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
105159         ts.tracing.pop();
105160         if (structureIsReused !== 2 /* Completely */) {
105161             processingDefaultLibFiles = [];
105162             processingOtherFiles = [];
105163             if (projectReferences) {
105164                 if (!resolvedProjectReferences) {
105165                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
105166                 }
105167                 if (rootNames.length) {
105168                     for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
105169                         var parsedRef = resolvedProjectReferences_1[_i];
105170                         if (!parsedRef)
105171                             continue;
105172                         var out = ts.outFile(parsedRef.commandLine.options);
105173                         if (useSourceOfProjectReferenceRedirect) {
105174                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
105175                                 for (var _d = 0, _e = parsedRef.commandLine.fileNames; _d < _e.length; _d++) {
105176                                     var fileName = _e[_d];
105177                                     processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
105178                                 }
105179                             }
105180                         }
105181                         else {
105182                             if (out) {
105183                                 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
105184                             }
105185                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
105186                                 for (var _f = 0, _g = parsedRef.commandLine.fileNames; _f < _g.length; _f++) {
105187                                     var fileName = _g[_f];
105188                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
105189                                         processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
105190                                     }
105191                                 }
105192                             }
105193                         }
105194                     }
105195                 }
105196             }
105197             ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length });
105198             ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
105199             ts.tracing.pop();
105200             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
105201             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
105202             if (typeReferences.length) {
105203                 ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length });
105204                 // This containingFilename needs to match with the one used in managed-side
105205                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
105206                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
105207                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
105208                 for (var i = 0; i < typeReferences.length; i++) {
105209                     processTypeReferenceDirective(typeReferences[i], resolutions[i]);
105210                 }
105211                 ts.tracing.pop();
105212             }
105213             // Do not process the default library if:
105214             //  - The '--noLib' flag is used.
105215             //  - A 'no-default-lib' reference comment is encountered in
105216             //      processing the root files.
105217             if (rootNames.length && !skipDefaultLib) {
105218                 // If '--lib' is not specified, include default library file according to '--target'
105219                 // otherwise, using options specified in '--lib' instead of '--target' default library file
105220                 var defaultLibraryFileName = getDefaultLibraryFileName();
105221                 if (!options.lib && defaultLibraryFileName) {
105222                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
105223                 }
105224                 else {
105225                     ts.forEach(options.lib, function (libFileName) {
105226                         processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
105227                     });
105228                 }
105229             }
105230             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
105231                 var path = _a[0], file = _a[1];
105232                 return file === undefined ? path : undefined;
105233             }));
105234             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
105235             processingDefaultLibFiles = undefined;
105236             processingOtherFiles = undefined;
105237         }
105238         ts.Debug.assert(!!missingFilePaths);
105239         // Release any files we have acquired in the old program but are
105240         // not part of the new program.
105241         if (oldProgram && host.onReleaseOldSourceFile) {
105242             var oldSourceFiles = oldProgram.getSourceFiles();
105243             for (var _h = 0, oldSourceFiles_1 = oldSourceFiles; _h < oldSourceFiles_1.length; _h++) {
105244                 var oldSourceFile = oldSourceFiles_1[_h];
105245                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
105246                 if (shouldCreateNewSourceFile || !newFile ||
105247                     // old file wasnt redirect but new file is
105248                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
105249                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
105250                 }
105251             }
105252             oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) {
105253                 if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) {
105254                     host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
105255                 }
105256             });
105257         }
105258         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
105259         oldProgram = undefined;
105260         var program = {
105261             getRootFileNames: function () { return rootNames; },
105262             getSourceFile: getSourceFile,
105263             getSourceFileByPath: getSourceFileByPath,
105264             getSourceFiles: function () { return files; },
105265             getMissingFilePaths: function () { return missingFilePaths; },
105266             getRefFileMap: function () { return refFileMap; },
105267             getFilesByNameMap: function () { return filesByName; },
105268             getCompilerOptions: function () { return options; },
105269             getSyntacticDiagnostics: getSyntacticDiagnostics,
105270             getOptionsDiagnostics: getOptionsDiagnostics,
105271             getGlobalDiagnostics: getGlobalDiagnostics,
105272             getSemanticDiagnostics: getSemanticDiagnostics,
105273             getCachedSemanticDiagnostics: getCachedSemanticDiagnostics,
105274             getSuggestionDiagnostics: getSuggestionDiagnostics,
105275             getDeclarationDiagnostics: getDeclarationDiagnostics,
105276             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
105277             getProgramDiagnostics: getProgramDiagnostics,
105278             getTypeChecker: getTypeChecker,
105279             getClassifiableNames: getClassifiableNames,
105280             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
105281             getCommonSourceDirectory: getCommonSourceDirectory,
105282             emit: emit,
105283             getCurrentDirectory: function () { return currentDirectory; },
105284             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
105285             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
105286             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
105287             getTypeCatalog: function () { return getDiagnosticsProducingTypeChecker().getTypeCatalog(); },
105288             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
105289             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
105290             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
105291             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
105292             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
105293             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
105294             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
105295             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
105296             getSourceFileFromReference: getSourceFileFromReference,
105297             getLibFileFromReference: getLibFileFromReference,
105298             sourceFileToPackageName: sourceFileToPackageName,
105299             redirectTargetsMap: redirectTargetsMap,
105300             isEmittedFile: isEmittedFile,
105301             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
105302             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
105303             getProjectReferences: getProjectReferences,
105304             getResolvedProjectReferences: getResolvedProjectReferences,
105305             getProjectReferenceRedirect: getProjectReferenceRedirect,
105306             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
105307             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
105308             forEachResolvedProjectReference: forEachResolvedProjectReference,
105309             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
105310             emitBuildInfo: emitBuildInfo,
105311             fileExists: fileExists,
105312             directoryExists: directoryExists,
105313             getSymlinkCache: getSymlinkCache,
105314             realpath: (_b = host.realpath) === null || _b === void 0 ? void 0 : _b.bind(host),
105315             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
105316             structureIsReused: structureIsReused,
105317         };
105318         onProgramCreateComplete();
105319         verifyCompilerOptions();
105320         ts.performance.mark("afterProgram");
105321         ts.performance.measure("Program", "beforeProgram", "afterProgram");
105322         ts.tracing.end.apply(ts.tracing, tracingData);
105323         return program;
105324         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) {
105325             if (!moduleNames.length)
105326                 return ts.emptyArray;
105327             var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory);
105328             var redirectedReference = getRedirectReferenceForResolution(containingFile);
105329             ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName });
105330             ts.performance.mark("beforeResolveModule");
105331             var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference);
105332             ts.performance.mark("afterResolveModule");
105333             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
105334             ts.tracing.pop();
105335             return result;
105336         }
105337         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) {
105338             if (!typeDirectiveNames.length)
105339                 return [];
105340             var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile;
105341             var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined;
105342             ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName });
105343             ts.performance.mark("beforeResolveTypeReference");
105344             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference);
105345             ts.performance.mark("afterResolveTypeReference");
105346             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
105347             ts.tracing.pop();
105348             return result;
105349         }
105350         function getRedirectReferenceForResolution(file) {
105351             var redirect = getResolvedProjectReferenceToRedirect(file.originalFileName);
105352             if (redirect || !ts.fileExtensionIs(file.originalFileName, ".d.ts" /* Dts */))
105353                 return redirect;
105354             // The originalFileName could not be actual source file name if file found was d.ts from referecned project
105355             // So in this case try to look up if this is output from referenced project, if it is use the redirected project in that case
105356             var resultFromDts = getRedirectReferenceForResolutionFromSourceOfProject(file.originalFileName, file.path);
105357             if (resultFromDts)
105358                 return resultFromDts;
105359             // If preserveSymlinks is true, module resolution wont jump the symlink
105360             // but the resolved real path may be the .d.ts from project reference
105361             // Note:: Currently we try the real path only if the
105362             // file is from node_modules to avoid having to run real path on all file paths
105363             if (!host.realpath || !options.preserveSymlinks || !ts.stringContains(file.originalFileName, ts.nodeModulesPathPart))
105364                 return undefined;
105365             var realDeclarationFileName = host.realpath(file.originalFileName);
105366             var realDeclarationPath = toPath(realDeclarationFileName);
105367             return realDeclarationPath === file.path ? undefined : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationFileName, realDeclarationPath);
105368         }
105369         function getRedirectReferenceForResolutionFromSourceOfProject(fileName, filePath) {
105370             var source = getSourceOfProjectReferenceRedirect(fileName);
105371             if (ts.isString(source))
105372                 return getResolvedProjectReferenceToRedirect(source);
105373             if (!source)
105374                 return undefined;
105375             // Output of .d.ts file so return resolved ref that matches the out file name
105376             return forEachResolvedProjectReference(function (resolvedRef) {
105377                 var out = ts.outFile(resolvedRef.commandLine.options);
105378                 if (!out)
105379                     return undefined;
105380                 return toPath(out) === filePath ? resolvedRef : undefined;
105381             });
105382         }
105383         function compareDefaultLibFiles(a, b) {
105384             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
105385         }
105386         function getDefaultLibFilePriority(a) {
105387             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
105388                 var basename = ts.getBaseFileName(a.fileName);
105389                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
105390                     return 0;
105391                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
105392                 var index = ts.libs.indexOf(name);
105393                 if (index !== -1)
105394                     return index + 1;
105395             }
105396             return ts.libs.length + 2;
105397         }
105398         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
105399             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
105400         }
105401         function toPath(fileName) {
105402             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
105403         }
105404         function getCommonSourceDirectory() {
105405             if (commonSourceDirectory === undefined) {
105406                 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
105407                 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
105408                     // If a rootDir is specified use it as the commonSourceDirectory
105409                     commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
105410                 }
105411                 else if (options.composite && options.configFilePath) {
105412                     // Project compilations never infer their root from the input source paths
105413                     commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
105414                     checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
105415                 }
105416                 else {
105417                     commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
105418                 }
105419                 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
105420                     // Make sure directory path ends with directory separator so this string can directly
105421                     // used to replace with "" to get the relative path of the source file and the relative path doesn't
105422                     // start with / making it rooted path
105423                     commonSourceDirectory += ts.directorySeparator;
105424                 }
105425             }
105426             return commonSourceDirectory;
105427         }
105428         function getClassifiableNames() {
105429             var _a;
105430             if (!classifiableNames) {
105431                 // Initialize a checker so that all our files are bound.
105432                 getTypeChecker();
105433                 classifiableNames = new ts.Set();
105434                 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
105435                     var sourceFile = files_2[_i];
105436                     (_a = sourceFile.classifiableNames) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return classifiableNames.add(value); });
105437                 }
105438             }
105439             return classifiableNames;
105440         }
105441         function resolveModuleNamesReusingOldState(moduleNames, file) {
105442             if (structureIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
105443                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
105444                 // the best we can do is fallback to the default logic.
105445                 return resolveModuleNamesWorker(moduleNames, file, /*reusedNames*/ undefined);
105446             }
105447             var oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName);
105448             if (oldSourceFile !== file && file.resolvedModules) {
105449                 // `file` was created for the new program.
105450                 //
105451                 // We only set `file.resolvedModules` via work from the current function,
105452                 // so it is defined iff we already called the current function on `file`.
105453                 // That call happened no later than the creation of the `file` object,
105454                 // which per above occurred during the current program creation.
105455                 // Since we assume the filesystem does not change during program creation,
105456                 // it is safe to reuse resolutions from the earlier call.
105457                 var result_14 = [];
105458                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
105459                     var moduleName = moduleNames_1[_i];
105460                     var resolvedModule = file.resolvedModules.get(moduleName);
105461                     result_14.push(resolvedModule);
105462                 }
105463                 return result_14;
105464             }
105465             // At this point, we know at least one of the following hold:
105466             // - file has local declarations for ambient modules
105467             // - old program state is available
105468             // With this information, we can infer some module resolutions without performing resolution.
105469             /** An ordered list of module names for which we cannot recover the resolution. */
105470             var unknownModuleNames;
105471             /**
105472              * The indexing of elements in this list matches that of `moduleNames`.
105473              *
105474              * Before combining results, result[i] is in one of the following states:
105475              * * undefined: needs to be recomputed,
105476              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
105477              * Needs to be reset to undefined before returning,
105478              * * ResolvedModuleFull instance: can be reused.
105479              */
105480             var result;
105481             var reusedNames;
105482             /** A transient placeholder used to mark predicted resolution in the result list. */
105483             var predictedToResolveToAmbientModuleMarker = {};
105484             for (var i = 0; i < moduleNames.length; i++) {
105485                 var moduleName = moduleNames[i];
105486                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
105487                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
105488                     var oldResolvedModule = ts.getResolvedModule(oldSourceFile, moduleName);
105489                     if (oldResolvedModule) {
105490                         if (ts.isTraceEnabled(options, host)) {
105491                             ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory));
105492                         }
105493                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
105494                         (reusedNames || (reusedNames = [])).push(moduleName);
105495                         continue;
105496                     }
105497                 }
105498                 // We know moduleName resolves to an ambient module provided that moduleName:
105499                 // - is in the list of ambient modules locally declared in the current source file.
105500                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
105501                 //   (so the same module declaration will land in the new program)
105502                 var resolvesToAmbientModuleInNonModifiedFile = false;
105503                 if (ts.contains(file.ambientModuleNames, moduleName)) {
105504                     resolvesToAmbientModuleInNonModifiedFile = true;
105505                     if (ts.isTraceEnabled(options, host)) {
105506                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory));
105507                     }
105508                 }
105509                 else {
105510                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
105511                 }
105512                 if (resolvesToAmbientModuleInNonModifiedFile) {
105513                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
105514                 }
105515                 else {
105516                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
105517                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
105518                 }
105519             }
105520             var resolutions = unknownModuleNames && unknownModuleNames.length
105521                 ? resolveModuleNamesWorker(unknownModuleNames, file, reusedNames)
105522                 : ts.emptyArray;
105523             // Combine results of resolutions and predicted results
105524             if (!result) {
105525                 // There were no unresolved/ambient resolutions.
105526                 ts.Debug.assert(resolutions.length === moduleNames.length);
105527                 return resolutions;
105528             }
105529             var j = 0;
105530             for (var i = 0; i < result.length; i++) {
105531                 if (result[i]) {
105532                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
105533                     // If it is the former, we can leave it as is.
105534                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
105535                         result[i] = undefined; // TODO: GH#18217
105536                     }
105537                 }
105538                 else {
105539                     result[i] = resolutions[j];
105540                     j++;
105541                 }
105542             }
105543             ts.Debug.assert(j === resolutions.length);
105544             return result;
105545             // If we change our policy of rechecking failed lookups on each program create,
105546             // we should adjust the value returned here.
105547             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
105548                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
105549                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
105550                 if (resolutionToFile && resolvedFile) {
105551                     // In the old program, we resolved to an ambient module that was in the same
105552                     //   place as we expected to find an actual module file.
105553                     // We actually need to return 'false' here even though this seems like a 'true' case
105554                     //   because the normal module resolution algorithm will find this anyway.
105555                     return false;
105556                 }
105557                 // at least one of declarations should come from non-modified source file
105558                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
105559                 if (!unmodifiedFile) {
105560                     return false;
105561                 }
105562                 if (ts.isTraceEnabled(options, host)) {
105563                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
105564                 }
105565                 return true;
105566             }
105567         }
105568         function canReuseProjectReferences() {
105569             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) {
105570                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
105571                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
105572                 if (oldResolvedRef) {
105573                     // Resolved project reference has gone missing or changed
105574                     return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
105575                 }
105576                 else {
105577                     // A previously-unresolved reference may be resolved now
105578                     return newResolvedRef !== undefined;
105579                 }
105580             }, function (oldProjectReferences, parent) {
105581                 // If array of references is changed, we cant resue old program
105582                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
105583                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
105584             });
105585         }
105586         function tryReuseStructureFromOldProgram() {
105587             var _a;
105588             if (!oldProgram) {
105589                 return 0 /* Not */;
105590             }
105591             // check properties that can affect structure of the program or module resolution strategy
105592             // if any of these properties has changed - structure cannot be reused
105593             var oldOptions = oldProgram.getCompilerOptions();
105594             if (ts.changesAffectModuleResolution(oldOptions, options)) {
105595                 return 0 /* Not */;
105596             }
105597             // there is an old program, check if we can reuse its structure
105598             var oldRootNames = oldProgram.getRootFileNames();
105599             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
105600                 return 0 /* Not */;
105601             }
105602             if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
105603                 return 0 /* Not */;
105604             }
105605             // Check if any referenced project tsconfig files are different
105606             if (!canReuseProjectReferences()) {
105607                 return 0 /* Not */;
105608             }
105609             if (projectReferences) {
105610                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
105611             }
105612             // check if program source files has changed in the way that can affect structure of the program
105613             var newSourceFiles = [];
105614             var modifiedSourceFiles = [];
105615             structureIsReused = 2 /* Completely */;
105616             // If the missing file paths are now present, it can change the progam structure,
105617             // and hence cant reuse the structure.
105618             // This is same as how we dont reuse the structure if one of the file from old program is now missing
105619             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
105620                 return 0 /* Not */;
105621             }
105622             var oldSourceFiles = oldProgram.getSourceFiles();
105623             var SeenPackageName;
105624             (function (SeenPackageName) {
105625                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
105626                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
105627             })(SeenPackageName || (SeenPackageName = {}));
105628             var seenPackageNames = new ts.Map();
105629             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
105630                 var oldSourceFile = oldSourceFiles_2[_i];
105631                 var newSourceFile = host.getSourceFileByPath
105632                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
105633                     : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
105634                 if (!newSourceFile) {
105635                     return 0 /* Not */;
105636                 }
105637                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
105638                 var fileChanged = void 0;
105639                 if (oldSourceFile.redirectInfo) {
105640                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
105641                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
105642                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
105643                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
105644                         return 0 /* Not */;
105645                     }
105646                     fileChanged = false;
105647                     newSourceFile = oldSourceFile; // Use the redirect.
105648                 }
105649                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
105650                     // If a redirected-to source file changes, the redirect may be broken.
105651                     if (newSourceFile !== oldSourceFile) {
105652                         return 0 /* Not */;
105653                     }
105654                     fileChanged = false;
105655                 }
105656                 else {
105657                     fileChanged = newSourceFile !== oldSourceFile;
105658                 }
105659                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
105660                 newSourceFile.path = oldSourceFile.path;
105661                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
105662                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
105663                 newSourceFile.fileName = oldSourceFile.fileName;
105664                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
105665                 if (packageName !== undefined) {
105666                     // If there are 2 different source files for the same package name and at least one of them changes,
105667                     // they might become redirects. So we must rebuild the program.
105668                     var prevKind = seenPackageNames.get(packageName);
105669                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
105670                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
105671                         return 0 /* Not */;
105672                     }
105673                     seenPackageNames.set(packageName, newKind);
105674                 }
105675                 if (fileChanged) {
105676                     // The `newSourceFile` object was created for the new program.
105677                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
105678                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
105679                         return 0 /* Not */;
105680                     }
105681                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
105682                         // value of no-default-lib has changed
105683                         // this will affect if default library is injected into the list of files
105684                         structureIsReused = 1 /* SafeModules */;
105685                     }
105686                     // check tripleslash references
105687                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
105688                         // tripleslash references has changed
105689                         structureIsReused = 1 /* SafeModules */;
105690                     }
105691                     // check imports and module augmentations
105692                     collectExternalModuleReferences(newSourceFile);
105693                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
105694                         // imports has changed
105695                         structureIsReused = 1 /* SafeModules */;
105696                     }
105697                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
105698                         // moduleAugmentations has changed
105699                         structureIsReused = 1 /* SafeModules */;
105700                     }
105701                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
105702                         // dynamicImport has changed
105703                         structureIsReused = 1 /* SafeModules */;
105704                     }
105705                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
105706                         // 'types' references has changed
105707                         structureIsReused = 1 /* SafeModules */;
105708                     }
105709                     // tentatively approve the file
105710                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
105711                 }
105712                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
105713                     // 'module/types' references could have changed
105714                     structureIsReused = 1 /* SafeModules */;
105715                     // add file to the modified list so that we will resolve it later
105716                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
105717                 }
105718                 // if file has passed all checks it should be safe to reuse it
105719                 newSourceFiles.push(newSourceFile);
105720             }
105721             if (structureIsReused !== 2 /* Completely */) {
105722                 return structureIsReused;
105723             }
105724             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
105725             for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) {
105726                 var oldFile = oldSourceFiles_3[_b];
105727                 if (!ts.contains(modifiedFiles, oldFile)) {
105728                     for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) {
105729                         var moduleName = _d[_c];
105730                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
105731                     }
105732                 }
105733             }
105734             // try to verify results of module resolution
105735             for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) {
105736                 var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile;
105737                 var moduleNames = getModuleNames(newSourceFile);
105738                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile);
105739                 // ensure that module resolution results are still correct
105740                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
105741                 if (resolutionsChanged) {
105742                     structureIsReused = 1 /* SafeModules */;
105743                     newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
105744                 }
105745                 else {
105746                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
105747                 }
105748                 // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
105749                 var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
105750                 var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile);
105751                 // ensure that types resolutions are still correct
105752                 var typeReferenceEesolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
105753                 if (typeReferenceEesolutionsChanged) {
105754                     structureIsReused = 1 /* SafeModules */;
105755                     newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, typeReferenceResolutions);
105756                 }
105757                 else {
105758                     newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
105759                 }
105760             }
105761             if (structureIsReused !== 2 /* Completely */) {
105762                 return structureIsReused;
105763             }
105764             if ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host)) {
105765                 return 1 /* SafeModules */;
105766             }
105767             missingFilePaths = oldProgram.getMissingFilePaths();
105768             refFileMap = oldProgram.getRefFileMap();
105769             // update fileName -> file mapping
105770             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
105771             for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) {
105772                 var newSourceFile = newSourceFiles_1[_g];
105773                 filesByName.set(newSourceFile.path, newSourceFile);
105774             }
105775             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
105776             oldFilesByNameMap.forEach(function (oldFile, path) {
105777                 if (!oldFile) {
105778                     filesByName.set(path, oldFile);
105779                     return;
105780                 }
105781                 if (oldFile.path === path) {
105782                     // Set the file as found during node modules search if it was found that way in old progra,
105783                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
105784                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
105785                     }
105786                     return;
105787                 }
105788                 filesByName.set(path, filesByName.get(oldFile.path));
105789             });
105790             files = newSourceFiles;
105791             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
105792             for (var _h = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _h < modifiedSourceFiles_2.length; _h++) {
105793                 var modifiedFile = modifiedSourceFiles_2[_h];
105794                 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
105795             }
105796             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
105797             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
105798             redirectTargetsMap = oldProgram.redirectTargetsMap;
105799             return 2 /* Completely */;
105800         }
105801         function getEmitHost(writeFileCallback) {
105802             return {
105803                 getPrependNodes: getPrependNodes,
105804                 getCanonicalFileName: getCanonicalFileName,
105805                 getCommonSourceDirectory: program.getCommonSourceDirectory,
105806                 getCompilerOptions: program.getCompilerOptions,
105807                 getCurrentDirectory: function () { return currentDirectory; },
105808                 getNewLine: function () { return host.getNewLine(); },
105809                 getSourceFile: program.getSourceFile,
105810                 getSourceFileByPath: program.getSourceFileByPath,
105811                 getSourceFiles: program.getSourceFiles,
105812                 getLibFileFromReference: program.getLibFileFromReference,
105813                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
105814                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
105815                 getProjectReferenceRedirect: getProjectReferenceRedirect,
105816                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
105817                 getSymlinkCache: getSymlinkCache,
105818                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
105819                 isEmitBlocked: isEmitBlocked,
105820                 readFile: function (f) { return host.readFile(f); },
105821                 fileExists: function (f) {
105822                     // Use local caches
105823                     var path = toPath(f);
105824                     if (getSourceFileByPath(path))
105825                         return true;
105826                     if (ts.contains(missingFilePaths, path))
105827                         return false;
105828                     // Before falling back to the host
105829                     return host.fileExists(f);
105830                 },
105831                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
105832                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
105833                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
105834                 redirectTargetsMap: redirectTargetsMap,
105835             };
105836         }
105837         function emitBuildInfo(writeFileCallback) {
105838             ts.Debug.assert(!ts.outFile(options));
105839             var tracingData = ["emit" /* Emit */, "emitBuildInfo"];
105840             ts.tracing.begin.apply(ts.tracing, tracingData);
105841             ts.performance.mark("beforeEmit");
105842             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
105843             /*targetSourceFile*/ undefined, 
105844             /*transformers*/ ts.noTransformers, 
105845             /*emitOnlyDtsFiles*/ false, 
105846             /*onlyBuildInfo*/ true);
105847             ts.performance.mark("afterEmit");
105848             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
105849             ts.tracing.end.apply(ts.tracing, tracingData);
105850             return emitResult;
105851         }
105852         function getResolvedProjectReferences() {
105853             return resolvedProjectReferences;
105854         }
105855         function getProjectReferences() {
105856             return projectReferences;
105857         }
105858         function getPrependNodes() {
105859             return createPrependNodes(projectReferences, function (_ref, index) { var _a; return (_a = resolvedProjectReferences[index]) === null || _a === void 0 ? void 0 : _a.commandLine; }, function (fileName) {
105860                 var path = toPath(fileName);
105861                 var sourceFile = getSourceFileByPath(path);
105862                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
105863             });
105864         }
105865         function isSourceFileFromExternalLibrary(file) {
105866             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
105867         }
105868         function isSourceFileDefaultLibrary(file) {
105869             if (file.hasNoDefaultLib) {
105870                 return true;
105871             }
105872             if (!options.noLib) {
105873                 return false;
105874             }
105875             // If '--lib' is not specified, include default library file according to '--target'
105876             // otherwise, using options specified in '--lib' instead of '--target' default library file
105877             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
105878             if (!options.lib) {
105879                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
105880             }
105881             else {
105882                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
105883             }
105884         }
105885         function getDiagnosticsProducingTypeChecker() {
105886             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
105887         }
105888         function dropDiagnosticsProducingTypeChecker() {
105889             diagnosticsProducingTypeChecker = undefined;
105890         }
105891         function getTypeChecker() {
105892             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
105893         }
105894         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
105895             var tracingData = ["emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }];
105896             ts.tracing.begin.apply(ts.tracing, tracingData);
105897             var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
105898             ts.tracing.end.apply(ts.tracing, tracingData);
105899             return result;
105900         }
105901         function isEmitBlocked(emitFileName) {
105902             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
105903         }
105904         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
105905             if (!forceDtsEmit) {
105906                 var result = handleNoEmitOptions(program, sourceFile, writeFileCallback, cancellationToken);
105907                 if (result)
105908                     return result;
105909             }
105910             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
105911             // any cost associated with it (like type checking) are appropriate associated with
105912             // the type-checking counter.
105913             //
105914             // If the -out option is specified, we should not pass the source file to getEmitResolver.
105915             // This is because in the -out scenario all files need to be emitted, and therefore all
105916             // files need to be type checked. And the way to specify that all files need to be type
105917             // checked is to not pass the file to getEmitResolver.
105918             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver(ts.outFile(options) ? undefined : sourceFile, cancellationToken);
105919             ts.performance.mark("beforeEmit");
105920             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
105921             /*onlyBuildInfo*/ false, forceDtsEmit);
105922             ts.performance.mark("afterEmit");
105923             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
105924             return emitResult;
105925         }
105926         function getSourceFile(fileName) {
105927             return getSourceFileByPath(toPath(fileName));
105928         }
105929         function getSourceFileByPath(path) {
105930             return filesByName.get(path) || undefined;
105931         }
105932         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
105933             if (sourceFile) {
105934                 return getDiagnostics(sourceFile, cancellationToken);
105935             }
105936             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
105937                 if (cancellationToken) {
105938                     cancellationToken.throwIfCancellationRequested();
105939                 }
105940                 return getDiagnostics(sourceFile, cancellationToken);
105941             }));
105942         }
105943         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
105944             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
105945         }
105946         function getSemanticDiagnostics(sourceFile, cancellationToken) {
105947             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
105948         }
105949         function getCachedSemanticDiagnostics(sourceFile) {
105950             var _a;
105951             return sourceFile
105952                 ? (_a = cachedBindAndCheckDiagnosticsForFile.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics;
105953         }
105954         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
105955             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
105956         }
105957         function getProgramDiagnostics(sourceFile) {
105958             if (ts.skipTypeChecking(sourceFile, options, program)) {
105959                 return ts.emptyArray;
105960             }
105961             var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
105962             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
105963             return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
105964         }
105965         function getMergedProgramDiagnostics(sourceFile) {
105966             var _a;
105967             var allDiagnostics = [];
105968             for (var _i = 1; _i < arguments.length; _i++) {
105969                 allDiagnostics[_i - 1] = arguments[_i];
105970             }
105971             var flatDiagnostics = ts.flatten(allDiagnostics);
105972             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
105973                 return flatDiagnostics;
105974             }
105975             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
105976         }
105977         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
105978             var options = program.getCompilerOptions();
105979             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
105980             if (!sourceFile || ts.outFile(options)) {
105981                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
105982             }
105983             else {
105984                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
105985             }
105986         }
105987         function getSyntacticDiagnosticsForFile(sourceFile) {
105988             // For JavaScript files, we report semantic errors for using TypeScript-only
105989             // constructs from within a JavaScript file as syntactic errors.
105990             if (ts.isSourceFileJS(sourceFile)) {
105991                 if (!sourceFile.additionalSyntacticDiagnostics) {
105992                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
105993                 }
105994                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
105995             }
105996             return sourceFile.parseDiagnostics;
105997         }
105998         function runWithCancellationToken(func) {
105999             try {
106000                 return func();
106001             }
106002             catch (e) {
106003                 if (e instanceof ts.OperationCanceledException) {
106004                     // We were canceled while performing the operation.  Because our type checker
106005                     // might be a bad state, we need to throw it away.
106006                     //
106007                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
106008                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
106009                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
106010                     // cancel when the user has made a change anyways.  And, in that case, we (the
106011                     // program instance) will get thrown away anyways.  So trying to keep one of
106012                     // these type checkers alive doesn't serve much purpose.
106013                     noDiagnosticsTypeChecker = undefined;
106014                     diagnosticsProducingTypeChecker = undefined;
106015                 }
106016                 throw e;
106017             }
106018         }
106019         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
106020             return ts.concatenate(filterSemanticDiagnotics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options), getProgramDiagnostics(sourceFile));
106021         }
106022         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
106023             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
106024         }
106025         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
106026             return runWithCancellationToken(function () {
106027                 if (ts.skipTypeChecking(sourceFile, options, program)) {
106028                     return ts.emptyArray;
106029                 }
106030                 var typeChecker = getDiagnosticsProducingTypeChecker();
106031                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
106032                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
106033                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
106034                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
106035                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
106036                     sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
106037                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
106038                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
106039                 return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
106040             });
106041         }
106042         function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics) {
106043             var _a;
106044             var allDiagnostics = [];
106045             for (var _i = 2; _i < arguments.length; _i++) {
106046                 allDiagnostics[_i - 2] = arguments[_i];
106047             }
106048             var flatDiagnostics = ts.flatten(allDiagnostics);
106049             if (!includeBindAndCheckDiagnostics || !((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
106050                 return flatDiagnostics;
106051             }
106052             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
106053             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
106054                 var errorExpectation = _d[_c];
106055                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
106056             }
106057             return diagnostics;
106058         }
106059         /**
106060          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
106061          * Comments that match to any of those diagnostics are marked as used.
106062          */
106063         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
106064             // Diagnostics are only reported if there is no comment directive preceding them
106065             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
106066             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
106067             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
106068             return { diagnostics: diagnostics, directives: directives };
106069         }
106070         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
106071             return runWithCancellationToken(function () {
106072                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
106073             });
106074         }
106075         /**
106076          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
106077          */
106078         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
106079             var file = diagnostic.file, start = diagnostic.start;
106080             if (!file) {
106081                 return -1;
106082             }
106083             // Start out with the line just before the text
106084             var lineStarts = ts.getLineStarts(file);
106085             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
106086             while (line >= 0) {
106087                 // As soon as that line is known to have a comment directive, use that
106088                 if (directives.markUsed(line)) {
106089                     return line;
106090                 }
106091                 // Stop searching if the line is not empty and not a comment
106092                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
106093                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
106094                     return -1;
106095                 }
106096                 line--;
106097             }
106098             return -1;
106099         }
106100         function getJSSyntacticDiagnosticsForFile(sourceFile) {
106101             return runWithCancellationToken(function () {
106102                 var diagnostics = [];
106103                 walk(sourceFile, sourceFile);
106104                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
106105                 return diagnostics;
106106                 function walk(node, parent) {
106107                     // Return directly from the case if the given node doesnt want to visit each child
106108                     // Otherwise break to visit each child
106109                     switch (parent.kind) {
106110                         case 160 /* Parameter */:
106111                         case 163 /* PropertyDeclaration */:
106112                         case 165 /* MethodDeclaration */:
106113                             if (parent.questionToken === node) {
106114                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
106115                                 return "skip";
106116                             }
106117                         // falls through
106118                         case 164 /* MethodSignature */:
106119                         case 166 /* Constructor */:
106120                         case 167 /* GetAccessor */:
106121                         case 168 /* SetAccessor */:
106122                         case 208 /* FunctionExpression */:
106123                         case 251 /* FunctionDeclaration */:
106124                         case 209 /* ArrowFunction */:
106125                         case 249 /* VariableDeclaration */:
106126                             // type annotation
106127                             if (parent.type === node) {
106128                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
106129                                 return "skip";
106130                             }
106131                     }
106132                     switch (node.kind) {
106133                         case 262 /* ImportClause */:
106134                             if (node.isTypeOnly) {
106135                                 diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
106136                                 return "skip";
106137                             }
106138                             break;
106139                         case 267 /* ExportDeclaration */:
106140                             if (node.isTypeOnly) {
106141                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
106142                                 return "skip";
106143                             }
106144                             break;
106145                         case 260 /* ImportEqualsDeclaration */:
106146                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
106147                             return "skip";
106148                         case 266 /* ExportAssignment */:
106149                             if (node.isExportEquals) {
106150                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
106151                                 return "skip";
106152                             }
106153                             break;
106154                         case 286 /* HeritageClause */:
106155                             var heritageClause = node;
106156                             if (heritageClause.token === 116 /* ImplementsKeyword */) {
106157                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
106158                                 return "skip";
106159                             }
106160                             break;
106161                         case 253 /* InterfaceDeclaration */:
106162                             var interfaceKeyword = ts.tokenToString(117 /* InterfaceKeyword */);
106163                             ts.Debug.assertIsDefined(interfaceKeyword);
106164                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
106165                             return "skip";
106166                         case 256 /* ModuleDeclaration */:
106167                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(140 /* NamespaceKeyword */) : ts.tokenToString(139 /* ModuleKeyword */);
106168                             ts.Debug.assertIsDefined(moduleKeyword);
106169                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
106170                             return "skip";
106171                         case 254 /* TypeAliasDeclaration */:
106172                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
106173                             return "skip";
106174                         case 255 /* EnumDeclaration */:
106175                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91 /* EnumKeyword */));
106176                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
106177                             return "skip";
106178                         case 225 /* NonNullExpression */:
106179                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
106180                             return "skip";
106181                         case 224 /* AsExpression */:
106182                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
106183                             return "skip";
106184                         case 206 /* TypeAssertionExpression */:
106185                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
106186                     }
106187                 }
106188                 function walkArray(nodes, parent) {
106189                     if (parent.decorators === nodes && !options.experimentalDecorators) {
106190                         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_in_your_tsconfig_or_jsconfig_to_remove_this_warning));
106191                     }
106192                     switch (parent.kind) {
106193                         case 252 /* ClassDeclaration */:
106194                         case 221 /* ClassExpression */:
106195                         case 165 /* MethodDeclaration */:
106196                         case 166 /* Constructor */:
106197                         case 167 /* GetAccessor */:
106198                         case 168 /* SetAccessor */:
106199                         case 208 /* FunctionExpression */:
106200                         case 251 /* FunctionDeclaration */:
106201                         case 209 /* ArrowFunction */:
106202                             // Check type parameters
106203                             if (nodes === parent.typeParameters) {
106204                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
106205                                 return "skip";
106206                             }
106207                         // falls through
106208                         case 232 /* VariableStatement */:
106209                             // Check modifiers
106210                             if (nodes === parent.modifiers) {
106211                                 checkModifiers(parent.modifiers, parent.kind === 232 /* VariableStatement */);
106212                                 return "skip";
106213                             }
106214                             break;
106215                         case 163 /* PropertyDeclaration */:
106216                             // Check modifiers of property declaration
106217                             if (nodes === parent.modifiers) {
106218                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
106219                                     var modifier = _a[_i];
106220                                     if (modifier.kind !== 123 /* StaticKeyword */) {
106221                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
106222                                     }
106223                                 }
106224                                 return "skip";
106225                             }
106226                             break;
106227                         case 160 /* Parameter */:
106228                             // Check modifiers of parameter declaration
106229                             if (nodes === parent.modifiers) {
106230                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
106231                                 return "skip";
106232                             }
106233                             break;
106234                         case 203 /* CallExpression */:
106235                         case 204 /* NewExpression */:
106236                         case 223 /* ExpressionWithTypeArguments */:
106237                         case 274 /* JsxSelfClosingElement */:
106238                         case 275 /* JsxOpeningElement */:
106239                         case 205 /* TaggedTemplateExpression */:
106240                             // Check type arguments
106241                             if (nodes === parent.typeArguments) {
106242                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
106243                                 return "skip";
106244                             }
106245                             break;
106246                     }
106247                 }
106248                 function checkModifiers(modifiers, isConstValid) {
106249                     for (var _i = 0, modifiers_2 = modifiers; _i < modifiers_2.length; _i++) {
106250                         var modifier = modifiers_2[_i];
106251                         switch (modifier.kind) {
106252                             case 84 /* ConstKeyword */:
106253                                 if (isConstValid) {
106254                                     continue;
106255                                 }
106256                             // to report error,
106257                             // falls through
106258                             case 122 /* PublicKeyword */:
106259                             case 120 /* PrivateKeyword */:
106260                             case 121 /* ProtectedKeyword */:
106261                             case 142 /* ReadonlyKeyword */:
106262                             case 133 /* DeclareKeyword */:
106263                             case 125 /* AbstractKeyword */:
106264                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
106265                                 break;
106266                             // These are all legal modifiers.
106267                             case 123 /* StaticKeyword */:
106268                             case 92 /* ExportKeyword */:
106269                             case 87 /* DefaultKeyword */:
106270                         }
106271                     }
106272                 }
106273                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
106274                     var start = nodes.pos;
106275                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
106276                 }
106277                 // Since these are syntactic diagnostics, parent might not have been set
106278                 // this means the sourceFile cannot be infered from the node
106279                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
106280                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
106281                 }
106282             });
106283         }
106284         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
106285             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
106286         }
106287         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
106288             return runWithCancellationToken(function () {
106289                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
106290                 // Don't actually write any files since we're just getting diagnostics.
106291                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
106292             });
106293         }
106294         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
106295             var _a;
106296             var cachedResult = sourceFile
106297                 ? (_a = cache.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path) : cache.allDiagnostics;
106298             if (cachedResult) {
106299                 return cachedResult;
106300             }
106301             var result = getDiagnostics(sourceFile, cancellationToken);
106302             if (sourceFile) {
106303                 (cache.perFile || (cache.perFile = new ts.Map())).set(sourceFile.path, result);
106304             }
106305             else {
106306                 cache.allDiagnostics = result;
106307             }
106308             return result;
106309         }
106310         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
106311             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
106312         }
106313         function getOptionsDiagnostics() {
106314             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
106315         }
106316         function getOptionsDiagnosticsOfConfigFile() {
106317             if (!options.configFile) {
106318                 return ts.emptyArray;
106319             }
106320             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
106321             forEachResolvedProjectReference(function (resolvedRef) {
106322                 diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
106323             });
106324             return diagnostics;
106325         }
106326         function getGlobalDiagnostics() {
106327             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
106328         }
106329         function getConfigFileParsingDiagnostics() {
106330             return configFileParsingDiagnostics || ts.emptyArray;
106331         }
106332         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
106333             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
106334         }
106335         function fileReferenceIsEqualTo(a, b) {
106336             return a.fileName === b.fileName;
106337         }
106338         function moduleNameIsEqualTo(a, b) {
106339             return a.kind === 78 /* Identifier */
106340                 ? b.kind === 78 /* Identifier */ && a.escapedText === b.escapedText
106341                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
106342         }
106343         function createSyntheticImport(text, file) {
106344             var externalHelpersModuleReference = ts.factory.createStringLiteral(text);
106345             var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
106346             ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
106347             ts.setParent(externalHelpersModuleReference, importDecl);
106348             ts.setParent(importDecl, file);
106349             // explicitly unset the synthesized flag on these declarations so the checker API will answer questions about them
106350             // (which is required to build the dependency graph for incremental emit)
106351             externalHelpersModuleReference.flags &= ~8 /* Synthesized */;
106352             importDecl.flags &= ~8 /* Synthesized */;
106353             return externalHelpersModuleReference;
106354         }
106355         function collectExternalModuleReferences(file) {
106356             if (file.imports) {
106357                 return;
106358             }
106359             var isJavaScriptFile = ts.isSourceFileJS(file);
106360             var isExternalModuleFile = ts.isExternalModule(file);
106361             // file.imports may not be undefined if there exists dynamic import
106362             var imports;
106363             var moduleAugmentations;
106364             var ambientModules;
106365             // If we are importing helpers, we need to add a synthetic reference to resolve the
106366             // helpers library.
106367             if ((options.isolatedModules || isExternalModuleFile)
106368                 && !file.isDeclarationFile) {
106369                 if (options.importHelpers) {
106370                     // synthesize 'import "tslib"' declaration
106371                     imports = [createSyntheticImport(ts.externalHelpersModuleNameText, file)];
106372                 }
106373                 var jsxImport = ts.getJSXRuntimeImport(ts.getJSXImplicitImportBase(options, file), options);
106374                 if (jsxImport) {
106375                     // synthesize `import "base/jsx-runtime"` declaration
106376                     (imports || (imports = [])).push(createSyntheticImport(jsxImport, file));
106377                 }
106378             }
106379             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
106380                 var node = _a[_i];
106381                 collectModuleReferences(node, /*inAmbientModule*/ false);
106382             }
106383             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
106384                 collectDynamicImportOrRequireCalls(file);
106385             }
106386             file.imports = imports || ts.emptyArray;
106387             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
106388             file.ambientModuleNames = ambientModules || ts.emptyArray;
106389             return;
106390             function collectModuleReferences(node, inAmbientModule) {
106391                 if (ts.isAnyImportOrReExport(node)) {
106392                     var moduleNameExpr = ts.getExternalModuleName(node);
106393                     // TypeScript 1.0 spec (April 2014): 12.1.6
106394                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
106395                     // only through top - level external module names. Relative external module names are not permitted.
106396                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
106397                         imports = ts.append(imports, moduleNameExpr);
106398                     }
106399                 }
106400                 else if (ts.isModuleDeclaration(node)) {
106401                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasSyntacticModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
106402                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
106403                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
106404                         // This will happen in two cases:
106405                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
106406                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
106407                         //   immediately nested in top level ambient module declaration .
106408                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
106409                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
106410                         }
106411                         else if (!inAmbientModule) {
106412                             if (file.isDeclarationFile) {
106413                                 // for global .d.ts files record name of ambient module
106414                                 (ambientModules || (ambientModules = [])).push(nameText);
106415                             }
106416                             // An AmbientExternalModuleDeclaration declares an external module.
106417                             // This type of declaration is permitted only in the global module.
106418                             // The StringLiteral must specify a top - level external module name.
106419                             // Relative external module names are not permitted
106420                             // NOTE: body of ambient module is always a module block, if it exists
106421                             var body = node.body;
106422                             if (body) {
106423                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
106424                                     var statement = _a[_i];
106425                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
106426                                 }
106427                             }
106428                         }
106429                     }
106430                 }
106431             }
106432             function collectDynamicImportOrRequireCalls(file) {
106433                 var r = /import|require/g;
106434                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
106435                     var node = getNodeAtPosition(file, r.lastIndex);
106436                     if (isJavaScriptFile && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
106437                         imports = ts.append(imports, node.arguments[0]);
106438                     }
106439                     // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
106440                     else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
106441                         imports = ts.append(imports, node.arguments[0]);
106442                     }
106443                     else if (ts.isLiteralImportTypeNode(node)) {
106444                         imports = ts.append(imports, node.argument.literal);
106445                     }
106446                 }
106447             }
106448             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
106449             function getNodeAtPosition(sourceFile, position) {
106450                 var current = sourceFile;
106451                 var getContainingChild = function (child) {
106452                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
106453                         return child;
106454                     }
106455                 };
106456                 while (true) {
106457                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
106458                     if (!child) {
106459                         return current;
106460                     }
106461                     current = child;
106462                 }
106463             }
106464         }
106465         function getLibFileFromReference(ref) {
106466             var libName = ts.toFileNameLowerCase(ref.fileName);
106467             var libFileName = ts.libMap.get(libName);
106468             if (libFileName) {
106469                 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
106470             }
106471         }
106472         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
106473         function getSourceFileFromReference(referencingFile, ref) {
106474             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
106475         }
106476         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
106477             if (ts.hasExtension(fileName)) {
106478                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
106479                 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
106480                     if (fail) {
106481                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
106482                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
106483                         }
106484                         else {
106485                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
106486                         }
106487                     }
106488                     return undefined;
106489                 }
106490                 var sourceFile = getSourceFile(fileName);
106491                 if (fail) {
106492                     if (!sourceFile) {
106493                         var redirect = getProjectReferenceRedirect(fileName);
106494                         if (redirect) {
106495                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
106496                         }
106497                         else {
106498                             fail(ts.Diagnostics.File_0_not_found, fileName);
106499                         }
106500                     }
106501                     else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
106502                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
106503                     }
106504                 }
106505                 return sourceFile;
106506             }
106507             else {
106508                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
106509                 if (sourceFileNoExtension)
106510                     return sourceFileNoExtension;
106511                 if (fail && options.allowNonTsExtensions) {
106512                     fail(ts.Diagnostics.File_0_not_found, fileName);
106513                     return undefined;
106514                 }
106515                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
106516                 if (fail && !sourceFileWithAddedExtension)
106517                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
106518                 return sourceFileWithAddedExtension;
106519             }
106520         }
106521         /** This has side effects through `findSourceFile`. */
106522         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
106523             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
106524             function (diagnostic) {
106525                 var args = [];
106526                 for (var _i = 1; _i < arguments.length; _i++) {
106527                     args[_i - 1] = arguments[_i];
106528                 }
106529                 return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
106530             }, refFile && refFile.file);
106531         }
106532         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
106533             var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
106534             var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
106535             fileProcessingDiagnostics.add(refToReportErrorOn ?
106536                 createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
106537                 createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
106538         }
106539         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
106540             var redirect = Object.create(redirectTarget);
106541             redirect.fileName = fileName;
106542             redirect.path = path;
106543             redirect.resolvedPath = resolvedPath;
106544             redirect.originalFileName = originalFileName;
106545             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
106546             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
106547             Object.defineProperties(redirect, {
106548                 id: {
106549                     get: function () { return this.redirectInfo.redirectTarget.id; },
106550                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
106551                 },
106552                 symbol: {
106553                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
106554                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
106555                 },
106556             });
106557             return redirect;
106558         }
106559         // Get source file from normalized fileName
106560         function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
106561             ts.tracing.push("program" /* Program */, "findSourceFile", {
106562                 fileName: fileName,
106563                 isDefaultLib: isDefaultLib || undefined,
106564                 refKind: refFile ? ts.RefFileKind[refFile.kind] : undefined,
106565             });
106566             var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId);
106567             ts.tracing.pop();
106568             return result;
106569         }
106570         function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
106571             if (useSourceOfProjectReferenceRedirect) {
106572                 var source = getSourceOfProjectReferenceRedirect(fileName);
106573                 // If preserveSymlinks is true, module resolution wont jump the symlink
106574                 // but the resolved real path may be the .d.ts from project reference
106575                 // Note:: Currently we try the real path only if the
106576                 // file is from node_modules to avoid having to run real path on all file paths
106577                 if (!source &&
106578                     host.realpath &&
106579                     options.preserveSymlinks &&
106580                     ts.isDeclarationFileName(fileName) &&
106581                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
106582                     var realPath = host.realpath(fileName);
106583                     if (realPath !== fileName)
106584                         source = getSourceOfProjectReferenceRedirect(realPath);
106585                 }
106586                 if (source) {
106587                     var file_1 = ts.isString(source) ?
106588                         findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
106589                         undefined;
106590                     if (file_1)
106591                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
106592                     return file_1;
106593                 }
106594             }
106595             var originalFileName = fileName;
106596             if (filesByName.has(path)) {
106597                 var file_2 = filesByName.get(path);
106598                 addFileToRefFileMap(fileName, file_2 || undefined, refFile);
106599                 // try to check if we've already seen this file but with a different casing in path
106600                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
106601                 if (file_2 && options.forceConsistentCasingInFileNames) {
106602                     var checkedName = file_2.fileName;
106603                     var isRedirect = toPath(checkedName) !== toPath(fileName);
106604                     if (isRedirect) {
106605                         fileName = getProjectReferenceRedirect(fileName) || fileName;
106606                     }
106607                     // Check if it differs only in drive letters its ok to ignore that error:
106608                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
106609                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
106610                     if (checkedAbsolutePath !== inputAbsolutePath) {
106611                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
106612                     }
106613                 }
106614                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
106615                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
106616                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
106617                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
106618                     if (!options.noResolve) {
106619                         processReferencedFiles(file_2, isDefaultLib);
106620                         processTypeReferenceDirectives(file_2);
106621                     }
106622                     if (!options.noLib) {
106623                         processLibReferenceDirectives(file_2);
106624                     }
106625                     modulesWithElidedImports.set(file_2.path, false);
106626                     processImportedModules(file_2);
106627                 }
106628                 // See if we need to reprocess the imports due to prior skipped imports
106629                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
106630                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
106631                         modulesWithElidedImports.set(file_2.path, false);
106632                         processImportedModules(file_2);
106633                     }
106634                 }
106635                 return file_2 || undefined;
106636             }
106637             var redirectedPath;
106638             if (refFile && !useSourceOfProjectReferenceRedirect) {
106639                 var redirectProject = getProjectReferenceRedirectProject(fileName);
106640                 if (redirectProject) {
106641                     if (ts.outFile(redirectProject.commandLine.options)) {
106642                         // Shouldnt create many to 1 mapping file in --out scenario
106643                         return undefined;
106644                     }
106645                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
106646                     fileName = redirect;
106647                     // Once we start redirecting to a file, we can potentially come back to it
106648                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
106649                     // end up trying to add it to the program *again* because we were tracking it via its
106650                     // original (un-redirected) name. So we have to map both the original path and the redirected path
106651                     // to the source file we're about to find/create
106652                     redirectedPath = toPath(redirect);
106653                 }
106654             }
106655             // We haven't looked for this file, do so now and cache result
106656             var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { return fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); }, shouldCreateNewSourceFile);
106657             if (packageId) {
106658                 var packageIdKey = ts.packageIdToString(packageId);
106659                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
106660                 if (fileFromPackageId) {
106661                     // Some other SourceFile already exists with this package name and version.
106662                     // Instead of creating a duplicate, just redirect to the existing one.
106663                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
106664                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
106665                     addFileToFilesByName(dupFile, path, redirectedPath);
106666                     sourceFileToPackageName.set(path, packageId.name);
106667                     processingOtherFiles.push(dupFile);
106668                     return dupFile;
106669                 }
106670                 else if (file) {
106671                     // This is the first source file to have this packageId.
106672                     packageIdToSourceFile.set(packageIdKey, file);
106673                     sourceFileToPackageName.set(path, packageId.name);
106674                 }
106675             }
106676             addFileToFilesByName(file, path, redirectedPath);
106677             if (file) {
106678                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
106679                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
106680                 file.path = path;
106681                 file.resolvedPath = toPath(fileName);
106682                 file.originalFileName = originalFileName;
106683                 addFileToRefFileMap(fileName, file, refFile);
106684                 if (host.useCaseSensitiveFileNames()) {
106685                     var pathLowerCase = ts.toFileNameLowerCase(path);
106686                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
106687                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
106688                     if (existingFile) {
106689                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
106690                     }
106691                     else {
106692                         filesByNameIgnoreCase.set(pathLowerCase, file);
106693                     }
106694                 }
106695                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
106696                 if (!options.noResolve) {
106697                     processReferencedFiles(file, isDefaultLib);
106698                     processTypeReferenceDirectives(file);
106699                 }
106700                 if (!options.noLib) {
106701                     processLibReferenceDirectives(file);
106702                 }
106703                 // always process imported modules to record module name resolutions
106704                 processImportedModules(file);
106705                 if (isDefaultLib) {
106706                     processingDefaultLibFiles.push(file);
106707                 }
106708                 else {
106709                     processingOtherFiles.push(file);
106710                 }
106711             }
106712             return file;
106713         }
106714         function addFileToRefFileMap(referencedFileName, file, refFile) {
106715             if (refFile && file) {
106716                 (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
106717                     referencedFileName: referencedFileName,
106718                     kind: refFile.kind,
106719                     index: refFile.index,
106720                     file: refFile.file.path
106721                 });
106722             }
106723         }
106724         function addFileToFilesByName(file, path, redirectedPath) {
106725             if (redirectedPath) {
106726                 filesByName.set(redirectedPath, file);
106727                 filesByName.set(path, file || false);
106728             }
106729             else {
106730                 filesByName.set(path, file);
106731             }
106732         }
106733         function getProjectReferenceRedirect(fileName) {
106734             var referencedProject = getProjectReferenceRedirectProject(fileName);
106735             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
106736         }
106737         function getProjectReferenceRedirectProject(fileName) {
106738             // Ignore dts or any json files
106739             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
106740                 return undefined;
106741             }
106742             // If this file is produced by a referenced project, we need to rewrite it to
106743             // look in the output folder of the referenced project rather than the input
106744             return getResolvedProjectReferenceToRedirect(fileName);
106745         }
106746         function getProjectReferenceOutputName(referencedProject, fileName) {
106747             var out = ts.outFile(referencedProject.commandLine.options);
106748             return out ?
106749                 ts.changeExtension(out, ".d.ts" /* Dts */) :
106750                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
106751         }
106752         /**
106753          * Get the referenced project if the file is input file from that reference project
106754          */
106755         function getResolvedProjectReferenceToRedirect(fileName) {
106756             if (mapFromFileToProjectReferenceRedirects === undefined) {
106757                 mapFromFileToProjectReferenceRedirects = new ts.Map();
106758                 forEachResolvedProjectReference(function (referencedProject) {
106759                     // not input file from the referenced project, ignore
106760                     if (toPath(options.configFilePath) !== referencedProject.sourceFile.path) {
106761                         referencedProject.commandLine.fileNames.forEach(function (f) {
106762                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referencedProject.sourceFile.path);
106763                         });
106764                     }
106765                 });
106766             }
106767             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
106768             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
106769         }
106770         function forEachResolvedProjectReference(cb) {
106771             return ts.forEachResolvedProjectReference(resolvedProjectReferences, cb);
106772         }
106773         function getSourceOfProjectReferenceRedirect(file) {
106774             if (!ts.isDeclarationFileName(file))
106775                 return undefined;
106776             if (mapFromToProjectReferenceRedirectSource === undefined) {
106777                 mapFromToProjectReferenceRedirectSource = new ts.Map();
106778                 forEachResolvedProjectReference(function (resolvedRef) {
106779                     var out = ts.outFile(resolvedRef.commandLine.options);
106780                     if (out) {
106781                         // Dont know which source file it means so return true?
106782                         var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
106783                         mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
106784                     }
106785                     else {
106786                         ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
106787                             if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
106788                                 var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
106789                                 mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
106790                             }
106791                         });
106792                     }
106793                 });
106794             }
106795             return mapFromToProjectReferenceRedirectSource.get(toPath(file));
106796         }
106797         function isSourceOfProjectReferenceRedirect(fileName) {
106798             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
106799         }
106800         function getResolvedProjectReferenceByPath(projectReferencePath) {
106801             if (!projectReferenceRedirects) {
106802                 return undefined;
106803             }
106804             return projectReferenceRedirects.get(projectReferencePath) || undefined;
106805         }
106806         function processReferencedFiles(file, isDefaultLib) {
106807             ts.forEach(file.referencedFiles, function (ref, index) {
106808                 var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
106809                 processSourceFile(referencedFileName, isDefaultLib, 
106810                 /*ignoreNoDefaultLib*/ false, 
106811                 /*packageId*/ undefined, {
106812                     kind: ts.RefFileKind.ReferenceFile,
106813                     index: index,
106814                     file: file,
106815                     pos: ref.pos,
106816                     end: ref.end
106817                 });
106818             });
106819         }
106820         function processTypeReferenceDirectives(file) {
106821             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
106822             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
106823             if (!typeDirectives) {
106824                 return;
106825             }
106826             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file);
106827             for (var i = 0; i < typeDirectives.length; i++) {
106828                 var ref = file.typeReferenceDirectives[i];
106829                 var resolvedTypeReferenceDirective = resolutions[i];
106830                 // store resolved type directive on the file
106831                 var fileName = ts.toFileNameLowerCase(ref.fileName);
106832                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
106833                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
106834                     kind: ts.RefFileKind.TypeReferenceDirective,
106835                     index: i,
106836                     file: file,
106837                     pos: ref.pos,
106838                     end: ref.end
106839                 });
106840             }
106841         }
106842         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
106843             ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: refFile === null || refFile === void 0 ? void 0 : refFile.kind, refPath: refFile === null || refFile === void 0 ? void 0 : refFile.file.path });
106844             processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, refFile);
106845             ts.tracing.pop();
106846         }
106847         function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
106848             // If we already found this library as a primary reference - nothing to do
106849             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
106850             if (previousResolution && previousResolution.primary) {
106851                 return;
106852             }
106853             var saveResolution = true;
106854             if (resolvedTypeReferenceDirective) {
106855                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
106856                     currentNodeModulesDepth++;
106857                 if (resolvedTypeReferenceDirective.primary) {
106858                     // resolved from the primary path
106859                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
106860                 }
106861                 else {
106862                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
106863                     // for sameness and possibly issue an error
106864                     if (previousResolution) {
106865                         // Don't bother reading the file again if it's the same file.
106866                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
106867                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
106868                             var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
106869                             if (otherFileText !== existingFile_1.text) {
106870                                 // Try looking up ref for original file
106871                                 var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
106872                                 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
106873                                 fileProcessingDiagnostics.add(refToReportErrorOn ?
106874                                     createFileDiagnosticAtReference(refToReportErrorOn, 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) :
106875                                     createRefFileDiagnostic(refFile, 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));
106876                             }
106877                         }
106878                         // don't overwrite previous resolution result
106879                         saveResolution = false;
106880                     }
106881                     else {
106882                         // First resolution of this library
106883                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
106884                     }
106885                 }
106886                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
106887                     currentNodeModulesDepth--;
106888             }
106889             else {
106890                 fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
106891             }
106892             if (saveResolution) {
106893                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
106894             }
106895         }
106896         function processLibReferenceDirectives(file) {
106897             ts.forEach(file.libReferenceDirectives, function (libReference) {
106898                 var libName = ts.toFileNameLowerCase(libReference.fileName);
106899                 var libFileName = ts.libMap.get(libName);
106900                 if (libFileName) {
106901                     // we ignore any 'no-default-lib' reference set on this file.
106902                     processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
106903                 }
106904                 else {
106905                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
106906                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
106907                     var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
106908                     fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
106909                 }
106910             });
106911         }
106912         function createRefFileDiagnostic(refFile, message) {
106913             var args = [];
106914             for (var _i = 2; _i < arguments.length; _i++) {
106915                 args[_i - 2] = arguments[_i];
106916             }
106917             if (!refFile) {
106918                 return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
106919             }
106920             else {
106921                 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
106922             }
106923         }
106924         function getCanonicalFileName(fileName) {
106925             return host.getCanonicalFileName(fileName);
106926         }
106927         function processImportedModules(file) {
106928             collectExternalModuleReferences(file);
106929             if (file.imports.length || file.moduleAugmentations.length) {
106930                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
106931                 var moduleNames = getModuleNames(file);
106932                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, file);
106933                 ts.Debug.assert(resolutions.length === moduleNames.length);
106934                 for (var i = 0; i < moduleNames.length; i++) {
106935                     var resolution = resolutions[i];
106936                     ts.setResolvedModule(file, moduleNames[i], resolution);
106937                     if (!resolution) {
106938                         continue;
106939                     }
106940                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
106941                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
106942                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
106943                     var resolvedFileName = resolution.resolvedFileName;
106944                     if (isFromNodeModulesSearch) {
106945                         currentNodeModulesDepth++;
106946                     }
106947                     // add file to program only if:
106948                     // - resolution was successful
106949                     // - noResolve is falsy
106950                     // - module name comes from the list of imports
106951                     // - it's not a top level JavaScript module that exceeded the search max
106952                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
106953                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
106954                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
106955                     var shouldAddFile = resolvedFileName
106956                         && !getResolutionDiagnostic(options, resolution)
106957                         && !options.noResolve
106958                         && i < file.imports.length
106959                         && !elideImport
106960                         && !(isJsFile && !ts.getAllowJSCompilerOption(options))
106961                         && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
106962                     if (elideImport) {
106963                         modulesWithElidedImports.set(file.path, true);
106964                     }
106965                     else if (shouldAddFile) {
106966                         var path = toPath(resolvedFileName);
106967                         var pos = ts.skipTrivia(file.text, file.imports[i].pos);
106968                         findSourceFile(resolvedFileName, path, 
106969                         /*isDefaultLib*/ false, 
106970                         /*ignoreNoDefaultLib*/ false, {
106971                             kind: ts.RefFileKind.Import,
106972                             index: i,
106973                             file: file,
106974                             pos: pos,
106975                             end: file.imports[i].end
106976                         }, resolution.packageId);
106977                     }
106978                     if (isFromNodeModulesSearch) {
106979                         currentNodeModulesDepth--;
106980                     }
106981                 }
106982             }
106983             else {
106984                 // no imports - drop cached module resolutions
106985                 file.resolvedModules = undefined;
106986             }
106987         }
106988         function computeCommonSourceDirectory(sourceFiles) {
106989             var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
106990             return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
106991         }
106992         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
106993             var allFilesBelongToPath = true;
106994             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
106995             var rootPaths;
106996             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
106997                 var sourceFile = sourceFiles_2[_i];
106998                 if (!sourceFile.isDeclarationFile) {
106999                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
107000                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
107001                         if (!rootPaths)
107002                             rootPaths = new ts.Set(rootNames.map(toPath));
107003                         addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
107004                         allFilesBelongToPath = false;
107005                     }
107006                 }
107007             }
107008             return allFilesBelongToPath;
107009         }
107010         function parseProjectReferenceConfigFile(ref) {
107011             if (!projectReferenceRedirects) {
107012                 projectReferenceRedirects = new ts.Map();
107013             }
107014             // The actual filename (i.e. add "/tsconfig.json" if necessary)
107015             var refPath = resolveProjectReferencePath(ref);
107016             var sourceFilePath = toPath(refPath);
107017             var fromCache = projectReferenceRedirects.get(sourceFilePath);
107018             if (fromCache !== undefined) {
107019                 return fromCache || undefined;
107020             }
107021             var commandLine;
107022             var sourceFile;
107023             if (host.getParsedCommandLine) {
107024                 commandLine = host.getParsedCommandLine(refPath);
107025                 if (!commandLine) {
107026                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
107027                     projectReferenceRedirects.set(sourceFilePath, false);
107028                     return undefined;
107029                 }
107030                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
107031                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
107032                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
107033             }
107034             else {
107035                 // An absolute path pointing to the containing directory of the config file
107036                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
107037                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
107038                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
107039                 if (sourceFile === undefined) {
107040                     projectReferenceRedirects.set(sourceFilePath, false);
107041                     return undefined;
107042                 }
107043                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
107044             }
107045             sourceFile.fileName = refPath;
107046             sourceFile.path = sourceFilePath;
107047             sourceFile.resolvedPath = sourceFilePath;
107048             sourceFile.originalFileName = refPath;
107049             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
107050             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
107051             if (commandLine.projectReferences) {
107052                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
107053             }
107054             return resolvedRef;
107055         }
107056         function verifyCompilerOptions() {
107057             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
107058                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
107059             }
107060             if (options.isolatedModules) {
107061                 if (options.out) {
107062                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
107063                 }
107064                 if (options.outFile) {
107065                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
107066                 }
107067             }
107068             if (options.inlineSourceMap) {
107069                 if (options.sourceMap) {
107070                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
107071                 }
107072                 if (options.mapRoot) {
107073                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
107074                 }
107075             }
107076             if (options.composite) {
107077                 if (options.declaration === false) {
107078                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
107079                 }
107080                 if (options.incremental === false) {
107081                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
107082                 }
107083             }
107084             var outputFile = ts.outFile(options);
107085             if (options.tsBuildInfoFile) {
107086                 if (!ts.isIncrementalCompilation(options)) {
107087                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
107088                 }
107089             }
107090             else if (options.incremental && !outputFile && !options.configFilePath) {
107091                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
107092             }
107093             verifyProjectReferences();
107094             // List of collected files is complete; validate exhautiveness if this is a project with a file list
107095             if (options.composite) {
107096                 var rootPaths = new ts.Set(rootNames.map(toPath));
107097                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
107098                     var file = files_3[_i];
107099                     // Ignore file that is not emitted
107100                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
107101                         addProgramDiagnosticAtRefPath(file, rootPaths, ts.Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, file.fileName, options.configFilePath || "");
107102                     }
107103                 }
107104             }
107105             if (options.paths) {
107106                 for (var key in options.paths) {
107107                     if (!ts.hasProperty(options.paths, key)) {
107108                         continue;
107109                     }
107110                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
107111                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
107112                     }
107113                     if (ts.isArray(options.paths[key])) {
107114                         var len = options.paths[key].length;
107115                         if (len === 0) {
107116                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
107117                         }
107118                         for (var i = 0; i < len; i++) {
107119                             var subst = options.paths[key][i];
107120                             var typeOfSubst = typeof subst;
107121                             if (typeOfSubst === "string") {
107122                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
107123                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
107124                                 }
107125                                 if (!options.baseUrl && !ts.pathIsRelative(subst) && !ts.pathIsAbsolute(subst)) {
107126                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash);
107127                                 }
107128                             }
107129                             else {
107130                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
107131                             }
107132                         }
107133                     }
107134                     else {
107135                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
107136                     }
107137                 }
107138             }
107139             if (!options.sourceMap && !options.inlineSourceMap) {
107140                 if (options.inlineSources) {
107141                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
107142                 }
107143                 if (options.sourceRoot) {
107144                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
107145                 }
107146             }
107147             if (options.out && options.outFile) {
107148                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
107149             }
107150             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
107151                 // Error to specify --mapRoot without --sourcemap
107152                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
107153             }
107154             if (options.declarationDir) {
107155                 if (!ts.getEmitDeclarations(options)) {
107156                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
107157                 }
107158                 if (outputFile) {
107159                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
107160                 }
107161             }
107162             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
107163                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
107164             }
107165             if (options.lib && options.noLib) {
107166                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
107167             }
107168             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
107169                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
107170             }
107171             var languageVersion = options.target || 0 /* ES3 */;
107172             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
107173             if (options.isolatedModules) {
107174                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
107175                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
107176                 }
107177                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
107178                 if (firstNonExternalModuleSourceFile) {
107179                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
107180                     programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics._0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module, ts.getBaseFileName(firstNonExternalModuleSourceFile.fileName)));
107181                 }
107182             }
107183             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
107184                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
107185                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
107186                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
107187             }
107188             // Cannot specify module gen that isn't amd or system with --out
107189             if (outputFile && !options.emitDeclarationOnly) {
107190                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
107191                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
107192                 }
107193                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
107194                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
107195                     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"));
107196                 }
107197             }
107198             if (options.resolveJsonModule) {
107199                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
107200                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
107201                 }
107202                 // Any emit other than common js, amd, es2015 or esnext is error
107203                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
107204                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
107205                 }
107206             }
107207             // there has to be common source directory if user specified --outdir || --sourceRoot
107208             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
107209             if (options.outDir || // there is --outDir specified
107210                 options.sourceRoot || // there is --sourceRoot specified
107211                 options.mapRoot) { // there is --mapRoot specified
107212                 // Precalculate and cache the common source directory
107213                 var dir = getCommonSourceDirectory();
107214                 // 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
107215                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
107216                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
107217                 }
107218             }
107219             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
107220                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
107221             }
107222             if (options.checkJs && !ts.getAllowJSCompilerOption(options)) {
107223                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
107224             }
107225             if (options.emitDeclarationOnly) {
107226                 if (!ts.getEmitDeclarations(options)) {
107227                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
107228                 }
107229                 if (options.noEmit) {
107230                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
107231                 }
107232             }
107233             if (options.emitDecoratorMetadata &&
107234                 !options.experimentalDecorators) {
107235                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
107236             }
107237             if (options.jsxFactory) {
107238                 if (options.reactNamespace) {
107239                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
107240                 }
107241                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
107242                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFactory", ts.inverseJsxOptionMap.get("" + options.jsx));
107243                 }
107244                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
107245                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
107246                 }
107247             }
107248             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
107249                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
107250             }
107251             if (options.jsxFragmentFactory) {
107252                 if (!options.jsxFactory) {
107253                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "jsxFragmentFactory", "jsxFactory");
107254                 }
107255                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
107256                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFragmentFactory", ts.inverseJsxOptionMap.get("" + options.jsx));
107257                 }
107258                 if (!ts.parseIsolatedEntityName(options.jsxFragmentFactory, languageVersion)) {
107259                     createOptionValueDiagnostic("jsxFragmentFactory", ts.Diagnostics.Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFragmentFactory);
107260                 }
107261             }
107262             if (options.reactNamespace) {
107263                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
107264                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "reactNamespace", ts.inverseJsxOptionMap.get("" + options.jsx));
107265                 }
107266             }
107267             if (options.jsxImportSource) {
107268                 if (options.jsx === 2 /* React */) {
107269                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxImportSource", ts.inverseJsxOptionMap.get("" + options.jsx));
107270                 }
107271             }
107272             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
107273             if (!options.noEmit && !options.suppressOutputPathCheck) {
107274                 var emitHost = getEmitHost();
107275                 var emitFilesSeen_1 = new ts.Set();
107276                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
107277                     if (!options.emitDeclarationOnly) {
107278                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
107279                     }
107280                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
107281                 });
107282             }
107283             // Verify that all the emit files are unique and don't overwrite input files
107284             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
107285                 if (emitFileName) {
107286                     var emitFilePath = toPath(emitFileName);
107287                     // Report error if the output overwrites input file
107288                     if (filesByName.has(emitFilePath)) {
107289                         var chain = void 0;
107290                         if (!options.configFilePath) {
107291                             // The program is from either an inferred project or an external project
107292                             chain = 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);
107293                         }
107294                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
107295                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
107296                     }
107297                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
107298                     // Report error if multiple files write into same file
107299                     if (emitFilesSeen.has(emitFileKey)) {
107300                         // Already seen the same emit file - report error
107301                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
107302                     }
107303                     else {
107304                         emitFilesSeen.add(emitFileKey);
107305                     }
107306                 }
107307             }
107308         }
107309         function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
107310             var _a, _b;
107311             var args = [];
107312             for (var _i = 2; _i < arguments.length; _i++) {
107313                 args[_i - 2] = arguments[_i];
107314             }
107315             var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
107316             var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
107317             var pos, end;
107318             switch (kind) {
107319                 case ts.RefFileKind.Import:
107320                     pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
107321                     end = refFile.imports[index].end;
107322                     break;
107323                 case ts.RefFileKind.ReferenceFile:
107324                     (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
107325                     break;
107326                 case ts.RefFileKind.TypeReferenceDirective:
107327                     (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
107328                     break;
107329                 default:
107330                     return ts.Debug.assertNever(kind);
107331             }
107332             return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
107333         }
107334         function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
107335             var args = [];
107336             for (var _i = 3; _i < arguments.length; _i++) {
107337                 args[_i - 3] = arguments[_i];
107338             }
107339             var refPaths = refFileMap === null || refFileMap === void 0 ? void 0 : refFileMap.get(file.path);
107340             var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
107341                 ts.elementAt(refPaths, 0);
107342             programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
107343         }
107344         function verifyProjectReferences() {
107345             var buildInfoPath = !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
107346             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, parent, index) {
107347                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
107348                 var parentFile = parent && parent.sourceFile;
107349                 if (!resolvedRef) {
107350                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
107351                     return;
107352                 }
107353                 var options = resolvedRef.commandLine.options;
107354                 if (!options.composite || options.noEmit) {
107355                     // ok to not have composite if the current program is container only
107356                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
107357                     if (inputs.length) {
107358                         if (!options.composite)
107359                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
107360                         if (options.noEmit)
107361                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path);
107362                     }
107363                 }
107364                 if (ref.prepend) {
107365                     var out = ts.outFile(options);
107366                     if (out) {
107367                         if (!host.fileExists(out)) {
107368                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
107369                         }
107370                     }
107371                     else {
107372                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
107373                     }
107374                 }
107375                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
107376                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
107377                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
107378                 }
107379             });
107380         }
107381         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
107382             var needCompilerDiagnostic = true;
107383             var pathsSyntax = getOptionPathsSyntax();
107384             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
107385                 var pathProp = pathsSyntax_1[_i];
107386                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
107387                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
107388                         var keyProps = _b[_a];
107389                         var initializer = keyProps.initializer;
107390                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
107391                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
107392                             needCompilerDiagnostic = false;
107393                         }
107394                     }
107395                 }
107396             }
107397             if (needCompilerDiagnostic) {
107398                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
107399             }
107400         }
107401         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
107402             var needCompilerDiagnostic = true;
107403             var pathsSyntax = getOptionPathsSyntax();
107404             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
107405                 var pathProp = pathsSyntax_2[_i];
107406                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
107407                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
107408                     needCompilerDiagnostic = false;
107409                 }
107410             }
107411             if (needCompilerDiagnostic) {
107412                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
107413             }
107414         }
107415         function getOptionsSyntaxByName(name) {
107416             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
107417             if (compilerOptionsObjectLiteralSyntax) {
107418                 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
107419             }
107420             return undefined;
107421         }
107422         function getOptionPathsSyntax() {
107423             return getOptionsSyntaxByName("paths") || ts.emptyArray;
107424         }
107425         function createDiagnosticForOptionName(message, option1, option2, option3) {
107426             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
107427         }
107428         function createOptionValueDiagnostic(option1, message, arg0) {
107429             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
107430         }
107431         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
107432             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
107433             if (referencesSyntax && referencesSyntax.elements.length > index) {
107434                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
107435             }
107436             else {
107437                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
107438             }
107439         }
107440         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
107441             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
107442             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
107443                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
107444             if (needCompilerDiagnostic) {
107445                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
107446             }
107447         }
107448         function getCompilerOptionsObjectLiteralSyntax() {
107449             if (_compilerOptionsObjectLiteralSyntax === undefined) {
107450                 _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
107451                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
107452                 if (jsonObjectLiteral) {
107453                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
107454                         var prop = _a[_i];
107455                         if (ts.isObjectLiteralExpression(prop.initializer)) {
107456                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
107457                             break;
107458                         }
107459                     }
107460                 }
107461             }
107462             return _compilerOptionsObjectLiteralSyntax;
107463         }
107464         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
107465             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
107466             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
107467                 var prop = props_3[_i];
107468                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
107469             }
107470             return !!props.length;
107471         }
107472         function blockEmittingOfFile(emitFileName, diag) {
107473             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
107474             programDiagnostics.add(diag);
107475         }
107476         function isEmittedFile(file) {
107477             if (options.noEmit) {
107478                 return false;
107479             }
107480             // If this is source file, its not emitted file
107481             var filePath = toPath(file);
107482             if (getSourceFileByPath(filePath)) {
107483                 return false;
107484             }
107485             // If options have --outFile or --out just check that
107486             var out = ts.outFile(options);
107487             if (out) {
107488                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
107489             }
107490             // If declarationDir is specified, return if its a file in that directory
107491             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
107492                 return true;
107493             }
107494             // If --outDir, check if file is in that directory
107495             if (options.outDir) {
107496                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
107497             }
107498             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
107499                 // Otherwise just check if sourceFile with the name exists
107500                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
107501                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
107502                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
107503             }
107504             return false;
107505         }
107506         function isSameFile(file1, file2) {
107507             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
107508         }
107509         function getSymlinkCache() {
107510             if (host.getSymlinkCache) {
107511                 return host.getSymlinkCache();
107512             }
107513             return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
107514         }
107515     }
107516     ts.createProgram = createProgram;
107517     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
107518         var setOfDeclarationDirectories;
107519         var originalFileExists = host.compilerHost.fileExists;
107520         var originalDirectoryExists = host.compilerHost.directoryExists;
107521         var originalGetDirectories = host.compilerHost.getDirectories;
107522         var originalRealpath = host.compilerHost.realpath;
107523         if (!host.useSourceOfProjectReferenceRedirect)
107524             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
107525         host.compilerHost.fileExists = fileExists;
107526         var directoryExists;
107527         if (originalDirectoryExists) {
107528             // This implementation of directoryExists checks if the directory being requested is
107529             // directory of .d.ts file for the referenced Project.
107530             // If it is it returns true irrespective of whether that directory exists on host
107531             directoryExists = host.compilerHost.directoryExists = function (path) {
107532                 if (originalDirectoryExists.call(host.compilerHost, path)) {
107533                     handleDirectoryCouldBeSymlink(path);
107534                     return true;
107535                 }
107536                 if (!host.getResolvedProjectReferences())
107537                     return false;
107538                 if (!setOfDeclarationDirectories) {
107539                     setOfDeclarationDirectories = new ts.Set();
107540                     host.forEachResolvedProjectReference(function (ref) {
107541                         var out = ts.outFile(ref.commandLine.options);
107542                         if (out) {
107543                             setOfDeclarationDirectories.add(ts.getDirectoryPath(host.toPath(out)));
107544                         }
107545                         else {
107546                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
107547                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
107548                             if (declarationDir) {
107549                                 setOfDeclarationDirectories.add(host.toPath(declarationDir));
107550                             }
107551                         }
107552                     });
107553                 }
107554                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
107555             };
107556         }
107557         if (originalGetDirectories) {
107558             // Call getDirectories only if directory actually present on the host
107559             // This is needed to ensure that we arent getting directories that we fake about presence for
107560             host.compilerHost.getDirectories = function (path) {
107561                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
107562                     originalGetDirectories.call(host.compilerHost, path) :
107563                     [];
107564             };
107565         }
107566         // This is something we keep for life time of the host
107567         if (originalRealpath) {
107568             host.compilerHost.realpath = function (s) {
107569                 var _a;
107570                 return ((_a = host.getSymlinkCache().getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.get(host.toPath(s))) ||
107571                     originalRealpath.call(host.compilerHost, s);
107572             };
107573         }
107574         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists, directoryExists: directoryExists };
107575         function onProgramCreateComplete() {
107576             host.compilerHost.fileExists = originalFileExists;
107577             host.compilerHost.directoryExists = originalDirectoryExists;
107578             host.compilerHost.getDirectories = originalGetDirectories;
107579             // DO not revert realpath as it could be used later
107580         }
107581         // This implementation of fileExists checks if the file being requested is
107582         // .d.ts file for the referenced Project.
107583         // If it is it returns true irrespective of whether that file exists on host
107584         function fileExists(file) {
107585             if (originalFileExists.call(host.compilerHost, file))
107586                 return true;
107587             if (!host.getResolvedProjectReferences())
107588                 return false;
107589             if (!ts.isDeclarationFileName(file))
107590                 return false;
107591             // Project references go to source file instead of .d.ts file
107592             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
107593         }
107594         function fileExistsIfProjectReferenceDts(file) {
107595             var source = host.getSourceOfProjectReferenceRedirect(file);
107596             return source !== undefined ?
107597                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
107598                 undefined;
107599         }
107600         function directoryExistsIfProjectReferenceDeclDir(dir) {
107601             var dirPath = host.toPath(dir);
107602             var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
107603             return ts.forEachKey(setOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
107604                 // Any parent directory of declaration dir
107605                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
107606                 // Any directory inside declaration dir
107607                 ts.startsWith(dirPath, declDirPath + "/"); });
107608         }
107609         function handleDirectoryCouldBeSymlink(directory) {
107610             var _a;
107611             if (!host.getResolvedProjectReferences())
107612                 return;
107613             // Because we already watch node_modules, handle symlinks in there
107614             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
107615                 return;
107616             var symlinkCache = host.getSymlinkCache();
107617             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
107618             if ((_a = symlinkCache.getSymlinkedDirectories()) === null || _a === void 0 ? void 0 : _a.has(directoryPath))
107619                 return;
107620             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
107621             var realPath;
107622             if (real === directory ||
107623                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
107624                 // not symlinked
107625                 symlinkCache.setSymlinkedDirectory(directoryPath, false);
107626                 return;
107627             }
107628             symlinkCache.setSymlinkedDirectory(directoryPath, {
107629                 real: ts.ensureTrailingDirectorySeparator(real),
107630                 realPath: realPath
107631             });
107632         }
107633         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
107634             var _a;
107635             var fileOrDirectoryExistsUsingSource = isFile ?
107636                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
107637                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
107638             // Check current directory or file
107639             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
107640             if (result !== undefined)
107641                 return result;
107642             var symlinkCache = host.getSymlinkCache();
107643             var symlinkedDirectories = symlinkCache.getSymlinkedDirectories();
107644             if (!symlinkedDirectories)
107645                 return false;
107646             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
107647             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
107648                 return false;
107649             if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.has(fileOrDirectoryPath)))
107650                 return true;
107651             // If it contains node_modules check if its one of the symlinked path we know of
107652             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
107653                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
107654                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
107655                     return undefined;
107656                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
107657                 if (isFile && result) {
107658                     // Store the real path for the file'
107659                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
107660                     symlinkCache.setSymlinkedFile(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
107661                 }
107662                 return result;
107663             }) || false;
107664         }
107665     }
107666     /*@internal*/
107667     ts.emitSkippedWithNoDiagnostics = { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
107668     /*@internal*/
107669     function handleNoEmitOptions(program, sourceFile, writeFile, cancellationToken) {
107670         var options = program.getCompilerOptions();
107671         if (options.noEmit) {
107672             // Cache the semantic diagnostics
107673             program.getSemanticDiagnostics(sourceFile, cancellationToken);
107674             return sourceFile || ts.outFile(options) ?
107675                 ts.emitSkippedWithNoDiagnostics :
107676                 program.emitBuildInfo(writeFile, cancellationToken);
107677         }
107678         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
107679         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
107680         // get any preEmit diagnostics, not just the ones
107681         if (!options.noEmitOnError)
107682             return undefined;
107683         var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
107684         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
107685             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
107686         }
107687         if (!diagnostics.length)
107688             return undefined;
107689         var emittedFiles;
107690         if (!sourceFile && !ts.outFile(options)) {
107691             var emitResult = program.emitBuildInfo(writeFile, cancellationToken);
107692             if (emitResult.diagnostics)
107693                 diagnostics = __spreadArrays(diagnostics, emitResult.diagnostics);
107694             emittedFiles = emitResult.emittedFiles;
107695         }
107696         return { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: emittedFiles, emitSkipped: true };
107697     }
107698     ts.handleNoEmitOptions = handleNoEmitOptions;
107699     /*@internal*/
107700     function filterSemanticDiagnotics(diagnostic, option) {
107701         return ts.filter(diagnostic, function (d) { return !d.skippedOn || !option[d.skippedOn]; });
107702     }
107703     ts.filterSemanticDiagnotics = filterSemanticDiagnotics;
107704     /* @internal */
107705     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
107706         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
107707         return {
107708             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
107709             readDirectory: function (root, extensions, excludes, includes, depth) {
107710                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
107711                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
107712             },
107713             readFile: function (f) { return directoryStructureHost.readFile(f); },
107714             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
107715             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
107716             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
107717             trace: host.trace ? function (s) { return host.trace(s); } : undefined
107718         };
107719     }
107720     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
107721     /* @internal */
107722     function createPrependNodes(projectReferences, getCommandLine, readFile) {
107723         if (!projectReferences)
107724             return ts.emptyArray;
107725         var nodes;
107726         for (var i = 0; i < projectReferences.length; i++) {
107727             var ref = projectReferences[i];
107728             var resolvedRefOpts = getCommandLine(ref, i);
107729             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
107730                 var out = ts.outFile(resolvedRefOpts.options);
107731                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
107732                 if (!out)
107733                     continue;
107734                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
107735                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
107736                 (nodes || (nodes = [])).push(node);
107737             }
107738         }
107739         return nodes || ts.emptyArray;
107740     }
107741     ts.createPrependNodes = createPrependNodes;
107742     function resolveProjectReferencePath(hostOrRef, ref) {
107743         var passedInRef = ref ? ref : hostOrRef;
107744         return ts.resolveConfigFileProjectName(passedInRef.path);
107745     }
107746     ts.resolveProjectReferencePath = resolveProjectReferencePath;
107747     /* @internal */
107748     /**
107749      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
107750      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
107751      * This returns a diagnostic even if the module will be an untyped module.
107752      */
107753     function getResolutionDiagnostic(options, _a) {
107754         var extension = _a.extension;
107755         switch (extension) {
107756             case ".ts" /* Ts */:
107757             case ".d.ts" /* Dts */:
107758                 // These are always allowed.
107759                 return undefined;
107760             case ".tsx" /* Tsx */:
107761                 return needJsx();
107762             case ".jsx" /* Jsx */:
107763                 return needJsx() || needAllowJs();
107764             case ".js" /* Js */:
107765                 return needAllowJs();
107766             case ".json" /* Json */:
107767                 return needResolveJsonModule();
107768         }
107769         function needJsx() {
107770             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
107771         }
107772         function needAllowJs() {
107773             return ts.getAllowJSCompilerOption(options) || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
107774         }
107775         function needResolveJsonModule() {
107776             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
107777         }
107778     }
107779     ts.getResolutionDiagnostic = getResolutionDiagnostic;
107780     function getModuleNames(_a) {
107781         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
107782         var res = imports.map(function (i) { return i.text; });
107783         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
107784             var aug = moduleAugmentations_1[_i];
107785             if (aug.kind === 10 /* StringLiteral */) {
107786                 res.push(aug.text);
107787             }
107788             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
107789         }
107790         return res;
107791     }
107792 })(ts || (ts = {}));
107793 /*@internal*/
107794 var ts;
107795 (function (ts) {
107796     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
107797         var outputFiles = [];
107798         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
107799         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
107800         function writeFile(fileName, text, writeByteOrderMark) {
107801             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
107802         }
107803     }
107804     ts.getFileEmitOutput = getFileEmitOutput;
107805     var BuilderState;
107806     (function (BuilderState) {
107807         /**
107808          * Get the referencedFile from the imported module symbol
107809          */
107810         function getReferencedFileFromImportedModuleSymbol(symbol) {
107811             if (symbol.declarations && symbol.declarations[0]) {
107812                 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
107813                 return declarationSourceFile && declarationSourceFile.resolvedPath;
107814             }
107815         }
107816         /**
107817          * Get the referencedFile from the import name node from file
107818          */
107819         function getReferencedFileFromImportLiteral(checker, importName) {
107820             var symbol = checker.getSymbolAtLocation(importName);
107821             return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
107822         }
107823         /**
107824          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
107825          */
107826         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
107827             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
107828         }
107829         /**
107830          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
107831          */
107832         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
107833             var referencedFiles;
107834             // We need to use a set here since the code can contain the same import twice,
107835             // but that will only be one dependency.
107836             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
107837             if (sourceFile.imports && sourceFile.imports.length > 0) {
107838                 var checker = program.getTypeChecker();
107839                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
107840                     var importName = _a[_i];
107841                     var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
107842                     if (declarationSourceFilePath) {
107843                         addReferencedFile(declarationSourceFilePath);
107844                     }
107845                 }
107846             }
107847             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
107848             // Handle triple slash references
107849             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
107850                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
107851                     var referencedFile = _c[_b];
107852                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
107853                     addReferencedFile(referencedPath);
107854                 }
107855             }
107856             // Handle type reference directives
107857             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
107858                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
107859                     if (!resolvedTypeReferenceDirective) {
107860                         return;
107861                     }
107862                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
107863                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
107864                     addReferencedFile(typeFilePath);
107865                 });
107866             }
107867             // Add module augmentation as references
107868             if (sourceFile.moduleAugmentations.length) {
107869                 var checker = program.getTypeChecker();
107870                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
107871                     var moduleName = _e[_d];
107872                     if (!ts.isStringLiteral(moduleName)) {
107873                         continue;
107874                     }
107875                     var symbol = checker.getSymbolAtLocation(moduleName);
107876                     if (!symbol) {
107877                         continue;
107878                     }
107879                     // Add any file other than our own as reference
107880                     addReferenceFromAmbientModule(symbol);
107881                 }
107882             }
107883             // From ambient modules
107884             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
107885                 var ambientModule = _g[_f];
107886                 if (ambientModule.declarations.length > 1) {
107887                     addReferenceFromAmbientModule(ambientModule);
107888                 }
107889             }
107890             return referencedFiles;
107891             function addReferenceFromAmbientModule(symbol) {
107892                 // Add any file other than our own as reference
107893                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
107894                     var declaration = _a[_i];
107895                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
107896                     if (declarationSourceFile &&
107897                         declarationSourceFile !== sourceFile) {
107898                         addReferencedFile(declarationSourceFile.resolvedPath);
107899                     }
107900                 }
107901             }
107902             function addReferencedFile(referencedPath) {
107903                 (referencedFiles || (referencedFiles = new ts.Set())).add(referencedPath);
107904             }
107905         }
107906         /**
107907          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
107908          */
107909         function canReuseOldState(newReferencedMap, oldState) {
107910             return oldState && !oldState.referencedMap === !newReferencedMap;
107911         }
107912         BuilderState.canReuseOldState = canReuseOldState;
107913         /**
107914          * Creates the state of file references and signature for the new program from oldState if it is safe
107915          */
107916         function create(newProgram, getCanonicalFileName, oldState) {
107917             var fileInfos = new ts.Map();
107918             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined;
107919             var exportedModulesMap = referencedMap ? new ts.Map() : undefined;
107920             var hasCalledUpdateShapeSignature = new ts.Set();
107921             var useOldState = canReuseOldState(referencedMap, oldState);
107922             // Ensure source files have parent pointers set
107923             newProgram.getTypeChecker();
107924             // Create the reference map, and set the file infos
107925             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
107926                 var sourceFile = _a[_i];
107927                 var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
107928                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
107929                 if (referencedMap) {
107930                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
107931                     if (newReferences) {
107932                         referencedMap.set(sourceFile.resolvedPath, newReferences);
107933                     }
107934                     // Copy old visible to outside files map
107935                     if (useOldState) {
107936                         var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
107937                         if (exportedModules) {
107938                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
107939                         }
107940                     }
107941                 }
107942                 fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
107943             }
107944             return {
107945                 fileInfos: fileInfos,
107946                 referencedMap: referencedMap,
107947                 exportedModulesMap: exportedModulesMap,
107948                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
107949             };
107950         }
107951         BuilderState.create = create;
107952         /**
107953          * Releases needed properties
107954          */
107955         function releaseCache(state) {
107956             state.allFilesExcludingDefaultLibraryFile = undefined;
107957             state.allFileNames = undefined;
107958         }
107959         BuilderState.releaseCache = releaseCache;
107960         /**
107961          * Creates a clone of the state
107962          */
107963         function clone(state) {
107964             // Dont need to backup allFiles info since its cache anyway
107965             return {
107966                 fileInfos: new ts.Map(state.fileInfos),
107967                 referencedMap: state.referencedMap && new ts.Map(state.referencedMap),
107968                 exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap),
107969                 hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature),
107970             };
107971         }
107972         BuilderState.clone = clone;
107973         /**
107974          * Gets the files affected by the path from the program
107975          */
107976         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
107977             // Since the operation could be cancelled, the signatures are always stored in the cache
107978             // They will be committed once it is safe to use them
107979             // eg when calling this api from tsserver, if there is no cancellation of the operation
107980             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
107981             var signatureCache = cacheToUpdateSignature || new ts.Map();
107982             var sourceFile = programOfThisState.getSourceFileByPath(path);
107983             if (!sourceFile) {
107984                 return ts.emptyArray;
107985             }
107986             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
107987                 return [sourceFile];
107988             }
107989             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
107990             if (!cacheToUpdateSignature) {
107991                 // Commit all the signatures in the signature cache
107992                 updateSignaturesFromCache(state, signatureCache);
107993             }
107994             return result;
107995         }
107996         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
107997         /**
107998          * Updates the signatures from the cache into state's fileinfo signatures
107999          * This should be called whenever it is safe to commit the state of the builder
108000          */
108001         function updateSignaturesFromCache(state, signatureCache) {
108002             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
108003         }
108004         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
108005         function updateSignatureOfFile(state, signature, path) {
108006             state.fileInfos.get(path).signature = signature;
108007             state.hasCalledUpdateShapeSignature.add(path);
108008         }
108009         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
108010         /**
108011          * Returns if the shape of the signature has changed since last emit
108012          */
108013         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
108014             ts.Debug.assert(!!sourceFile);
108015             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
108016             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
108017             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
108018                 return false;
108019             }
108020             var info = state.fileInfos.get(sourceFile.resolvedPath);
108021             if (!info)
108022                 return ts.Debug.fail();
108023             var prevSignature = info.signature;
108024             var latestSignature;
108025             if (sourceFile.isDeclarationFile) {
108026                 latestSignature = sourceFile.version;
108027                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
108028                     // All the references in this file are exported
108029                     var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
108030                     exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
108031                 }
108032             }
108033             else {
108034                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
108035                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
108036                 /*customTransformers*/ undefined, 
108037                 /*forceDtsEmit*/ true);
108038                 var firstDts_1 = emitOutput_1.outputFiles &&
108039                     programOfThisState.getCompilerOptions().declarationMap ?
108040                     emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
108041                     emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
108042                 if (firstDts_1) {
108043                     ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts" /* Dts */), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); });
108044                     latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text);
108045                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
108046                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
108047                     }
108048                 }
108049                 else {
108050                     latestSignature = prevSignature; // TODO: GH#18217
108051                 }
108052             }
108053             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
108054             return !prevSignature || latestSignature !== prevSignature;
108055         }
108056         BuilderState.updateShapeSignature = updateShapeSignature;
108057         /**
108058          * Coverts the declaration emit result into exported modules map
108059          */
108060         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
108061             if (!exportedModulesFromDeclarationEmit) {
108062                 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
108063                 return;
108064             }
108065             var exportedModules;
108066             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
108067             exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
108068             function addExportedModule(exportedModulePath) {
108069                 if (exportedModulePath) {
108070                     if (!exportedModules) {
108071                         exportedModules = new ts.Set();
108072                     }
108073                     exportedModules.add(exportedModulePath);
108074                 }
108075             }
108076         }
108077         /**
108078          * Updates the exported modules from cache into state's exported modules map
108079          * This should be called whenever it is safe to commit the state of the builder
108080          */
108081         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
108082             if (exportedModulesMapCache) {
108083                 ts.Debug.assert(!!state.exportedModulesMap);
108084                 exportedModulesMapCache.forEach(function (exportedModules, path) {
108085                     if (exportedModules) {
108086                         state.exportedModulesMap.set(path, exportedModules);
108087                     }
108088                     else {
108089                         state.exportedModulesMap.delete(path);
108090                     }
108091                 });
108092             }
108093         }
108094         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
108095         /**
108096          * Get all the dependencies of the sourceFile
108097          */
108098         function getAllDependencies(state, programOfThisState, sourceFile) {
108099             var compilerOptions = programOfThisState.getCompilerOptions();
108100             // With --out or --outFile all outputs go into single file, all files depend on each other
108101             if (ts.outFile(compilerOptions)) {
108102                 return getAllFileNames(state, programOfThisState);
108103             }
108104             // If this is non module emit, or its a global file, it depends on all the source files
108105             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
108106                 return getAllFileNames(state, programOfThisState);
108107             }
108108             // Get the references, traversing deep from the referenceMap
108109             var seenMap = new ts.Set();
108110             var queue = [sourceFile.resolvedPath];
108111             while (queue.length) {
108112                 var path = queue.pop();
108113                 if (!seenMap.has(path)) {
108114                     seenMap.add(path);
108115                     var references = state.referencedMap.get(path);
108116                     if (references) {
108117                         var iterator = references.keys();
108118                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
108119                             queue.push(iterResult.value);
108120                         }
108121                     }
108122                 }
108123             }
108124             return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { var _a, _b; return (_b = (_a = programOfThisState.getSourceFileByPath(path)) === null || _a === void 0 ? void 0 : _a.fileName) !== null && _b !== void 0 ? _b : path; }));
108125         }
108126         BuilderState.getAllDependencies = getAllDependencies;
108127         /**
108128          * Gets the names of all files from the program
108129          */
108130         function getAllFileNames(state, programOfThisState) {
108131             if (!state.allFileNames) {
108132                 var sourceFiles = programOfThisState.getSourceFiles();
108133                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
108134             }
108135             return state.allFileNames;
108136         }
108137         /**
108138          * Gets the files referenced by the the file path
108139          */
108140         function getReferencedByPaths(state, referencedFilePath) {
108141             return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
108142                 var filePath = _a[0], referencesInFile = _a[1];
108143                 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
108144             }));
108145         }
108146         BuilderState.getReferencedByPaths = getReferencedByPaths;
108147         /**
108148          * For script files that contains only ambient external modules, although they are not actually external module files,
108149          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
108150          * there are no point to rebuild all script files if these special files have changed. However, if any statement
108151          * in the file is not ambient external module, we treat it as a regular script file.
108152          */
108153         function containsOnlyAmbientModules(sourceFile) {
108154             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
108155                 var statement = _a[_i];
108156                 if (!ts.isModuleWithStringLiteralName(statement)) {
108157                     return false;
108158                 }
108159             }
108160             return true;
108161         }
108162         /**
108163          * Return true if file contains anything that augments to global scope we need to build them as if
108164          * they are global files as well as module
108165          */
108166         function containsGlobalScopeAugmentation(sourceFile) {
108167             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
108168         }
108169         /**
108170          * Return true if the file will invalidate all files because it affectes global scope
108171          */
108172         function isFileAffectingGlobalScope(sourceFile) {
108173             return containsGlobalScopeAugmentation(sourceFile) ||
108174                 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
108175         }
108176         /**
108177          * Gets all files of the program excluding the default library file
108178          */
108179         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
108180             // Use cached result
108181             if (state.allFilesExcludingDefaultLibraryFile) {
108182                 return state.allFilesExcludingDefaultLibraryFile;
108183             }
108184             var result;
108185             if (firstSourceFile)
108186                 addSourceFile(firstSourceFile);
108187             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
108188                 var sourceFile = _a[_i];
108189                 if (sourceFile !== firstSourceFile) {
108190                     addSourceFile(sourceFile);
108191                 }
108192             }
108193             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
108194             return state.allFilesExcludingDefaultLibraryFile;
108195             function addSourceFile(sourceFile) {
108196                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
108197                     (result || (result = [])).push(sourceFile);
108198                 }
108199             }
108200         }
108201         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
108202         /**
108203          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
108204          */
108205         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
108206             var compilerOptions = programOfThisState.getCompilerOptions();
108207             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
108208             // so returning the file itself is good enough.
108209             if (compilerOptions && ts.outFile(compilerOptions)) {
108210                 return [sourceFileWithUpdatedShape];
108211             }
108212             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
108213         }
108214         /**
108215          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
108216          */
108217         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
108218             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
108219                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
108220             }
108221             var compilerOptions = programOfThisState.getCompilerOptions();
108222             if (compilerOptions && (compilerOptions.isolatedModules || ts.outFile(compilerOptions))) {
108223                 return [sourceFileWithUpdatedShape];
108224             }
108225             // Now we need to if each file in the referencedBy list has a shape change as well.
108226             // Because if so, its own referencedBy files need to be saved as well to make the
108227             // emitting result consistent with files on disk.
108228             var seenFileNamesMap = new ts.Map();
108229             // Start with the paths this file was referenced by
108230             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
108231             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
108232             while (queue.length > 0) {
108233                 var currentPath = queue.pop();
108234                 if (!seenFileNamesMap.has(currentPath)) {
108235                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
108236                     seenFileNamesMap.set(currentPath, currentSourceFile);
108237                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) {
108238                         queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
108239                     }
108240                 }
108241             }
108242             // Return array of values that needs emit
108243             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
108244         }
108245     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
108246 })(ts || (ts = {}));
108247 /*@internal*/
108248 var ts;
108249 (function (ts) {
108250     var BuilderFileEmit;
108251     (function (BuilderFileEmit) {
108252         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
108253         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
108254     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
108255     function hasSameKeys(map1, map2) {
108256         // Has same size and every key is present in both maps
108257         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
108258     }
108259     /**
108260      * Create the state so that we can iterate on changedFiles/affected files
108261      */
108262     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
108263         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
108264         state.program = newProgram;
108265         var compilerOptions = newProgram.getCompilerOptions();
108266         state.compilerOptions = compilerOptions;
108267         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
108268         if (!ts.outFile(compilerOptions)) {
108269             state.semanticDiagnosticsPerFile = new ts.Map();
108270         }
108271         state.changedFilesSet = new ts.Set();
108272         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
108273         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
108274         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
108275             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
108276         if (useOldState) {
108277             // Verify the sanity of old state
108278             if (!oldState.currentChangedFilePath) {
108279                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
108280                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
108281             }
108282             var changedFilesSet = oldState.changedFilesSet;
108283             if (canCopySemanticDiagnostics) {
108284                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
108285             }
108286             // Copy old state's changed files set
108287             changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); });
108288             if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) {
108289                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
108290                 state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind);
108291                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
108292                 state.seenAffectedFiles = new ts.Set();
108293             }
108294         }
108295         // Update changed files and copy semantic diagnostics if we can
108296         var referencedMap = state.referencedMap;
108297         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
108298         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
108299         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
108300         state.fileInfos.forEach(function (info, sourceFilePath) {
108301             var oldInfo;
108302             var newReferences;
108303             // if not using old state, every file is changed
108304             if (!useOldState ||
108305                 // File wasnt present in old state
108306                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
108307                 // versions dont match
108308                 oldInfo.version !== info.version ||
108309                 // Referenced files changed
108310                 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
108311                 // Referenced file was deleted in the new program
108312                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
108313                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
108314                 state.changedFilesSet.add(sourceFilePath);
108315             }
108316             else if (canCopySemanticDiagnostics) {
108317                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
108318                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
108319                     return;
108320                 }
108321                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
108322                     return;
108323                 }
108324                 // Unchanged file copy diagnostics
108325                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
108326                 if (diagnostics) {
108327                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
108328                     if (!state.semanticDiagnosticsFromOldState) {
108329                         state.semanticDiagnosticsFromOldState = new ts.Set();
108330                     }
108331                     state.semanticDiagnosticsFromOldState.add(sourceFilePath);
108332                 }
108333             }
108334         });
108335         // If the global file is removed, add all files as changed
108336         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
108337             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
108338                 .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); });
108339         }
108340         else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
108341             // Add all files to affectedFilesPendingEmit since emit changed
108342             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
108343             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
108344             state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set();
108345         }
108346         state.buildInfoEmitPending = !!state.changedFilesSet.size;
108347         return state;
108348     }
108349     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
108350         if (!diagnostics.length)
108351             return ts.emptyArray;
108352         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
108353         return diagnostics.map(function (diagnostic) {
108354             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
108355             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
108356             result.reportsDeprecated = diagnostic.reportDeprecated;
108357             result.source = diagnostic.source;
108358             result.skippedOn = diagnostic.skippedOn;
108359             var relatedInformation = diagnostic.relatedInformation;
108360             result.relatedInformation = relatedInformation ?
108361                 relatedInformation.length ?
108362                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
108363                     [] :
108364                 undefined;
108365             return result;
108366         });
108367         function toPath(path) {
108368             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
108369         }
108370     }
108371     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
108372         var file = diagnostic.file;
108373         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
108374     }
108375     /**
108376      * Releases program and other related not needed properties
108377      */
108378     function releaseCache(state) {
108379         ts.BuilderState.releaseCache(state);
108380         state.program = undefined;
108381     }
108382     /**
108383      * Creates a clone of the state
108384      */
108385     function cloneBuilderProgramState(state) {
108386         var newState = ts.BuilderState.clone(state);
108387         newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile);
108388         newState.changedFilesSet = new ts.Set(state.changedFilesSet);
108389         newState.affectedFiles = state.affectedFiles;
108390         newState.affectedFilesIndex = state.affectedFilesIndex;
108391         newState.currentChangedFilePath = state.currentChangedFilePath;
108392         newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures);
108393         newState.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap && new ts.Map(state.currentAffectedFilesExportedModulesMap);
108394         newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles);
108395         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
108396         newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState);
108397         newState.program = state.program;
108398         newState.compilerOptions = state.compilerOptions;
108399         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
108400         newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
108401         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
108402         newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles);
108403         newState.programEmitComplete = state.programEmitComplete;
108404         return newState;
108405     }
108406     /**
108407      * Verifies that source file is ok to be used in calls that arent handled by next
108408      */
108409     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
108410         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
108411     }
108412     /**
108413      * This function returns the next affected file to be processed.
108414      * Note that until doneAffected is called it would keep reporting same result
108415      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
108416      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
108417      */
108418     function getNextAffectedFile(state, cancellationToken, computeHash) {
108419         while (true) {
108420             var affectedFiles = state.affectedFiles;
108421             if (affectedFiles) {
108422                 var seenAffectedFiles = state.seenAffectedFiles;
108423                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
108424                 while (affectedFilesIndex < affectedFiles.length) {
108425                     var affectedFile = affectedFiles[affectedFilesIndex];
108426                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
108427                         // Set the next affected file as seen and remove the cached semantic diagnostics
108428                         state.affectedFilesIndex = affectedFilesIndex;
108429                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
108430                         return affectedFile;
108431                     }
108432                     affectedFilesIndex++;
108433                 }
108434                 // Remove the changed file from the change set
108435                 state.changedFilesSet.delete(state.currentChangedFilePath);
108436                 state.currentChangedFilePath = undefined;
108437                 // Commit the changes in file signature
108438                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
108439                 state.currentAffectedFilesSignatures.clear();
108440                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
108441                 state.affectedFiles = undefined;
108442             }
108443             // Get next changed file
108444             var nextKey = state.changedFilesSet.keys().next();
108445             if (nextKey.done) {
108446                 // Done
108447                 return undefined;
108448             }
108449             // With --out or --outFile all outputs go into single file
108450             // so operations are performed directly on program, return program
108451             var program = ts.Debug.checkDefined(state.program);
108452             var compilerOptions = program.getCompilerOptions();
108453             if (ts.outFile(compilerOptions)) {
108454                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
108455                 return program;
108456             }
108457             // Get next batch of affected files
108458             if (!state.currentAffectedFilesSignatures)
108459                 state.currentAffectedFilesSignatures = new ts.Map();
108460             if (state.exportedModulesMap) {
108461                 if (!state.currentAffectedFilesExportedModulesMap)
108462                     state.currentAffectedFilesExportedModulesMap = new ts.Map();
108463             }
108464             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
108465             state.currentChangedFilePath = nextKey.value;
108466             state.affectedFilesIndex = 0;
108467             if (!state.seenAffectedFiles)
108468                 state.seenAffectedFiles = new ts.Set();
108469         }
108470     }
108471     /**
108472      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
108473      */
108474     function getNextAffectedFilePendingEmit(state) {
108475         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
108476         if (affectedFilesPendingEmit) {
108477             var seenEmittedFiles = (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map()));
108478             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
108479                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
108480                 if (affectedFile) {
108481                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
108482                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
108483                     if (seenKind === undefined || seenKind < emitKind) {
108484                         // emit this file
108485                         state.affectedFilesPendingEmitIndex = i;
108486                         return { affectedFile: affectedFile, emitKind: emitKind };
108487                     }
108488                 }
108489             }
108490             state.affectedFilesPendingEmit = undefined;
108491             state.affectedFilesPendingEmitKind = undefined;
108492             state.affectedFilesPendingEmitIndex = undefined;
108493         }
108494         return undefined;
108495     }
108496     /**
108497      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
108498      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
108499      */
108500     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
108501         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
108502         // If affected files is everything except default library, then nothing more to do
108503         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
108504             if (!state.cleanedDiagnosticsOfLibFiles) {
108505                 state.cleanedDiagnosticsOfLibFiles = true;
108506                 var program_1 = ts.Debug.checkDefined(state.program);
108507                 var options_2 = program_1.getCompilerOptions();
108508                 ts.forEach(program_1.getSourceFiles(), function (f) {
108509                     return program_1.isSourceFileDefaultLibrary(f) &&
108510                         !ts.skipTypeChecking(f, options_2, program_1) &&
108511                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
108512                 });
108513             }
108514             return;
108515         }
108516         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
108517             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
108518         }
108519     }
108520     /**
108521      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
108522      * Also we need to make sure signature is updated for these files
108523      */
108524     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
108525         removeSemanticDiagnosticsOf(state, path);
108526         if (!state.changedFilesSet.has(path)) {
108527             var program = ts.Debug.checkDefined(state.program);
108528             var sourceFile = program.getSourceFileByPath(path);
108529             if (sourceFile) {
108530                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
108531                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
108532                 // This ensures that we dont later during incremental builds considering wrong signature.
108533                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
108534                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
108535                 // If not dts emit, nothing more to do
108536                 if (ts.getEmitDeclarations(state.compilerOptions)) {
108537                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
108538                 }
108539             }
108540         }
108541         return false;
108542     }
108543     /**
108544      * Removes semantic diagnostics for path and
108545      * returns true if there are no more semantic diagnostics from the old state
108546      */
108547     function removeSemanticDiagnosticsOf(state, path) {
108548         if (!state.semanticDiagnosticsFromOldState) {
108549             return true;
108550         }
108551         state.semanticDiagnosticsFromOldState.delete(path);
108552         state.semanticDiagnosticsPerFile.delete(path);
108553         return !state.semanticDiagnosticsFromOldState.size;
108554     }
108555     function isChangedSignature(state, path) {
108556         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
108557         var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
108558         return newSignature !== oldSignature;
108559     }
108560     /**
108561      * Iterate on referencing modules that export entities from affected file
108562      */
108563     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
108564         // If there was change in signature (dts output) for the changed file,
108565         // then only we need to handle pending file emit
108566         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
108567             return;
108568         }
108569         if (!isChangedSignature(state, affectedFile.resolvedPath))
108570             return;
108571         // Since isolated modules dont change js files, files affected by change in signature is itself
108572         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
108573         if (state.compilerOptions.isolatedModules) {
108574             var seenFileNamesMap = new ts.Map();
108575             seenFileNamesMap.set(affectedFile.resolvedPath, true);
108576             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
108577             while (queue.length > 0) {
108578                 var currentPath = queue.pop();
108579                 if (!seenFileNamesMap.has(currentPath)) {
108580                     seenFileNamesMap.set(currentPath, true);
108581                     var result = fn(state, currentPath);
108582                     if (result && isChangedSignature(state, currentPath)) {
108583                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
108584                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
108585                     }
108586                 }
108587             }
108588         }
108589         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
108590         var seenFileAndExportsOfFile = new ts.Set();
108591         // Go through exported modules from cache first
108592         // If exported modules has path, all files referencing file exported from are affected
108593         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
108594             return exportedModules &&
108595                 exportedModules.has(affectedFile.resolvedPath) &&
108596                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
108597         })) {
108598             return;
108599         }
108600         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
108601         ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
108602             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
108603                 exportedModules.has(affectedFile.resolvedPath) &&
108604                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
108605         });
108606     }
108607     /**
108608      * Iterate on files referencing referencedPath
108609      */
108610     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
108611         return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
108612             return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
108613         });
108614     }
108615     /**
108616      * fn on file and iterate on anything that exports this file
108617      */
108618     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
108619         if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) {
108620             return false;
108621         }
108622         if (fn(state, filePath)) {
108623             // If there are no more diagnostics from old cache, done
108624             return true;
108625         }
108626         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
108627         // Go through exported modules from cache first
108628         // If exported modules has path, all files referencing file exported from are affected
108629         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
108630             return exportedModules &&
108631                 exportedModules.has(filePath) &&
108632                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
108633         })) {
108634             return true;
108635         }
108636         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
108637         if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
108638             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
108639                 exportedModules.has(filePath) &&
108640                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
108641         })) {
108642             return true;
108643         }
108644         // Remove diagnostics of files that import this file (without going to exports of referencing files)
108645         return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
108646             return referencesInFile.has(filePath) &&
108647                 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
108648                 fn(state, referencingFilePath);
108649         } // Dont add to seen since this is not yet done with the export removal
108650         );
108651     }
108652     /**
108653      * This is called after completing operation on the next affected file.
108654      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
108655      */
108656     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
108657         if (isBuildInfoEmit) {
108658             state.buildInfoEmitPending = false;
108659         }
108660         else if (affected === state.program) {
108661             state.changedFilesSet.clear();
108662             state.programEmitComplete = true;
108663         }
108664         else {
108665             state.seenAffectedFiles.add(affected.resolvedPath);
108666             if (emitKind !== undefined) {
108667                 (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind);
108668             }
108669             if (isPendingEmit) {
108670                 state.affectedFilesPendingEmitIndex++;
108671                 state.buildInfoEmitPending = true;
108672             }
108673             else {
108674                 state.affectedFilesIndex++;
108675             }
108676         }
108677     }
108678     /**
108679      * Returns the result with affected file
108680      */
108681     function toAffectedFileResult(state, result, affected) {
108682         doneWithAffectedFile(state, affected);
108683         return { result: result, affected: affected };
108684     }
108685     /**
108686      * Returns the result with affected file
108687      */
108688     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
108689         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
108690         return { result: result, affected: affected };
108691     }
108692     /**
108693      * Gets semantic diagnostics for the file which are
108694      * bindAndCheckDiagnostics (from cache) and program diagnostics
108695      */
108696     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
108697         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
108698     }
108699     /**
108700      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
108701      * Note that it is assumed that when asked about binder and checker diagnostics, the file has been taken out of affected files/changed file set
108702      */
108703     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
108704         var path = sourceFile.resolvedPath;
108705         if (state.semanticDiagnosticsPerFile) {
108706             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
108707             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
108708             if (cachedDiagnostics) {
108709                 return ts.filterSemanticDiagnotics(cachedDiagnostics, state.compilerOptions);
108710             }
108711         }
108712         // Diagnostics werent cached, get them from program, and cache the result
108713         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
108714         if (state.semanticDiagnosticsPerFile) {
108715             state.semanticDiagnosticsPerFile.set(path, diagnostics);
108716         }
108717         return ts.filterSemanticDiagnotics(diagnostics, state.compilerOptions);
108718     }
108719     /**
108720      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
108721      */
108722     function getProgramBuildInfo(state, getCanonicalFileName) {
108723         if (ts.outFile(state.compilerOptions))
108724             return undefined;
108725         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
108726         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
108727         var fileInfos = {};
108728         state.fileInfos.forEach(function (value, key) {
108729             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
108730             fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
108731         });
108732         var result = {
108733             fileInfos: fileInfos,
108734             options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
108735         };
108736         if (state.referencedMap) {
108737             var referencedMap = {};
108738             for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
108739                 var key = _a[_i];
108740                 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
108741             }
108742             result.referencedMap = referencedMap;
108743         }
108744         if (state.exportedModulesMap) {
108745             var exportedModulesMap = {};
108746             for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
108747                 var key = _c[_b];
108748                 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
108749                 // Not in temporary cache, use existing value
108750                 if (newValue === undefined)
108751                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
108752                 // Value in cache and has updated value map, use that
108753                 else if (newValue)
108754                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
108755             }
108756             result.exportedModulesMap = exportedModulesMap;
108757         }
108758         if (state.semanticDiagnosticsPerFile) {
108759             var semanticDiagnosticsPerFile = [];
108760             for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
108761                 var key = _e[_d];
108762                 var value = state.semanticDiagnosticsPerFile.get(key);
108763                 semanticDiagnosticsPerFile.push(value.length ?
108764                     [
108765                         relativeToBuildInfo(key),
108766                         state.hasReusableDiagnostic ?
108767                             value :
108768                             convertToReusableDiagnostics(value, relativeToBuildInfo)
108769                     ] :
108770                     relativeToBuildInfo(key));
108771             }
108772             result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
108773         }
108774         if (state.affectedFilesPendingEmit) {
108775             var affectedFilesPendingEmit = [];
108776             var seenFiles = new ts.Set();
108777             for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) {
108778                 var path = _g[_f];
108779                 if (ts.tryAddToSet(seenFiles, path)) {
108780                     affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]);
108781                 }
108782             }
108783             result.affectedFilesPendingEmit = affectedFilesPendingEmit;
108784         }
108785         return result;
108786         function relativeToBuildInfoEnsuringAbsolutePath(path) {
108787             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
108788         }
108789         function relativeToBuildInfo(path) {
108790             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
108791         }
108792     }
108793     function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
108794         var result = {};
108795         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
108796         for (var name in options) {
108797             if (ts.hasProperty(options, name)) {
108798                 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
108799             }
108800         }
108801         if (result.configFilePath) {
108802             result.configFilePath = relativeToBuildInfo(result.configFilePath);
108803         }
108804         return result;
108805     }
108806     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
108807         if (option) {
108808             if (option.type === "list") {
108809                 var values = value;
108810                 if (option.element.isFilePath && values.length) {
108811                     return values.map(relativeToBuildInfo);
108812                 }
108813             }
108814             else if (option.isFilePath) {
108815                 return relativeToBuildInfo(value);
108816             }
108817         }
108818         return value;
108819     }
108820     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
108821         ts.Debug.assert(!!diagnostics.length);
108822         return diagnostics.map(function (diagnostic) {
108823             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
108824             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
108825             result.reportDeprecated = diagnostic.reportsDeprecated;
108826             result.source = diagnostic.source;
108827             result.skippedOn = diagnostic.skippedOn;
108828             var relatedInformation = diagnostic.relatedInformation;
108829             result.relatedInformation = relatedInformation ?
108830                 relatedInformation.length ?
108831                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
108832                     [] :
108833                 undefined;
108834             return result;
108835         });
108836     }
108837     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
108838         var file = diagnostic.file;
108839         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
108840     }
108841     var BuilderProgramKind;
108842     (function (BuilderProgramKind) {
108843         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
108844         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
108845     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
108846     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
108847         var host;
108848         var newProgram;
108849         var oldProgram;
108850         if (newProgramOrRootNames === undefined) {
108851             ts.Debug.assert(hostOrOptions === undefined);
108852             host = oldProgramOrHost;
108853             oldProgram = configFileParsingDiagnosticsOrOldProgram;
108854             ts.Debug.assert(!!oldProgram);
108855             newProgram = oldProgram.getProgram();
108856         }
108857         else if (ts.isArray(newProgramOrRootNames)) {
108858             oldProgram = configFileParsingDiagnosticsOrOldProgram;
108859             newProgram = ts.createProgram({
108860                 rootNames: newProgramOrRootNames,
108861                 options: hostOrOptions,
108862                 host: oldProgramOrHost,
108863                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
108864                 configFileParsingDiagnostics: configFileParsingDiagnostics,
108865                 projectReferences: projectReferences
108866             });
108867             host = oldProgramOrHost;
108868         }
108869         else {
108870             newProgram = newProgramOrRootNames;
108871             host = hostOrOptions;
108872             oldProgram = oldProgramOrHost;
108873             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
108874         }
108875         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
108876     }
108877     ts.getBuilderCreationParameters = getBuilderCreationParameters;
108878     function createBuilderProgram(kind, _a) {
108879         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
108880         // Return same program if underlying program doesnt change
108881         var oldState = oldProgram && oldProgram.getState();
108882         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
108883             newProgram = undefined; // TODO: GH#18217
108884             oldState = undefined;
108885             return oldProgram;
108886         }
108887         /**
108888          * Create the canonical file name for identity
108889          */
108890         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
108891         /**
108892          * Computing hash to for signature verification
108893          */
108894         var computeHash = ts.maybeBind(host, host.createHash);
108895         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
108896         var backupState;
108897         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
108898         // To ensure that we arent storing any references to old program or new program without state
108899         newProgram = undefined; // TODO: GH#18217
108900         oldProgram = undefined;
108901         oldState = undefined;
108902         var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
108903         builderProgram.getState = function () { return state; };
108904         builderProgram.backupState = function () {
108905             ts.Debug.assert(backupState === undefined);
108906             backupState = cloneBuilderProgramState(state);
108907         };
108908         builderProgram.restoreState = function () {
108909             state = ts.Debug.checkDefined(backupState);
108910             backupState = undefined;
108911         };
108912         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
108913         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
108914         builderProgram.emit = emit;
108915         builderProgram.releaseProgram = function () {
108916             releaseCache(state);
108917             backupState = undefined;
108918         };
108919         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
108920             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
108921         }
108922         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
108923             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
108924             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
108925             builderProgram.emitBuildInfo = emitBuildInfo;
108926         }
108927         else {
108928             ts.notImplemented();
108929         }
108930         return builderProgram;
108931         function emitBuildInfo(writeFile, cancellationToken) {
108932             if (state.buildInfoEmitPending) {
108933                 var result = ts.Debug.checkDefined(state.program).emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken);
108934                 state.buildInfoEmitPending = false;
108935                 return result;
108936             }
108937             return ts.emitSkippedWithNoDiagnostics;
108938         }
108939         /**
108940          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
108941          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
108942          * in that order would be used to write the files
108943          */
108944         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
108945             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
108946             var emitKind = 1 /* Full */;
108947             var isPendingEmitFile = false;
108948             if (!affected) {
108949                 if (!ts.outFile(state.compilerOptions)) {
108950                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
108951                     if (!pendingAffectedFile) {
108952                         if (!state.buildInfoEmitPending) {
108953                             return undefined;
108954                         }
108955                         var affected_1 = ts.Debug.checkDefined(state.program);
108956                         return toAffectedFileEmitResult(state, 
108957                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
108958                         // Otherwise just affected file
108959                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
108960                         /*isPendingEmitFile*/ false, 
108961                         /*isBuildInfoEmit*/ true);
108962                     }
108963                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
108964                     isPendingEmitFile = true;
108965                 }
108966                 else {
108967                     var program = ts.Debug.checkDefined(state.program);
108968                     if (state.programEmitComplete)
108969                         return undefined;
108970                     affected = program;
108971                 }
108972             }
108973             return toAffectedFileEmitResult(state, 
108974             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
108975             // Otherwise just affected file
108976             ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile);
108977         }
108978         /**
108979          * Emits the JavaScript and declaration files.
108980          * When targetSource file is specified, emits the files corresponding to that source file,
108981          * otherwise for the whole program.
108982          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
108983          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
108984          * it will only emit all the affected files instead of whole program
108985          *
108986          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
108987          * in that order would be used to write the files
108988          */
108989         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
108990             var restorePendingEmitOnHandlingNoEmitSuccess = false;
108991             var savedAffectedFilesPendingEmit;
108992             var savedAffectedFilesPendingEmitKind;
108993             var savedAffectedFilesPendingEmitIndex;
108994             // Backup and restore affected pendings emit state for non emit Builder if noEmitOnError is enabled and emitBuildInfo could be written in case there are errors
108995             // This ensures pending files to emit is updated in tsbuildinfo
108996             // Note that when there are no errors, emit proceeds as if everything is emitted as it is callers reponsibility to write the files to disk if at all (because its builder that doesnt track files to emit)
108997             if (kind !== BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram &&
108998                 !targetSourceFile &&
108999                 !ts.outFile(state.compilerOptions) &&
109000                 !state.compilerOptions.noEmit &&
109001                 state.compilerOptions.noEmitOnError) {
109002                 restorePendingEmitOnHandlingNoEmitSuccess = true;
109003                 savedAffectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
109004                 savedAffectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
109005                 savedAffectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
109006             }
109007             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
109008                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
109009             }
109010             var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, writeFile, cancellationToken);
109011             if (result)
109012                 return result;
109013             if (restorePendingEmitOnHandlingNoEmitSuccess) {
109014                 state.affectedFilesPendingEmit = savedAffectedFilesPendingEmit;
109015                 state.affectedFilesPendingEmitKind = savedAffectedFilesPendingEmitKind;
109016                 state.affectedFilesPendingEmitIndex = savedAffectedFilesPendingEmitIndex;
109017             }
109018             // Emit only affected files if using builder for emit
109019             if (!targetSourceFile && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
109020                 // Emit and report any errors we ran into.
109021                 var sourceMaps = [];
109022                 var emitSkipped = false;
109023                 var diagnostics = void 0;
109024                 var emittedFiles = [];
109025                 var affectedEmitResult = void 0;
109026                 while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
109027                     emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
109028                     diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
109029                     emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
109030                     sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
109031                 }
109032                 return {
109033                     emitSkipped: emitSkipped,
109034                     diagnostics: diagnostics || ts.emptyArray,
109035                     emittedFiles: emittedFiles,
109036                     sourceMaps: sourceMaps
109037                 };
109038             }
109039             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
109040         }
109041         /**
109042          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
109043          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
109044          */
109045         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
109046             while (true) {
109047                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
109048                 if (!affected) {
109049                     // Done
109050                     return undefined;
109051                 }
109052                 else if (affected === state.program) {
109053                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
109054                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
109055                 }
109056                 // Add file to affected file pending emit to handle for later emit time
109057                 // Apart for emit builder do this for tsbuildinfo, do this for non emit builder when noEmit is set as tsbuildinfo is written and reused between emitters
109058                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram || state.compilerOptions.noEmit || state.compilerOptions.noEmitOnError) {
109059                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
109060                 }
109061                 // Get diagnostics for the affected file if its not ignored
109062                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
109063                     // Get next affected file
109064                     doneWithAffectedFile(state, affected);
109065                     continue;
109066                 }
109067                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
109068             }
109069         }
109070         /**
109071          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
109072          * The semantic diagnostics are cached and managed here
109073          * Note that it is assumed that when asked about semantic diagnostics through this API,
109074          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
109075          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
109076          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
109077          */
109078         function getSemanticDiagnostics(sourceFile, cancellationToken) {
109079             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
109080             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
109081             if (ts.outFile(compilerOptions)) {
109082                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
109083                 // We dont need to cache the diagnostics just return them from program
109084                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
109085             }
109086             if (sourceFile) {
109087                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
109088             }
109089             // When semantic builder asks for diagnostics of the whole program,
109090             // ensure that all the affected files are handled
109091             // eslint-disable-next-line no-empty
109092             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
109093             }
109094             var diagnostics;
109095             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
109096                 var sourceFile_1 = _a[_i];
109097                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
109098             }
109099             return diagnostics || ts.emptyArray;
109100         }
109101     }
109102     ts.createBuilderProgram = createBuilderProgram;
109103     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
109104         if (!state.affectedFilesPendingEmit)
109105             state.affectedFilesPendingEmit = [];
109106         if (!state.affectedFilesPendingEmitKind)
109107             state.affectedFilesPendingEmitKind = new ts.Map();
109108         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
109109         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
109110         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
109111         // affectedFilesPendingEmitIndex === undefined
109112         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
109113         //   so start from 0 as array would be affectedFilesPendingEmit
109114         // else, continue to iterate from existing index, the current set is appended to existing files
109115         if (state.affectedFilesPendingEmitIndex === undefined) {
109116             state.affectedFilesPendingEmitIndex = 0;
109117         }
109118     }
109119     function getMapOfReferencedSet(mapLike, toPath) {
109120         if (!mapLike)
109121             return undefined;
109122         var map = new ts.Map();
109123         // Copies keys/values from template. Note that for..in will not throw if
109124         // template is undefined, and instead will just exit the loop.
109125         for (var key in mapLike) {
109126             if (ts.hasProperty(mapLike, key)) {
109127                 map.set(toPath(key), new ts.Set(mapLike[key].map(toPath)));
109128             }
109129         }
109130         return map;
109131     }
109132     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
109133         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
109134         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
109135         var fileInfos = new ts.Map();
109136         for (var key in program.fileInfos) {
109137             if (ts.hasProperty(program.fileInfos, key)) {
109138                 fileInfos.set(toPath(key), program.fileInfos[key]);
109139             }
109140         }
109141         var state = {
109142             fileInfos: fileInfos,
109143             compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
109144             referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
109145             exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
109146             semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
109147             hasReusableDiagnostic: true,
109148             affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }),
109149             affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }),
109150             affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0,
109151         };
109152         return {
109153             getState: function () { return state; },
109154             backupState: ts.noop,
109155             restoreState: ts.noop,
109156             getProgram: ts.notImplemented,
109157             getProgramOrUndefined: ts.returnUndefined,
109158             releaseProgram: ts.noop,
109159             getCompilerOptions: function () { return state.compilerOptions; },
109160             getSourceFile: ts.notImplemented,
109161             getSourceFiles: ts.notImplemented,
109162             getOptionsDiagnostics: ts.notImplemented,
109163             getGlobalDiagnostics: ts.notImplemented,
109164             getConfigFileParsingDiagnostics: ts.notImplemented,
109165             getSyntacticDiagnostics: ts.notImplemented,
109166             getDeclarationDiagnostics: ts.notImplemented,
109167             getSemanticDiagnostics: ts.notImplemented,
109168             emit: ts.notImplemented,
109169             getAllDependencies: ts.notImplemented,
109170             getCurrentDirectory: ts.notImplemented,
109171             emitNextAffectedFile: ts.notImplemented,
109172             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
109173             emitBuildInfo: ts.notImplemented,
109174             close: ts.noop,
109175         };
109176         function toPath(path) {
109177             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
109178         }
109179         function toAbsolutePath(path) {
109180             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
109181         }
109182     }
109183     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
109184     function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
109185         return {
109186             getState: ts.notImplemented,
109187             backupState: ts.noop,
109188             restoreState: ts.noop,
109189             getProgram: getProgram,
109190             getProgramOrUndefined: function () { return state.program; },
109191             releaseProgram: function () { return state.program = undefined; },
109192             getCompilerOptions: function () { return state.compilerOptions; },
109193             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
109194             getSourceFiles: function () { return getProgram().getSourceFiles(); },
109195             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
109196             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
109197             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
109198             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
109199             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
109200             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
109201             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
109202             emitBuildInfo: function (writeFile, cancellationToken) { return getProgram().emitBuildInfo(writeFile, cancellationToken); },
109203             getAllDependencies: ts.notImplemented,
109204             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
109205             close: ts.noop,
109206         };
109207         function getProgram() {
109208             return ts.Debug.checkDefined(state.program);
109209         }
109210     }
109211     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
109212 })(ts || (ts = {}));
109213 var ts;
109214 (function (ts) {
109215     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
109216         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
109217     }
109218     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
109219     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
109220         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
109221     }
109222     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
109223     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
109224         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
109225         return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
109226     }
109227     ts.createAbstractBuilder = createAbstractBuilder;
109228 })(ts || (ts = {}));
109229 /*@internal*/
109230 var ts;
109231 (function (ts) {
109232     function removeIgnoredPath(path) {
109233         // Consider whole staging folder as if node_modules changed.
109234         if (ts.endsWith(path, "/node_modules/.staging")) {
109235             return ts.removeSuffix(path, "/.staging");
109236         }
109237         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
109238             undefined :
109239             path;
109240     }
109241     ts.removeIgnoredPath = removeIgnoredPath;
109242     /**
109243      * Filter out paths like
109244      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
109245      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
109246      * @param dirPath
109247      */
109248     function canWatchDirectory(dirPath) {
109249         var rootLength = ts.getRootLength(dirPath);
109250         if (dirPath.length === rootLength) {
109251             // Ignore "/", "c:/"
109252             return false;
109253         }
109254         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
109255         if (nextDirectorySeparator === -1) {
109256             // ignore "/user", "c:/users" or "c:/folderAtRoot"
109257             return false;
109258         }
109259         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
109260         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
109261         if (isNonDirectorySeparatorRoot &&
109262             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
109263             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
109264             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
109265             if (nextDirectorySeparator === -1) {
109266                 // ignore "//vda1cs4850/c$/folderAtRoot"
109267                 return false;
109268             }
109269             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
109270         }
109271         if (isNonDirectorySeparatorRoot &&
109272             pathPartForUserCheck.search(/users\//i) !== 0) {
109273             // Paths like c:/folderAtRoot/subFolder are allowed
109274             return true;
109275         }
109276         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
109277             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
109278             if (searchIndex === 0) {
109279                 // Folder isnt at expected minimum levels
109280                 return false;
109281             }
109282         }
109283         return true;
109284     }
109285     ts.canWatchDirectory = canWatchDirectory;
109286     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
109287         var filesWithChangedSetOfUnresolvedImports;
109288         var filesWithInvalidatedResolutions;
109289         var filesWithInvalidatedNonRelativeUnresolvedImports;
109290         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
109291         var resolutionsWithFailedLookups = [];
109292         var resolvedFileToResolution = ts.createMultiMap();
109293         var hasChangedAutomaticTypeDirectiveNames = false;
109294         var failedLookupChecks = [];
109295         var startsWithPathChecks = [];
109296         var isInDirectoryChecks = [];
109297         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
109298         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
109299         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
109300         // The key in the map is source file's path.
109301         // The values are Map of resolutions with key being name lookedup.
109302         var resolvedModuleNames = new ts.Map();
109303         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
109304         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
109305         var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
109306         var resolvedTypeReferenceDirectives = new ts.Map();
109307         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
109308         /**
109309          * These are the extensions that failed lookup files will have by default,
109310          * any other extension of failed lookup will be store that path in custom failed lookup path
109311          * This helps in not having to comb through all resolutions when files are added/removed
109312          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
109313          */
109314         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
109315         var customFailedLookupPaths = new ts.Map();
109316         var directoryWatchesOfFailedLookups = new ts.Map();
109317         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
109318         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
109319         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
109320         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
109321         var typeRootsWatches = new ts.Map();
109322         return {
109323             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
109324             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
109325             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
109326             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
109327             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
109328             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
109329             resolveModuleNames: resolveModuleNames,
109330             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
109331             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
109332             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
109333             removeResolutionsOfFile: removeResolutionsOfFile,
109334             hasChangedAutomaticTypeDirectiveNames: function () { return hasChangedAutomaticTypeDirectiveNames; },
109335             invalidateResolutionOfFile: invalidateResolutionOfFile,
109336             invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations,
109337             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
109338             createHasInvalidatedResolution: createHasInvalidatedResolution,
109339             updateTypeRootsWatch: updateTypeRootsWatch,
109340             closeTypeRootsWatch: closeTypeRootsWatch,
109341             clear: clear
109342         };
109343         function getResolvedModule(resolution) {
109344             return resolution.resolvedModule;
109345         }
109346         function getResolvedTypeReferenceDirective(resolution) {
109347             return resolution.resolvedTypeReferenceDirective;
109348         }
109349         function isInDirectoryPath(dir, file) {
109350             if (dir === undefined || file.length <= dir.length) {
109351                 return false;
109352             }
109353             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
109354         }
109355         function clear() {
109356             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
109357             customFailedLookupPaths.clear();
109358             nonRelativeExternalModuleResolutions.clear();
109359             closeTypeRootsWatch();
109360             resolvedModuleNames.clear();
109361             resolvedTypeReferenceDirectives.clear();
109362             resolvedFileToResolution.clear();
109363             resolutionsWithFailedLookups.length = 0;
109364             failedLookupChecks.length = 0;
109365             startsWithPathChecks.length = 0;
109366             isInDirectoryChecks.length = 0;
109367             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
109368             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
109369             clearPerDirectoryResolutions();
109370             hasChangedAutomaticTypeDirectiveNames = false;
109371         }
109372         function startRecordingFilesWithChangedResolutions() {
109373             filesWithChangedSetOfUnresolvedImports = [];
109374         }
109375         function finishRecordingFilesWithChangedResolutions() {
109376             var collected = filesWithChangedSetOfUnresolvedImports;
109377             filesWithChangedSetOfUnresolvedImports = undefined;
109378             return collected;
109379         }
109380         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
109381             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
109382                 return false;
109383             }
109384             // Invalidated if file has unresolved imports
109385             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
109386             return !!value && !!value.length;
109387         }
109388         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
109389             // Ensure pending resolutions are applied
109390             invalidateResolutionsOfFailedLookupLocations();
109391             if (forceAllFilesAsInvalidated) {
109392                 // Any file asked would have invalidated resolution
109393                 filesWithInvalidatedResolutions = undefined;
109394                 return ts.returnTrue;
109395             }
109396             var collected = filesWithInvalidatedResolutions;
109397             filesWithInvalidatedResolutions = undefined;
109398             return function (path) { return (!!collected && collected.has(path)) ||
109399                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
109400         }
109401         function clearPerDirectoryResolutions() {
109402             perDirectoryResolvedModuleNames.clear();
109403             nonRelativeModuleNameCache.clear();
109404             perDirectoryResolvedTypeReferenceDirectives.clear();
109405             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
109406             nonRelativeExternalModuleResolutions.clear();
109407         }
109408         function finishCachingPerDirectoryResolution() {
109409             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
109410             clearPerDirectoryResolutions();
109411             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
109412                 if (watcher.refCount === 0) {
109413                     directoryWatchesOfFailedLookups.delete(path);
109414                     watcher.watcher.close();
109415                 }
109416             });
109417             hasChangedAutomaticTypeDirectiveNames = false;
109418         }
109419         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
109420             var _a;
109421             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
109422             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
109423             if (!resolutionHost.getGlobalCache) {
109424                 return primaryResult;
109425             }
109426             // otherwise try to load typings from @types
109427             var globalCache = resolutionHost.getGlobalCache();
109428             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
109429                 // create different collection of failed lookup locations for second pass
109430                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
109431                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
109432                 if (resolvedModule) {
109433                     // Modify existing resolution so its saved in the directory cache as well
109434                     primaryResult.resolvedModule = resolvedModule;
109435                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
109436                     return primaryResult;
109437                 }
109438             }
109439             // Default return the result from the first pass
109440             return primaryResult;
109441         }
109442         function resolveNamesWithLocalCache(_a) {
109443             var _b;
109444             var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges;
109445             var path = resolutionHost.toPath(containingFile);
109446             var resolutionsInFile = cache.get(path) || cache.set(path, new ts.Map()).get(path);
109447             var dirPath = ts.getDirectoryPath(path);
109448             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
109449             var perDirectoryResolution = perDirectoryCache.get(dirPath);
109450             if (!perDirectoryResolution) {
109451                 perDirectoryResolution = new ts.Map();
109452                 perDirectoryCache.set(dirPath, perDirectoryResolution);
109453             }
109454             var resolvedModules = [];
109455             var compilerOptions = resolutionHost.getCompilationSettings();
109456             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
109457             // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
109458             var program = resolutionHost.getCurrentProgram();
109459             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
109460             var unmatchedRedirects = oldRedirect ?
109461                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
109462                 !!redirectedReference;
109463             var seenNamesInFile = new ts.Map();
109464             for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
109465                 var name = names_3[_i];
109466                 var resolution = resolutionsInFile.get(name);
109467                 // Resolution is valid if it is present and not invalidated
109468                 if (!seenNamesInFile.has(name) &&
109469                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
109470                     // If the name is unresolved import that was invalidated, recalculate
109471                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
109472                     var existingResolution = resolution;
109473                     var resolutionInDirectory = perDirectoryResolution.get(name);
109474                     if (resolutionInDirectory) {
109475                         resolution = resolutionInDirectory;
109476                     }
109477                     else {
109478                         resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
109479                         perDirectoryResolution.set(name, resolution);
109480                     }
109481                     resolutionsInFile.set(name, resolution);
109482                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
109483                     if (existingResolution) {
109484                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
109485                     }
109486                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
109487                         filesWithChangedSetOfUnresolvedImports.push(path);
109488                         // reset log changes to avoid recording the same file multiple times
109489                         logChanges = false;
109490                     }
109491                 }
109492                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
109493                 seenNamesInFile.set(name, true);
109494                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
109495             }
109496             // Stop watching and remove the unused name
109497             resolutionsInFile.forEach(function (resolution, name) {
109498                 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
109499                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
109500                     resolutionsInFile.delete(name);
109501                 }
109502             });
109503             return resolvedModules;
109504             function resolutionIsEqualTo(oldResolution, newResolution) {
109505                 if (oldResolution === newResolution) {
109506                     return true;
109507                 }
109508                 if (!oldResolution || !newResolution) {
109509                     return false;
109510                 }
109511                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
109512                 var newResult = getResolutionWithResolvedFileName(newResolution);
109513                 if (oldResult === newResult) {
109514                     return true;
109515                 }
109516                 if (!oldResult || !newResult) {
109517                     return false;
109518                 }
109519                 return oldResult.resolvedFileName === newResult.resolvedFileName;
109520             }
109521         }
109522         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
109523             return resolveNamesWithLocalCache({
109524                 names: typeDirectiveNames,
109525                 containingFile: containingFile,
109526                 redirectedReference: redirectedReference,
109527                 cache: resolvedTypeReferenceDirectives,
109528                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
109529                 loader: ts.resolveTypeReferenceDirective,
109530                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
109531                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
109532             });
109533         }
109534         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
109535             return resolveNamesWithLocalCache({
109536                 names: moduleNames,
109537                 containingFile: containingFile,
109538                 redirectedReference: redirectedReference,
109539                 cache: resolvedModuleNames,
109540                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
109541                 loader: resolveModuleName,
109542                 getResolutionWithResolvedFileName: getResolvedModule,
109543                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
109544                 reusedNames: reusedNames,
109545                 logChanges: logChangesWhenResolvingModule,
109546             });
109547         }
109548         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
109549             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
109550             return cache && cache.get(moduleName);
109551         }
109552         function isNodeModulesAtTypesDirectory(dirPath) {
109553             return ts.endsWith(dirPath, "/node_modules/@types");
109554         }
109555         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
109556             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
109557                 // Ensure failed look up is normalized path
109558                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
109559                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
109560                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
109561                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
109562                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
109563                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
109564                     return {
109565                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
109566                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
109567                     };
109568                 }
109569                 else {
109570                     // Always watch root directory non recursively
109571                     return {
109572                         dir: rootDir,
109573                         dirPath: rootPath,
109574                         nonRecursive: false
109575                     };
109576                 }
109577             }
109578             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
109579         }
109580         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
109581             // If directory path contains node module, get the most parent node_modules directory for watching
109582             while (ts.pathContainsNodeModules(dirPath)) {
109583                 dir = ts.getDirectoryPath(dir);
109584                 dirPath = ts.getDirectoryPath(dirPath);
109585             }
109586             // If the directory is node_modules use it to watch, always watch it recursively
109587             if (ts.isNodeModulesDirectory(dirPath)) {
109588                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
109589             }
109590             var nonRecursive = true;
109591             // Use some ancestor of the root directory
109592             var subDirectoryPath, subDirectory;
109593             if (rootPath !== undefined) {
109594                 while (!isInDirectoryPath(dirPath, rootPath)) {
109595                     var parentPath = ts.getDirectoryPath(dirPath);
109596                     if (parentPath === dirPath) {
109597                         break;
109598                     }
109599                     nonRecursive = false;
109600                     subDirectoryPath = dirPath;
109601                     subDirectory = dir;
109602                     dirPath = parentPath;
109603                     dir = ts.getDirectoryPath(dir);
109604                 }
109605             }
109606             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
109607         }
109608         function isPathWithDefaultFailedLookupExtension(path) {
109609             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
109610         }
109611         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
109612             if (resolution.refCount) {
109613                 resolution.refCount++;
109614                 ts.Debug.assertDefined(resolution.files);
109615             }
109616             else {
109617                 resolution.refCount = 1;
109618                 ts.Debug.assert(ts.length(resolution.files) === 0); // This resolution shouldnt be referenced by any file yet
109619                 if (ts.isExternalModuleNameRelative(name)) {
109620                     watchFailedLookupLocationOfResolution(resolution);
109621                 }
109622                 else {
109623                     nonRelativeExternalModuleResolutions.add(name, resolution);
109624                 }
109625                 var resolved = getResolutionWithResolvedFileName(resolution);
109626                 if (resolved && resolved.resolvedFileName) {
109627                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
109628                 }
109629             }
109630             (resolution.files || (resolution.files = [])).push(filePath);
109631         }
109632         function watchFailedLookupLocationOfResolution(resolution) {
109633             ts.Debug.assert(!!resolution.refCount);
109634             var failedLookupLocations = resolution.failedLookupLocations;
109635             if (!failedLookupLocations.length)
109636                 return;
109637             resolutionsWithFailedLookups.push(resolution);
109638             var setAtRoot = false;
109639             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
109640                 var failedLookupLocation = failedLookupLocations_1[_i];
109641                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
109642                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
109643                 if (toWatch) {
109644                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
109645                     // If the failed lookup location path is not one of the supported extensions,
109646                     // store it in the custom path
109647                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
109648                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
109649                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
109650                     }
109651                     if (dirPath === rootPath) {
109652                         ts.Debug.assert(!nonRecursive);
109653                         setAtRoot = true;
109654                     }
109655                     else {
109656                         setDirectoryWatcher(dir, dirPath, nonRecursive);
109657                     }
109658                 }
109659             }
109660             if (setAtRoot) {
109661                 // This is always non recursive
109662                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
109663             }
109664         }
109665         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
109666             var program = resolutionHost.getCurrentProgram();
109667             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
109668                 resolutions.forEach(watchFailedLookupLocationOfResolution);
109669             }
109670         }
109671         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
109672             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
109673             if (dirWatcher) {
109674                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
109675                 dirWatcher.refCount++;
109676             }
109677             else {
109678                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
109679             }
109680         }
109681         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
109682             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
109683             resolution.refCount--;
109684             if (resolution.refCount) {
109685                 return;
109686             }
109687             var resolved = getResolutionWithResolvedFileName(resolution);
109688             if (resolved && resolved.resolvedFileName) {
109689                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
109690             }
109691             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
109692                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
109693                 return;
109694             }
109695             var failedLookupLocations = resolution.failedLookupLocations;
109696             var removeAtRoot = false;
109697             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
109698                 var failedLookupLocation = failedLookupLocations_2[_i];
109699                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
109700                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
109701                 if (toWatch) {
109702                     var dirPath = toWatch.dirPath;
109703                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
109704                     if (refCount) {
109705                         if (refCount === 1) {
109706                             customFailedLookupPaths.delete(failedLookupLocationPath);
109707                         }
109708                         else {
109709                             ts.Debug.assert(refCount > 1);
109710                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
109711                         }
109712                     }
109713                     if (dirPath === rootPath) {
109714                         removeAtRoot = true;
109715                     }
109716                     else {
109717                         removeDirectoryWatcher(dirPath);
109718                     }
109719                 }
109720             }
109721             if (removeAtRoot) {
109722                 removeDirectoryWatcher(rootPath);
109723             }
109724         }
109725         function removeDirectoryWatcher(dirPath) {
109726             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
109727             // Do not close the watcher yet since it might be needed by other failed lookup locations.
109728             dirWatcher.refCount--;
109729         }
109730         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
109731             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
109732                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
109733                 if (cachedDirectoryStructureHost) {
109734                     // Since the file existence changed, update the sourceFiles cache
109735                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
109736                 }
109737                 scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
109738             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
109739         }
109740         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
109741             // Deleted file, stop watching failed lookups for all the resolutions in the file
109742             var resolutions = cache.get(filePath);
109743             if (resolutions) {
109744                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
109745                 cache.delete(filePath);
109746             }
109747         }
109748         function removeResolutionsFromProjectReferenceRedirects(filePath) {
109749             if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
109750                 return;
109751             }
109752             var program = resolutionHost.getCurrentProgram();
109753             if (!program) {
109754                 return;
109755             }
109756             // If this file is input file for the referenced project, get it
109757             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
109758             if (!resolvedProjectReference) {
109759                 return;
109760             }
109761             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
109762             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
109763         }
109764         function removeResolutionsOfFile(filePath) {
109765             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
109766             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
109767         }
109768         function invalidateResolutions(resolutions, canInvalidate) {
109769             if (!resolutions)
109770                 return false;
109771             var invalidated = false;
109772             for (var _i = 0, resolutions_1 = resolutions; _i < resolutions_1.length; _i++) {
109773                 var resolution = resolutions_1[_i];
109774                 if (resolution.isInvalidated || !canInvalidate(resolution))
109775                     continue;
109776                 resolution.isInvalidated = invalidated = true;
109777                 for (var _a = 0, _b = ts.Debug.assertDefined(resolution.files); _a < _b.length; _a++) {
109778                     var containingFilePath = _b[_a];
109779                     (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath);
109780                     // When its a file with inferred types resolution, invalidate type reference directive resolution
109781                     hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile);
109782                 }
109783             }
109784             return invalidated;
109785         }
109786         function invalidateResolutionOfFile(filePath) {
109787             removeResolutionsOfFile(filePath);
109788             // Resolution is invalidated if the resulting file name is same as the deleted file path
109789             var prevHasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
109790             if (invalidateResolutions(resolvedFileToResolution.get(filePath), ts.returnTrue) &&
109791                 hasChangedAutomaticTypeDirectiveNames &&
109792                 !prevHasChangedAutomaticTypeDirectiveNames) {
109793                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
109794             }
109795         }
109796         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
109797             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
109798             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
109799         }
109800         function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
109801             if (isCreatingWatchedDirectory) {
109802                 // Watching directory is created
109803                 // Invalidate any resolution has failed lookup in this directory
109804                 isInDirectoryChecks.push(fileOrDirectoryPath);
109805             }
109806             else {
109807                 // If something to do with folder/file starting with "." in node_modules folder, skip it
109808                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
109809                 if (!updatedPath)
109810                     return false;
109811                 fileOrDirectoryPath = updatedPath;
109812                 // prevent saving an open file from over-eagerly triggering invalidation
109813                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
109814                     return false;
109815                 }
109816                 // Some file or directory in the watching directory is created
109817                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
109818                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
109819                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
109820                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
109821                     // Invalidate any resolution from this directory
109822                     failedLookupChecks.push(fileOrDirectoryPath);
109823                     startsWithPathChecks.push(fileOrDirectoryPath);
109824                 }
109825                 else {
109826                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
109827                         return false;
109828                     }
109829                     // Ignore emits from the program
109830                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
109831                         return false;
109832                     }
109833                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
109834                     failedLookupChecks.push(fileOrDirectoryPath);
109835                 }
109836             }
109837             resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations();
109838         }
109839         function invalidateResolutionsOfFailedLookupLocations() {
109840             if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) {
109841                 return false;
109842             }
109843             var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution);
109844             failedLookupChecks.length = 0;
109845             startsWithPathChecks.length = 0;
109846             isInDirectoryChecks.length = 0;
109847             return invalidated;
109848         }
109849         function canInvalidateFailedLookupResolution(resolution) {
109850             return resolution.failedLookupLocations.some(function (location) {
109851                 var locationPath = resolutionHost.toPath(location);
109852                 return ts.contains(failedLookupChecks, locationPath) ||
109853                     startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) ||
109854                     isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); });
109855             });
109856         }
109857         function closeTypeRootsWatch() {
109858             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
109859         }
109860         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
109861             if (isInDirectoryPath(rootPath, typeRootPath)) {
109862                 return rootPath;
109863             }
109864             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
109865             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
109866         }
109867         function createTypeRootsWatch(typeRootPath, typeRoot) {
109868             // Create new watch and recursive info
109869             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
109870                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
109871                 if (cachedDirectoryStructureHost) {
109872                     // Since the file existence changed, update the sourceFiles cache
109873                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
109874                 }
109875                 // For now just recompile
109876                 // We could potentially store more data here about whether it was/would be really be used or not
109877                 // and with that determine to trigger compilation but for now this is enough
109878                 hasChangedAutomaticTypeDirectiveNames = true;
109879                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
109880                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
109881                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
109882                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
109883                 if (dirPath) {
109884                     scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
109885                 }
109886             }, 1 /* Recursive */);
109887         }
109888         /**
109889          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
109890          * To be called when compiler options change
109891          */
109892         function updateTypeRootsWatch() {
109893             var options = resolutionHost.getCompilationSettings();
109894             if (options.types) {
109895                 // No need to do any watch since resolution cache is going to handle the failed lookups
109896                 // for the types added by this
109897                 closeTypeRootsWatch();
109898                 return;
109899             }
109900             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
109901             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
109902             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
109903             if (typeRoots) {
109904                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
109905                     createNewValue: createTypeRootsWatch,
109906                     onDeleteValue: ts.closeFileWatcher
109907                 });
109908             }
109909             else {
109910                 closeTypeRootsWatch();
109911             }
109912         }
109913         /**
109914          * Use this function to return if directory exists to get type roots to watch
109915          * If we return directory exists then only the paths will be added to type roots
109916          * Hence return true for all directories except root directories which are filtered from watching
109917          */
109918         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
109919             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
109920             var dirPath = resolutionHost.toPath(dir);
109921             return dirPath === rootPath || canWatchDirectory(dirPath);
109922         }
109923     }
109924     ts.createResolutionCache = createResolutionCache;
109925 })(ts || (ts = {}));
109926 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
109927 /* @internal */
109928 var ts;
109929 (function (ts) {
109930     var moduleSpecifiers;
109931     (function (moduleSpecifiers) {
109932         var RelativePreference;
109933         (function (RelativePreference) {
109934             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
109935             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
109936             RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
109937         })(RelativePreference || (RelativePreference = {}));
109938         // See UserPreferences#importPathEnding
109939         var Ending;
109940         (function (Ending) {
109941             Ending[Ending["Minimal"] = 0] = "Minimal";
109942             Ending[Ending["Index"] = 1] = "Index";
109943             Ending[Ending["JsExtension"] = 2] = "JsExtension";
109944         })(Ending || (Ending = {}));
109945         function getPreferences(_a, compilerOptions, importingSourceFile) {
109946             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
109947             return {
109948                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
109949                 ending: getEnding(),
109950             };
109951             function getEnding() {
109952                 switch (importModuleSpecifierEnding) {
109953                     case "minimal": return 0 /* Minimal */;
109954                     case "index": return 1 /* Index */;
109955                     case "js": return 2 /* JsExtension */;
109956                     default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
109957                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
109958                 }
109959             }
109960         }
109961         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
109962             return {
109963                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
109964                 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
109965                     2 /* JsExtension */ :
109966                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
109967             };
109968         }
109969         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
109970             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
109971             if (res === oldImportSpecifier)
109972                 return undefined;
109973             return res;
109974         }
109975         moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
109976         // Note: importingSourceFile is just for usesJsExtensionOnImports
109977         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
109978             if (preferences === void 0) { preferences = {}; }
109979             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
109980         }
109981         moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
109982         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
109983             var info = getInfo(importingSourceFileName, host);
109984             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
109985             return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions, /*packageNameOnly*/ true); });
109986         }
109987         moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
109988         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
109989             var info = getInfo(importingSourceFileName, host);
109990             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
109991             return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions); }) ||
109992                 getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences);
109993         }
109994         /** Returns an import for each symlink and for the realpath. */
109995         function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
109996             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
109997             if (ambient)
109998                 return [ambient];
109999             var info = getInfo(importingSourceFile.path, host);
110000             var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
110001             var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
110002             var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
110003             var importedFileIsInNodeModules = ts.some(modulePaths, function (p) { return p.isInNodeModules; });
110004             // Module specifier priority:
110005             //   1. "Bare package specifiers" (e.g. "@foo/bar") resulting from a path through node_modules to a package.json's "types" entry
110006             //   2. Specifiers generated using "paths" from tsconfig
110007             //   3. Non-relative specfiers resulting from a path through node_modules (e.g. "@foo/bar/path/to/file")
110008             //   4. Relative paths
110009             var nodeModulesSpecifiers;
110010             var pathsSpecifiers;
110011             var relativeSpecifiers;
110012             for (var _i = 0, modulePaths_1 = modulePaths; _i < modulePaths_1.length; _i++) {
110013                 var modulePath = modulePaths_1[_i];
110014                 var specifier = tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions);
110015                 nodeModulesSpecifiers = ts.append(nodeModulesSpecifiers, specifier);
110016                 if (specifier && modulePath.isRedirect) {
110017                     // If we got a specifier for a redirect, it was a bare package specifier (e.g. "@foo/bar",
110018                     // not "@foo/bar/path/to/file"). No other specifier will be this good, so stop looking.
110019                     return nodeModulesSpecifiers;
110020                 }
110021                 if (!specifier && !modulePath.isRedirect) {
110022                     var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences);
110023                     if (ts.pathIsBareSpecifier(local)) {
110024                         pathsSpecifiers = ts.append(pathsSpecifiers, local);
110025                     }
110026                     else if (!importedFileIsInNodeModules || modulePath.isInNodeModules) {
110027                         // Why this extra conditional, not just an `else`? If some path to the file contained
110028                         // 'node_modules', but we can't create a non-relative specifier (e.g. "@foo/bar/path/to/file"),
110029                         // that means we had to go through a *sibling's* node_modules, not one we can access directly.
110030                         // If some path to the file was in node_modules but another was not, this likely indicates that
110031                         // we have a monorepo structure with symlinks. In this case, the non-node_modules path is
110032                         // probably the realpath, e.g. "../bar/path/to/file", but a relative path to another package
110033                         // in a monorepo is probably not portable. So, the module specifier we actually go with will be
110034                         // the relative path through node_modules, so that the declaration emitter can produce a
110035                         // portability error. (See declarationEmitReexportedSymlinkReference3)
110036                         relativeSpecifiers = ts.append(relativeSpecifiers, local);
110037                     }
110038                 }
110039             }
110040             return (pathsSpecifiers === null || pathsSpecifiers === void 0 ? void 0 : pathsSpecifiers.length) ? pathsSpecifiers :
110041                 (nodeModulesSpecifiers === null || nodeModulesSpecifiers === void 0 ? void 0 : nodeModulesSpecifiers.length) ? nodeModulesSpecifiers :
110042                     ts.Debug.checkDefined(relativeSpecifiers);
110043         }
110044         moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
110045         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
110046         function getInfo(importingSourceFileName, host) {
110047             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
110048             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
110049             return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
110050         }
110051         function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, host, _b) {
110052             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
110053             var ending = _b.ending, relativePreference = _b.relativePreference;
110054             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
110055             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
110056                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
110057             if (!baseUrl && !paths || relativePreference === 0 /* Relative */) {
110058                 return relativePath;
110059             }
110060             var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl;
110061             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName);
110062             if (!relativeToBaseUrl) {
110063                 return relativePath;
110064             }
110065             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
110066             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
110067             var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths;
110068             if (!nonRelative) {
110069                 return relativePath;
110070             }
110071             if (relativePreference === 1 /* NonRelative */) {
110072                 return nonRelative;
110073             }
110074             if (relativePreference !== 2 /* Auto */)
110075                 ts.Debug.assertNever(relativePreference);
110076             // Prefer a relative import over a baseUrl import if it has fewer components.
110077             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
110078         }
110079         function countPathComponents(path) {
110080             var count = 0;
110081             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
110082                 if (path.charCodeAt(i) === 47 /* slash */)
110083                     count++;
110084             }
110085             return count;
110086         }
110087         moduleSpecifiers.countPathComponents = countPathComponents;
110088         function usesJsExtensionOnImports(_a) {
110089             var imports = _a.imports;
110090             return ts.firstDefined(imports, function (_a) {
110091                 var text = _a.text;
110092                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
110093             }) || false;
110094         }
110095         function numberOfDirectorySeparators(str) {
110096             var match = str.match(/\//g);
110097             return match ? match.length : 0;
110098         }
110099         function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) {
110100             return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path));
110101         }
110102         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
110103             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
110104             var cwd = host.getCurrentDirectory();
110105             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
110106             var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
110107             var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
110108             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
110109             if (!preferSymlinks) {
110110                 var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); });
110111                 if (result_15)
110112                     return result_15;
110113             }
110114             var links = host.getSymlinkCache
110115                 ? host.getSymlinkCache()
110116                 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
110117             var symlinkedDirectories = links.getSymlinkedDirectories();
110118             var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames();
110119             var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) {
110120                 if (resolved === false)
110121                     return undefined;
110122                 if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) {
110123                     return undefined; // Don't want to a package to globally import from itself
110124                 }
110125                 return ts.forEach(targets, function (target) {
110126                     if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) {
110127                         return;
110128                     }
110129                     var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName);
110130                     var option = ts.resolvePath(path, relative);
110131                     if (!host.fileExists || host.fileExists(option)) {
110132                         var result_16 = cb(option, target === referenceRedirect);
110133                         if (result_16)
110134                             return result_16;
110135                     }
110136                 });
110137             });
110138             return result ||
110139                 (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined);
110140         }
110141         moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
110142         /**
110143          * Looks for existing imports that use symlinks to this module.
110144          * Symlinks will be returned first so they are preferred over the real path.
110145          */
110146         function getAllModulePaths(importingFileName, importedFileName, host) {
110147             var cwd = host.getCurrentDirectory();
110148             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
110149             var allFileNames = new ts.Map();
110150             var importedFileFromNodeModules = false;
110151             forEachFileNameOfModule(importingFileName, importedFileName, host, 
110152             /*preferSymlinks*/ true, function (path, isRedirect) {
110153                 var isInNodeModules = ts.pathContainsNodeModules(path);
110154                 allFileNames.set(path, { path: getCanonicalFileName(path), isRedirect: isRedirect, isInNodeModules: isInNodeModules });
110155                 importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules;
110156                 // don't return value, so we collect everything
110157             });
110158             // Sort by paths closest to importing file Name directory
110159             var sortedPaths = [];
110160             var _loop_24 = function (directory) {
110161                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
110162                 var pathsInDirectory;
110163                 allFileNames.forEach(function (_a, fileName) {
110164                     var path = _a.path, isRedirect = _a.isRedirect, isInNodeModules = _a.isInNodeModules;
110165                     if (ts.startsWith(path, directoryStart)) {
110166                         (pathsInDirectory || (pathsInDirectory = [])).push({ path: fileName, isRedirect: isRedirect, isInNodeModules: isInNodeModules });
110167                         allFileNames.delete(fileName);
110168                     }
110169                 });
110170                 if (pathsInDirectory) {
110171                     if (pathsInDirectory.length > 1) {
110172                         pathsInDirectory.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
110173                     }
110174                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
110175                 }
110176                 var newDirectory = ts.getDirectoryPath(directory);
110177                 if (newDirectory === directory)
110178                     return out_directory_1 = directory, "break";
110179                 directory = newDirectory;
110180                 out_directory_1 = directory;
110181             };
110182             var out_directory_1;
110183             for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
110184                 var state_8 = _loop_24(directory);
110185                 directory = out_directory_1;
110186                 if (state_8 === "break")
110187                     break;
110188             }
110189             if (allFileNames.size) {
110190                 var remainingPaths = ts.arrayFrom(allFileNames.values());
110191                 if (remainingPaths.length > 1)
110192                     remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
110193                 sortedPaths.push.apply(sortedPaths, remainingPaths);
110194             }
110195             return sortedPaths;
110196         }
110197         function tryGetModuleNameFromAmbientModule(moduleSymbol) {
110198             var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
110199             if (decl) {
110200                 return decl.name.text;
110201             }
110202         }
110203         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
110204             for (var key in paths) {
110205                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
110206                     var patternText_1 = _a[_i];
110207                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
110208                     var indexOfStar = pattern.indexOf("*");
110209                     if (indexOfStar !== -1) {
110210                         var prefix = pattern.substr(0, indexOfStar);
110211                         var suffix = pattern.substr(indexOfStar + 1);
110212                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
110213                             ts.startsWith(relativeToBaseUrl, prefix) &&
110214                             ts.endsWith(relativeToBaseUrl, suffix) ||
110215                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
110216                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
110217                             return key.replace("*", matchedStar);
110218                         }
110219                     }
110220                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
110221                         return key;
110222                     }
110223                 }
110224             }
110225         }
110226         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
110227             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
110228             if (normalizedTargetPath === undefined) {
110229                 return undefined;
110230             }
110231             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
110232             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
110233             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
110234                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
110235                 : ts.removeFileExtension(relativePath);
110236         }
110237         function tryGetModuleNameAsNodeModule(_a, _b, host, options, packageNameOnly) {
110238             var path = _a.path, isRedirect = _a.isRedirect;
110239             var getCanonicalFileName = _b.getCanonicalFileName, sourceDirectory = _b.sourceDirectory;
110240             if (!host.fileExists || !host.readFile) {
110241                 return undefined;
110242             }
110243             var parts = getNodeModulePathParts(path);
110244             if (!parts) {
110245                 return undefined;
110246             }
110247             // Simplify the full file path to something that can be resolved by Node.
110248             var moduleSpecifier = path;
110249             var isPackageRootPath = false;
110250             if (!packageNameOnly) {
110251                 var packageRootIndex = parts.packageRootIndex;
110252                 var moduleFileNameForExtensionless = void 0;
110253                 while (true) {
110254                     // If the module could be imported by a directory name, use that directory's name
110255                     var _c = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _c.moduleFileToTry, packageRootPath = _c.packageRootPath;
110256                     if (packageRootPath) {
110257                         moduleSpecifier = packageRootPath;
110258                         isPackageRootPath = true;
110259                         break;
110260                     }
110261                     if (!moduleFileNameForExtensionless)
110262                         moduleFileNameForExtensionless = moduleFileToTry;
110263                     // try with next level of directory
110264                     packageRootIndex = path.indexOf(ts.directorySeparator, packageRootIndex + 1);
110265                     if (packageRootIndex === -1) {
110266                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
110267                         break;
110268                     }
110269                 }
110270             }
110271             if (isRedirect && !isPackageRootPath) {
110272                 return undefined;
110273             }
110274             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
110275             // Get a path that's relative to node_modules or the importing file's path
110276             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
110277             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
110278             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
110279                 return undefined;
110280             }
110281             // If the module was found in @types, get the actual Node package name
110282             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
110283             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
110284             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
110285             return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
110286             function tryDirectoryWithPackageJson(packageRootIndex) {
110287                 var packageRootPath = path.substring(0, packageRootIndex);
110288                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
110289                 var moduleFileToTry = path;
110290                 if (host.fileExists(packageJsonPath)) {
110291                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
110292                     var versionPaths = packageJsonContent.typesVersions
110293                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
110294                         : undefined;
110295                     if (versionPaths) {
110296                         var subModuleName = path.slice(packageRootPath.length + 1);
110297                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
110298                         if (fromPaths !== undefined) {
110299                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
110300                         }
110301                     }
110302                     // If the file is the main module, it can be imported by the package name
110303                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
110304                     if (ts.isString(mainFileRelative)) {
110305                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
110306                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
110307                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
110308                         }
110309                     }
110310                 }
110311                 return { moduleFileToTry: moduleFileToTry };
110312             }
110313             function getExtensionlessFileName(path) {
110314                 // We still have a file name - remove the extension
110315                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
110316                 // If the file is /index, it can be imported by its directory name
110317                 // IFF there is not _also_ a file by the same name
110318                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
110319                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
110320                 }
110321                 return fullModulePathWithoutExtension;
110322             }
110323         }
110324         function tryGetAnyFileFromPath(host, path) {
110325             if (!host.fileExists)
110326                 return;
110327             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
110328             var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
110329             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
110330                 var e = extensions_3[_i];
110331                 var fullPath = path + e;
110332                 if (host.fileExists(fullPath)) {
110333                     return fullPath;
110334                 }
110335             }
110336         }
110337         function getNodeModulePathParts(fullPath) {
110338             // If fullPath can't be valid module file within node_modules, returns undefined.
110339             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
110340             // Returns indices:                       ^            ^                                                      ^             ^
110341             var topLevelNodeModulesIndex = 0;
110342             var topLevelPackageNameIndex = 0;
110343             var packageRootIndex = 0;
110344             var fileNameIndex = 0;
110345             var States;
110346             (function (States) {
110347                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
110348                 States[States["NodeModules"] = 1] = "NodeModules";
110349                 States[States["Scope"] = 2] = "Scope";
110350                 States[States["PackageContent"] = 3] = "PackageContent";
110351             })(States || (States = {}));
110352             var partStart = 0;
110353             var partEnd = 0;
110354             var state = 0 /* BeforeNodeModules */;
110355             while (partEnd >= 0) {
110356                 partStart = partEnd;
110357                 partEnd = fullPath.indexOf("/", partStart + 1);
110358                 switch (state) {
110359                     case 0 /* BeforeNodeModules */:
110360                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
110361                             topLevelNodeModulesIndex = partStart;
110362                             topLevelPackageNameIndex = partEnd;
110363                             state = 1 /* NodeModules */;
110364                         }
110365                         break;
110366                     case 1 /* NodeModules */:
110367                     case 2 /* Scope */:
110368                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
110369                             state = 2 /* Scope */;
110370                         }
110371                         else {
110372                             packageRootIndex = partEnd;
110373                             state = 3 /* PackageContent */;
110374                         }
110375                         break;
110376                     case 3 /* PackageContent */:
110377                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
110378                             state = 1 /* NodeModules */;
110379                         }
110380                         else {
110381                             state = 3 /* PackageContent */;
110382                         }
110383                         break;
110384                 }
110385             }
110386             fileNameIndex = partStart;
110387             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
110388         }
110389         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
110390             return ts.firstDefined(rootDirs, function (rootDir) {
110391                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
110392                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
110393             });
110394         }
110395         function removeExtensionAndIndexPostFix(fileName, ending, options) {
110396             if (ts.fileExtensionIs(fileName, ".json" /* Json */))
110397                 return fileName;
110398             var noExtension = ts.removeFileExtension(fileName);
110399             switch (ending) {
110400                 case 0 /* Minimal */:
110401                     return ts.removeSuffix(noExtension, "/index");
110402                 case 1 /* Index */:
110403                     return noExtension;
110404                 case 2 /* JsExtension */:
110405                     return noExtension + getJSExtensionForFile(fileName, options);
110406                 default:
110407                     return ts.Debug.assertNever(ending);
110408             }
110409         }
110410         function getJSExtensionForFile(fileName, options) {
110411             var ext = ts.extensionFromPath(fileName);
110412             switch (ext) {
110413                 case ".ts" /* Ts */:
110414                 case ".d.ts" /* Dts */:
110415                     return ".js" /* Js */;
110416                 case ".tsx" /* Tsx */:
110417                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
110418                 case ".js" /* Js */:
110419                 case ".jsx" /* Jsx */:
110420                 case ".json" /* Json */:
110421                     return ext;
110422                 case ".tsbuildinfo" /* TsBuildInfo */:
110423                     return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
110424                 default:
110425                     return ts.Debug.assertNever(ext);
110426             }
110427         }
110428         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
110429             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
110430             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
110431         }
110432         function isPathRelativeToParent(path) {
110433             return ts.startsWith(path, "..");
110434         }
110435     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
110436 })(ts || (ts = {}));
110437 /*@internal*/
110438 var ts;
110439 (function (ts) {
110440     var sysFormatDiagnosticsHost = ts.sys ? {
110441         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
110442         getNewLine: function () { return ts.sys.newLine; },
110443         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
110444     } : undefined; // TODO: GH#18217
110445     /**
110446      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
110447      */
110448     function createDiagnosticReporter(system, pretty) {
110449         var host = system === ts.sys ? sysFormatDiagnosticsHost : {
110450             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
110451             getNewLine: function () { return system.newLine; },
110452             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
110453         };
110454         if (!pretty) {
110455             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
110456         }
110457         var diagnostics = new Array(1);
110458         return function (diagnostic) {
110459             diagnostics[0] = diagnostic;
110460             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
110461             diagnostics[0] = undefined; // TODO: GH#18217
110462         };
110463     }
110464     ts.createDiagnosticReporter = createDiagnosticReporter;
110465     /**
110466      * @returns Whether the screen was cleared.
110467      */
110468     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
110469         if (system.clearScreen &&
110470             !options.preserveWatchOutput &&
110471             !options.extendedDiagnostics &&
110472             !options.diagnostics &&
110473             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
110474             system.clearScreen();
110475             return true;
110476         }
110477         return false;
110478     }
110479     ts.screenStartingMessageCodes = [
110480         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
110481         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
110482     ];
110483     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
110484         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
110485             ? newLine + newLine
110486             : newLine;
110487     }
110488     /**
110489      * Get locale specific time based on whether we are in test mode
110490      */
110491     function getLocaleTimeString(system) {
110492         return !system.now ?
110493             new Date().toLocaleTimeString() :
110494             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
110495     }
110496     ts.getLocaleTimeString = getLocaleTimeString;
110497     /**
110498      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
110499      */
110500     function createWatchStatusReporter(system, pretty) {
110501         return pretty ?
110502             function (diagnostic, newLine, options) {
110503                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
110504                 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
110505                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
110506                 system.write(output);
110507             } :
110508             function (diagnostic, newLine, options) {
110509                 var output = "";
110510                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
110511                     output += newLine;
110512                 }
110513                 output += getLocaleTimeString(system) + " - ";
110514                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
110515                 system.write(output);
110516             };
110517     }
110518     ts.createWatchStatusReporter = createWatchStatusReporter;
110519     /** Parses config file using System interface */
110520     function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
110521         var host = system;
110522         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
110523         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
110524         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
110525         return result;
110526     }
110527     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
110528     function getErrorCountForSummary(diagnostics) {
110529         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
110530     }
110531     ts.getErrorCountForSummary = getErrorCountForSummary;
110532     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
110533         return errorCount === 1 ?
110534             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
110535             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
110536     }
110537     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
110538     function getErrorSummaryText(errorCount, newLine) {
110539         if (errorCount === 0)
110540             return "";
110541         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
110542         return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
110543     }
110544     ts.getErrorSummaryText = getErrorSummaryText;
110545     function listFiles(program, writeFileName) {
110546         if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
110547             ts.forEach(program.getSourceFiles(), function (file) {
110548                 writeFileName(file.fileName);
110549             });
110550         }
110551     }
110552     ts.listFiles = listFiles;
110553     /**
110554      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
110555      */
110556     function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
110557         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
110558         // First get and report any syntactic errors.
110559         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
110560         var configFileParsingDiagnosticsLength = allDiagnostics.length;
110561         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
110562         // If we didn't have any syntactic errors, then also try getting the global and
110563         // semantic errors.
110564         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
110565             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
110566             if (!isListFilesOnly) {
110567                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
110568                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
110569                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
110570                 }
110571             }
110572         }
110573         // Emit and report any errors we ran into.
110574         var emitResult = isListFilesOnly
110575             ? { emitSkipped: true, diagnostics: ts.emptyArray }
110576             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
110577         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
110578         ts.addRange(allDiagnostics, emitDiagnostics);
110579         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
110580         diagnostics.forEach(reportDiagnostic);
110581         if (writeFileName) {
110582             var currentDir_1 = program.getCurrentDirectory();
110583             ts.forEach(emittedFiles, function (file) {
110584                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
110585                 writeFileName("TSFILE: " + filepath);
110586             });
110587             listFiles(program, writeFileName);
110588         }
110589         if (reportSummary) {
110590             reportSummary(getErrorCountForSummary(diagnostics));
110591         }
110592         return {
110593             emitResult: emitResult,
110594             diagnostics: diagnostics,
110595         };
110596     }
110597     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
110598     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
110599         var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
110600         if (emitResult.emitSkipped && diagnostics.length > 0) {
110601             // If the emitter didn't emit anything, then pass that value along.
110602             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
110603         }
110604         else if (diagnostics.length > 0) {
110605             // The emitter emitted something, inform the caller if that happened in the presence
110606             // of diagnostics or not.
110607             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
110608         }
110609         return ts.ExitStatus.Success;
110610     }
110611     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
110612     ts.noopFileWatcher = { close: ts.noop };
110613     ts.returnNoopFileWatcher = function () { return ts.noopFileWatcher; };
110614     function createWatchHost(system, reportWatchStatus) {
110615         if (system === void 0) { system = ts.sys; }
110616         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
110617         return {
110618             onWatchStatusChange: onWatchStatusChange,
110619             watchFile: ts.maybeBind(system, system.watchFile) || ts.returnNoopFileWatcher,
110620             watchDirectory: ts.maybeBind(system, system.watchDirectory) || ts.returnNoopFileWatcher,
110621             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
110622             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
110623         };
110624     }
110625     ts.createWatchHost = createWatchHost;
110626     ts.WatchType = {
110627         ConfigFile: "Config file",
110628         SourceFile: "Source file",
110629         MissingFile: "Missing file",
110630         WildcardDirectory: "Wild card directory",
110631         FailedLookupLocations: "Failed Lookup Locations",
110632         TypeRoots: "Type roots"
110633     };
110634     function createWatchFactory(host, options) {
110635         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
110636         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
110637         var result = ts.getWatchFactory(watchLogLevel, writeLog);
110638         result.writeLog = writeLog;
110639         return result;
110640     }
110641     ts.createWatchFactory = createWatchFactory;
110642     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
110643         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
110644         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
110645         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
110646         return {
110647             getSourceFile: function (fileName, languageVersion, onError) {
110648                 var text;
110649                 try {
110650                     ts.performance.mark("beforeIORead");
110651                     text = host.readFile(fileName, getCompilerOptions().charset);
110652                     ts.performance.mark("afterIORead");
110653                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
110654                 }
110655                 catch (e) {
110656                     if (onError) {
110657                         onError(e.message);
110658                     }
110659                     text = "";
110660                 }
110661                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
110662             },
110663             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
110664             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
110665             writeFile: writeFile,
110666             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
110667             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
110668             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
110669             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
110670             fileExists: function (f) { return host.fileExists(f); },
110671             readFile: function (f) { return host.readFile(f); },
110672             trace: ts.maybeBind(host, host.trace),
110673             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
110674             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
110675             realpath: ts.maybeBind(host, host.realpath),
110676             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
110677             createHash: ts.maybeBind(host, host.createHash),
110678             readDirectory: ts.maybeBind(host, host.readDirectory),
110679         };
110680         function writeFile(fileName, text, writeByteOrderMark, onError) {
110681             try {
110682                 ts.performance.mark("beforeIOWrite");
110683                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
110684                 // the host.writeFile will do its own directory creation and
110685                 // the ensureDirectoriesExist call will always be redundant.
110686                 ts.writeFileEnsuringDirectories(fileName, text, writeByteOrderMark, function (path, data, writeByteOrderMark) { return host.writeFile(path, data, writeByteOrderMark); }, function (path) { return host.createDirectory(path); }, function (path) { return host.directoryExists(path); });
110687                 ts.performance.mark("afterIOWrite");
110688                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
110689             }
110690             catch (e) {
110691                 if (onError) {
110692                     onError(e.message);
110693                 }
110694             }
110695         }
110696     }
110697     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
110698     function setGetSourceFileAsHashVersioned(compilerHost, host) {
110699         var originalGetSourceFile = compilerHost.getSourceFile;
110700         var computeHash = ts.maybeBind(host, host.createHash) || ts.generateDjb2Hash;
110701         compilerHost.getSourceFile = function () {
110702             var args = [];
110703             for (var _i = 0; _i < arguments.length; _i++) {
110704                 args[_i] = arguments[_i];
110705             }
110706             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
110707             if (result) {
110708                 result.version = computeHash(result.text);
110709             }
110710             return result;
110711         };
110712     }
110713     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
110714     /**
110715      * Creates the watch compiler host that can be extended with config file or root file names and options host
110716      */
110717     function createProgramHost(system, createProgram) {
110718         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
110719         return {
110720             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
110721             getNewLine: function () { return system.newLine; },
110722             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
110723             getDefaultLibLocation: getDefaultLibLocation,
110724             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
110725             fileExists: function (path) { return system.fileExists(path); },
110726             readFile: function (path, encoding) { return system.readFile(path, encoding); },
110727             directoryExists: function (path) { return system.directoryExists(path); },
110728             getDirectories: function (path) { return system.getDirectories(path); },
110729             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
110730             realpath: ts.maybeBind(system, system.realpath),
110731             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
110732             trace: function (s) { return system.write(s + system.newLine); },
110733             createDirectory: function (path) { return system.createDirectory(path); },
110734             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
110735             createHash: ts.maybeBind(system, system.createHash),
110736             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
110737         };
110738     }
110739     ts.createProgramHost = createProgramHost;
110740     /**
110741      * Creates the watch compiler host that can be extended with config file or root file names and options host
110742      */
110743     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
110744         if (system === void 0) { system = ts.sys; }
110745         var writeFileName = function (s) { return system.write(s + system.newLine); };
110746         var result = createProgramHost(system, createProgram);
110747         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
110748         result.afterProgramCreate = function (builderProgram) {
110749             var compilerOptions = builderProgram.getCompilerOptions();
110750             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
110751             emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
110752         };
110753         return result;
110754     }
110755     /**
110756      * Report error and exit
110757      */
110758     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
110759         reportDiagnostic(diagnostic);
110760         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
110761     }
110762     /**
110763      * Creates the watch compiler host from system for config file in watch mode
110764      */
110765     function createWatchCompilerHostOfConfigFile(_a) {
110766         var configFileName = _a.configFileName, optionsToExtend = _a.optionsToExtend, watchOptionsToExtend = _a.watchOptionsToExtend, extraFileExtensions = _a.extraFileExtensions, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus;
110767         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
110768         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
110769         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
110770         host.configFileName = configFileName;
110771         host.optionsToExtend = optionsToExtend;
110772         host.watchOptionsToExtend = watchOptionsToExtend;
110773         host.extraFileExtensions = extraFileExtensions;
110774         return host;
110775     }
110776     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
110777     /**
110778      * Creates the watch compiler host from system for compiling root files and options in watch mode
110779      */
110780     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
110781         var rootFiles = _a.rootFiles, options = _a.options, watchOptions = _a.watchOptions, projectReferences = _a.projectReferences, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus;
110782         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
110783         host.rootFiles = rootFiles;
110784         host.options = options;
110785         host.watchOptions = watchOptions;
110786         host.projectReferences = projectReferences;
110787         return host;
110788     }
110789     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
110790     function performIncrementalCompilation(input) {
110791         var system = input.system || ts.sys;
110792         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
110793         var builderProgram = ts.createIncrementalProgram(input);
110794         var exitStatus = emitFilesAndReportErrorsAndGetExitStatus(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
110795         if (input.afterProgramEmitAndDiagnostics)
110796             input.afterProgramEmitAndDiagnostics(builderProgram);
110797         return exitStatus;
110798     }
110799     ts.performIncrementalCompilation = performIncrementalCompilation;
110800 })(ts || (ts = {}));
110801 var ts;
110802 (function (ts) {
110803     function readBuilderProgram(compilerOptions, host) {
110804         if (ts.outFile(compilerOptions))
110805             return undefined;
110806         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
110807         if (!buildInfoPath)
110808             return undefined;
110809         var content = host.readFile(buildInfoPath);
110810         if (!content)
110811             return undefined;
110812         var buildInfo = ts.getBuildInfo(content);
110813         if (buildInfo.version !== ts.version)
110814             return undefined;
110815         if (!buildInfo.program)
110816             return undefined;
110817         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
110818     }
110819     ts.readBuilderProgram = readBuilderProgram;
110820     function createIncrementalCompilerHost(options, system) {
110821         if (system === void 0) { system = ts.sys; }
110822         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
110823         host.createHash = ts.maybeBind(system, system.createHash);
110824         ts.setGetSourceFileAsHashVersioned(host, system);
110825         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
110826         return host;
110827     }
110828     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
110829     function createIncrementalProgram(_a) {
110830         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
110831         host = host || createIncrementalCompilerHost(options);
110832         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
110833         var oldProgram = readBuilderProgram(options, host);
110834         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
110835     }
110836     ts.createIncrementalProgram = createIncrementalProgram;
110837     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
110838         if (ts.isArray(rootFilesOrConfigFileName)) {
110839             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
110840                 rootFiles: rootFilesOrConfigFileName,
110841                 options: options,
110842                 watchOptions: watchOptionsOrExtraFileExtensions,
110843                 projectReferences: projectReferencesOrWatchOptionsToExtend,
110844                 system: system,
110845                 createProgram: createProgram,
110846                 reportDiagnostic: reportDiagnostic,
110847                 reportWatchStatus: reportWatchStatus,
110848             });
110849         }
110850         else {
110851             return ts.createWatchCompilerHostOfConfigFile({
110852                 configFileName: rootFilesOrConfigFileName,
110853                 optionsToExtend: options,
110854                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
110855                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
110856                 system: system,
110857                 createProgram: createProgram,
110858                 reportDiagnostic: reportDiagnostic,
110859                 reportWatchStatus: reportWatchStatus,
110860             });
110861         }
110862     }
110863     ts.createWatchCompilerHost = createWatchCompilerHost;
110864     function createWatchProgram(host) {
110865         var builderProgram;
110866         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
110867         var missingFilesMap; // Map of file watchers for the missing files
110868         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
110869         var timerToUpdateProgram; // timer callback to recompile the program
110870         var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations
110871         var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info
110872         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
110873         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
110874         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
110875         var currentDirectory = host.getCurrentDirectory();
110876         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
110877         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
110878         var configFileSpecs;
110879         var configFileParsingDiagnostics;
110880         var canConfigFileJsonReportNoInputFiles = false;
110881         var hasChangedConfigFileParsingErrors = false;
110882         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
110883         var directoryStructureHost = cachedDirectoryStructureHost || host;
110884         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
110885         // From tsc we want to get already parsed result and hence check for rootFileNames
110886         var newLine = updateNewLine();
110887         if (configFileName && host.configFileParsingResult) {
110888             setConfigFileParsingResult(host.configFileParsingResult);
110889             newLine = updateNewLine();
110890         }
110891         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
110892         if (configFileName && !host.configFileParsingResult) {
110893             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
110894             ts.Debug.assert(!rootFileNames);
110895             parseConfigFile();
110896             newLine = updateNewLine();
110897         }
110898         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
110899         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
110900         writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
110901         var configFileWatcher;
110902         if (configFileName) {
110903             configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
110904         }
110905         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
110906         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
110907         // Members for CompilerHost
110908         var getNewSourceFile = compilerHost.getSourceFile;
110909         compilerHost.getSourceFile = function (fileName) {
110910             var args = [];
110911             for (var _i = 1; _i < arguments.length; _i++) {
110912                 args[_i - 1] = arguments[_i];
110913             }
110914             return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
110915         };
110916         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
110917         compilerHost.getNewLine = function () { return newLine; };
110918         compilerHost.fileExists = fileExists;
110919         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
110920         // Members for ResolutionCacheHost
110921         compilerHost.toPath = toPath;
110922         compilerHost.getCompilationSettings = function () { return compilerOptions; };
110923         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
110924         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
110925         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
110926         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
110927         compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations;
110928         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
110929         compilerHost.onChangedAutomaticTypeDirectiveNames = scheduleProgramUpdate;
110930         compilerHost.fileIsOpen = ts.returnFalse;
110931         compilerHost.getCurrentProgram = getCurrentProgram;
110932         compilerHost.writeLog = writeLog;
110933         // Cache for the module resolution
110934         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
110935             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
110936             currentDirectory, 
110937         /*logChangesWhenResolvingModule*/ false);
110938         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
110939         compilerHost.resolveModuleNames = host.resolveModuleNames ?
110940             (function () {
110941                 var args = [];
110942                 for (var _i = 0; _i < arguments.length; _i++) {
110943                     args[_i] = arguments[_i];
110944                 }
110945                 return host.resolveModuleNames.apply(host, args);
110946             }) :
110947             (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
110948         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
110949             (function () {
110950                 var args = [];
110951                 for (var _i = 0; _i < arguments.length; _i++) {
110952                     args[_i] = arguments[_i];
110953                 }
110954                 return host.resolveTypeReferenceDirectives.apply(host, args);
110955             }) :
110956             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
110957         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
110958         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
110959         synchronizeProgram();
110960         // Update the wild card directory watch
110961         watchConfigFileWildCardDirectories();
110962         return configFileName ?
110963             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
110964             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
110965         function close() {
110966             clearInvalidateResolutionsOfFailedLookupLocations();
110967             resolutionCache.clear();
110968             ts.clearMap(sourceFilesCache, function (value) {
110969                 if (value && value.fileWatcher) {
110970                     value.fileWatcher.close();
110971                     value.fileWatcher = undefined;
110972                 }
110973             });
110974             if (configFileWatcher) {
110975                 configFileWatcher.close();
110976                 configFileWatcher = undefined;
110977             }
110978             if (watchedWildcardDirectories) {
110979                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
110980                 watchedWildcardDirectories = undefined;
110981             }
110982             if (missingFilesMap) {
110983                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
110984                 missingFilesMap = undefined;
110985             }
110986         }
110987         function getCurrentBuilderProgram() {
110988             return builderProgram;
110989         }
110990         function getCurrentProgram() {
110991             return builderProgram && builderProgram.getProgramOrUndefined();
110992         }
110993         function synchronizeProgram() {
110994             writeLog("Synchronizing program");
110995             clearInvalidateResolutionsOfFailedLookupLocations();
110996             var program = getCurrentBuilderProgram();
110997             if (hasChangedCompilerOptions) {
110998                 newLine = updateNewLine();
110999                 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
111000                     resolutionCache.clear();
111001                 }
111002             }
111003             // All resolutions are invalid if user provided resolutions
111004             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
111005             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
111006                 if (hasChangedConfigFileParsingErrors) {
111007                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
111008                     hasChangedConfigFileParsingErrors = false;
111009                 }
111010             }
111011             else {
111012                 createNewProgram(hasInvalidatedResolution);
111013             }
111014             if (host.afterProgramCreate && program !== builderProgram) {
111015                 host.afterProgramCreate(builderProgram);
111016             }
111017             return builderProgram;
111018         }
111019         function createNewProgram(hasInvalidatedResolution) {
111020             // Compile the program
111021             writeLog("CreatingProgramWith::");
111022             writeLog("  roots: " + JSON.stringify(rootFileNames));
111023             writeLog("  options: " + JSON.stringify(compilerOptions));
111024             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
111025             hasChangedCompilerOptions = false;
111026             hasChangedConfigFileParsingErrors = false;
111027             resolutionCache.startCachingPerDirectoryResolution();
111028             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
111029             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
111030             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
111031             resolutionCache.finishCachingPerDirectoryResolution();
111032             // Update watches
111033             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath);
111034             if (needsUpdateInTypeRootWatch) {
111035                 resolutionCache.updateTypeRootsWatch();
111036             }
111037             if (missingFilePathsRequestedForRelease) {
111038                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
111039                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
111040                 // if there is already watcher for it (for missing files)
111041                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
111042                 // so that at later time we have correct result of their presence
111043                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
111044                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
111045                     if (!missingFilesMap.has(missingFilePath)) {
111046                         sourceFilesCache.delete(missingFilePath);
111047                     }
111048                 }
111049                 missingFilePathsRequestedForRelease = undefined;
111050             }
111051         }
111052         function updateRootFileNames(files) {
111053             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
111054             rootFileNames = files;
111055             scheduleProgramUpdate();
111056         }
111057         function updateNewLine() {
111058             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
111059         }
111060         function toPath(fileName) {
111061             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
111062         }
111063         function isFileMissingOnHost(hostSourceFile) {
111064             return typeof hostSourceFile === "boolean";
111065         }
111066         function isFilePresenceUnknownOnHost(hostSourceFile) {
111067             return typeof hostSourceFile.version === "boolean";
111068         }
111069         function fileExists(fileName) {
111070             var path = toPath(fileName);
111071             // If file is missing on host from cache, we can definitely say file doesnt exist
111072             // otherwise we need to ensure from the disk
111073             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
111074                 return false;
111075             }
111076             return directoryStructureHost.fileExists(fileName);
111077         }
111078         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
111079             var hostSourceFile = sourceFilesCache.get(path);
111080             // No source file on the host
111081             if (isFileMissingOnHost(hostSourceFile)) {
111082                 return undefined;
111083             }
111084             // Create new source file if requested or the versions dont match
111085             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
111086                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
111087                 if (hostSourceFile) {
111088                     if (sourceFile) {
111089                         // Set the source file and create file watcher now that file was present on the disk
111090                         hostSourceFile.sourceFile = sourceFile;
111091                         hostSourceFile.version = sourceFile.version;
111092                         if (!hostSourceFile.fileWatcher) {
111093                             hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
111094                         }
111095                     }
111096                     else {
111097                         // There is no source file on host any more, close the watch, missing file paths will track it
111098                         if (hostSourceFile.fileWatcher) {
111099                             hostSourceFile.fileWatcher.close();
111100                         }
111101                         sourceFilesCache.set(path, false);
111102                     }
111103                 }
111104                 else {
111105                     if (sourceFile) {
111106                         var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
111107                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
111108                     }
111109                     else {
111110                         sourceFilesCache.set(path, false);
111111                     }
111112                 }
111113                 return sourceFile;
111114             }
111115             return hostSourceFile.sourceFile;
111116         }
111117         function nextSourceFileVersion(path) {
111118             var hostSourceFile = sourceFilesCache.get(path);
111119             if (hostSourceFile !== undefined) {
111120                 if (isFileMissingOnHost(hostSourceFile)) {
111121                     // The next version, lets set it as presence unknown file
111122                     sourceFilesCache.set(path, { version: false });
111123                 }
111124                 else {
111125                     hostSourceFile.version = false;
111126                 }
111127             }
111128         }
111129         function getSourceVersion(path) {
111130             var hostSourceFile = sourceFilesCache.get(path);
111131             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
111132         }
111133         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
111134             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
111135             // If this is the source file thats in the cache and new program doesnt need it,
111136             // remove the cached entry.
111137             // Note we arent deleting entry if file became missing in new program or
111138             // there was version update and new source file was created.
111139             if (hostSourceFileInfo !== undefined) {
111140                 // record the missing file paths so they can be removed later if watchers arent tracking them
111141                 if (isFileMissingOnHost(hostSourceFileInfo)) {
111142                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
111143                 }
111144                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
111145                     if (hostSourceFileInfo.fileWatcher) {
111146                         hostSourceFileInfo.fileWatcher.close();
111147                     }
111148                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
111149                     if (!hasSourceFileByPath) {
111150                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
111151                     }
111152                 }
111153             }
111154         }
111155         function reportWatchDiagnostic(message) {
111156             if (host.onWatchStatusChange) {
111157                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
111158             }
111159         }
111160         function hasChangedAutomaticTypeDirectiveNames() {
111161             return resolutionCache.hasChangedAutomaticTypeDirectiveNames();
111162         }
111163         function clearInvalidateResolutionsOfFailedLookupLocations() {
111164             if (!timerToInvalidateFailedLookupResolutions)
111165                 return false;
111166             host.clearTimeout(timerToInvalidateFailedLookupResolutions);
111167             timerToInvalidateFailedLookupResolutions = undefined;
111168             return true;
111169         }
111170         function scheduleInvalidateResolutionsOfFailedLookupLocations() {
111171             if (!host.setTimeout || !host.clearTimeout) {
111172                 return resolutionCache.invalidateResolutionsOfFailedLookupLocations();
111173             }
111174             var pending = clearInvalidateResolutionsOfFailedLookupLocations();
111175             writeLog("Scheduling invalidateFailedLookup" + (pending ? ", Cancelled earlier one" : ""));
111176             timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250);
111177         }
111178         function invalidateResolutionsOfFailedLookup() {
111179             timerToInvalidateFailedLookupResolutions = undefined;
111180             if (resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
111181                 scheduleProgramUpdate();
111182             }
111183         }
111184         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
111185         // operations (such as saving all modified files in an editor) a chance to complete before we kick
111186         // off a new compilation.
111187         function scheduleProgramUpdate() {
111188             if (!host.setTimeout || !host.clearTimeout) {
111189                 return;
111190             }
111191             if (timerToUpdateProgram) {
111192                 host.clearTimeout(timerToUpdateProgram);
111193             }
111194             writeLog("Scheduling update");
111195             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
111196         }
111197         function scheduleProgramReload() {
111198             ts.Debug.assert(!!configFileName);
111199             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
111200             scheduleProgramUpdate();
111201         }
111202         function updateProgramWithWatchStatus() {
111203             timerToUpdateProgram = undefined;
111204             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
111205             updateProgram();
111206         }
111207         function updateProgram() {
111208             switch (reloadLevel) {
111209                 case ts.ConfigFileProgramReloadLevel.Partial:
111210                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
111211                     reloadFileNamesFromConfigFile();
111212                     break;
111213                 case ts.ConfigFileProgramReloadLevel.Full:
111214                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
111215                     reloadConfigFile();
111216                     break;
111217                 default:
111218                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
111219                     synchronizeProgram();
111220                     break;
111221             }
111222             ts.perfLogger.logStopUpdateProgram("Done");
111223             return getCurrentBuilderProgram();
111224         }
111225         function reloadFileNamesFromConfigFile() {
111226             writeLog("Reloading new file names and options");
111227             var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions);
111228             if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
111229                 hasChangedConfigFileParsingErrors = true;
111230             }
111231             rootFileNames = result.fileNames;
111232             // Update the program
111233             synchronizeProgram();
111234         }
111235         function reloadConfigFile() {
111236             writeLog("Reloading config file: " + configFileName);
111237             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
111238             if (cachedDirectoryStructureHost) {
111239                 cachedDirectoryStructureHost.clearCache();
111240             }
111241             parseConfigFile();
111242             hasChangedCompilerOptions = true;
111243             synchronizeProgram();
111244             // Update the wild card directory watch
111245             watchConfigFileWildCardDirectories();
111246         }
111247         function parseConfigFile() {
111248             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
111249         }
111250         function setConfigFileParsingResult(configFileParseResult) {
111251             rootFileNames = configFileParseResult.fileNames;
111252             compilerOptions = configFileParseResult.options;
111253             watchOptions = configFileParseResult.watchOptions;
111254             configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
111255             projectReferences = configFileParseResult.projectReferences;
111256             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
111257             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw);
111258             hasChangedConfigFileParsingErrors = true;
111259         }
111260         function onSourceFileChange(fileName, eventKind, path) {
111261             updateCachedSystemWithFile(fileName, path, eventKind);
111262             // Update the source file cache
111263             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
111264                 resolutionCache.invalidateResolutionOfFile(path);
111265             }
111266             resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
111267             nextSourceFileVersion(path);
111268             // Update the program
111269             scheduleProgramUpdate();
111270         }
111271         function updateCachedSystemWithFile(fileName, path, eventKind) {
111272             if (cachedDirectoryStructureHost) {
111273                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
111274             }
111275         }
111276         function watchMissingFilePath(missingFilePath) {
111277             return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
111278         }
111279         function onMissingFileChange(fileName, eventKind, missingFilePath) {
111280             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
111281             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
111282                 missingFilesMap.get(missingFilePath).close();
111283                 missingFilesMap.delete(missingFilePath);
111284                 // Delete the entry in the source files cache so that new source file is created
111285                 nextSourceFileVersion(missingFilePath);
111286                 // When a missing file is created, we should update the graph.
111287                 scheduleProgramUpdate();
111288             }
111289         }
111290         function watchConfigFileWildCardDirectories() {
111291             if (configFileSpecs) {
111292                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = new ts.Map()), new ts.Map(ts.getEntries(configFileSpecs.wildcardDirectories)), watchWildcardDirectory);
111293             }
111294             else if (watchedWildcardDirectories) {
111295                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
111296             }
111297         }
111298         function watchWildcardDirectory(directory, flags) {
111299             return watchDirectory(host, directory, function (fileOrDirectory) {
111300                 ts.Debug.assert(!!configFileName);
111301                 var fileOrDirectoryPath = toPath(fileOrDirectory);
111302                 // Since the file existence changed, update the sourceFiles cache
111303                 if (cachedDirectoryStructureHost) {
111304                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
111305                 }
111306                 nextSourceFileVersion(fileOrDirectoryPath);
111307                 if (ts.isIgnoredFileFromWildCardWatching({
111308                     watchedDirPath: toPath(directory),
111309                     fileOrDirectory: fileOrDirectory,
111310                     fileOrDirectoryPath: fileOrDirectoryPath,
111311                     configFileName: configFileName,
111312                     configFileSpecs: configFileSpecs,
111313                     extraFileExtensions: extraFileExtensions,
111314                     options: compilerOptions,
111315                     program: getCurrentBuilderProgram(),
111316                     currentDirectory: currentDirectory,
111317                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
111318                     writeLog: writeLog
111319                 }))
111320                     return;
111321                 // Reload is pending, do the reload
111322                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
111323                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
111324                     // Schedule Update the program
111325                     scheduleProgramUpdate();
111326                 }
111327             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
111328         }
111329     }
111330     ts.createWatchProgram = createWatchProgram;
111331 })(ts || (ts = {}));
111332 /*@internal*/
111333 var ts;
111334 (function (ts) {
111335     var UpToDateStatusType;
111336     (function (UpToDateStatusType) {
111337         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
111338         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
111339         /**
111340          * The project appears out of date because its upstream inputs are newer than its outputs,
111341          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
111342          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
111343          */
111344         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
111345         /**
111346          * The project appears out of date because its upstream inputs are newer than its outputs,
111347          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
111348          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
111349          */
111350         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
111351         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
111352         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
111353         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
111354         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
111355         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
111356         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
111357         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
111358         /**
111359          * Projects with no outputs (i.e. "solution" files)
111360          */
111361         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
111362     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
111363     function resolveConfigFileProjectName(project) {
111364         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
111365             return project;
111366         }
111367         return ts.combinePaths(project, "tsconfig.json");
111368     }
111369     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
111370 })(ts || (ts = {}));
111371 var ts;
111372 (function (ts) {
111373     var minimumDate = new Date(-8640000000000000);
111374     var maximumDate = new Date(8640000000000000);
111375     var BuildResultFlags;
111376     (function (BuildResultFlags) {
111377         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
111378         /**
111379          * No errors of any kind occurred during build
111380          */
111381         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
111382         /**
111383          * None of the .d.ts files emitted by this build were
111384          * different from the existing files on disk
111385          */
111386         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
111387         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
111388         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
111389         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
111390         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
111391         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
111392         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
111393     })(BuildResultFlags || (BuildResultFlags = {}));
111394     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
111395         var existingValue = configFileMap.get(resolved);
111396         var newValue;
111397         if (!existingValue) {
111398             newValue = createT();
111399             configFileMap.set(resolved, newValue);
111400         }
111401         return existingValue || newValue;
111402     }
111403     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
111404         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); });
111405     }
111406     function newer(date1, date2) {
111407         return date2 > date1 ? date2 : date1;
111408     }
111409     function isDeclarationFile(fileName) {
111410         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
111411     }
111412     /*@internal*/
111413     function isCircularBuildOrder(buildOrder) {
111414         return !!buildOrder && !!buildOrder.buildOrder;
111415     }
111416     ts.isCircularBuildOrder = isCircularBuildOrder;
111417     /*@internal*/
111418     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
111419         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
111420     }
111421     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
111422     /**
111423      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
111424      */
111425     function createBuilderStatusReporter(system, pretty) {
111426         return function (diagnostic) {
111427             var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
111428             output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
111429             system.write(output);
111430         };
111431     }
111432     ts.createBuilderStatusReporter = createBuilderStatusReporter;
111433     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
111434         var host = ts.createProgramHost(system, createProgram);
111435         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
111436         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
111437         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
111438         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
111439         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
111440         host.now = ts.maybeBind(system, system.now); // For testing
111441         return host;
111442     }
111443     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
111444         if (system === void 0) { system = ts.sys; }
111445         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
111446         host.reportErrorSummary = reportErrorSummary;
111447         return host;
111448     }
111449     ts.createSolutionBuilderHost = createSolutionBuilderHost;
111450     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
111451         if (system === void 0) { system = ts.sys; }
111452         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
111453         var watchHost = ts.createWatchHost(system, reportWatchStatus);
111454         ts.copyProperties(host, watchHost);
111455         return host;
111456     }
111457     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
111458     function getCompilerOptionsOfBuildOptions(buildOptions) {
111459         var result = {};
111460         ts.commonOptionsWithBuild.forEach(function (option) {
111461             if (ts.hasProperty(buildOptions, option.name))
111462                 result[option.name] = buildOptions[option.name];
111463         });
111464         return result;
111465     }
111466     function createSolutionBuilder(host, rootNames, defaultOptions) {
111467         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
111468     }
111469     ts.createSolutionBuilder = createSolutionBuilder;
111470     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
111471         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
111472     }
111473     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
111474     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
111475         var host = hostOrHostWithWatch;
111476         var hostWithWatch = hostOrHostWithWatch;
111477         var currentDirectory = host.getCurrentDirectory();
111478         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
111479         // State of the solution
111480         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
111481         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
111482         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
111483         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
111484         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
111485         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
111486         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
111487         if (!compilerHost.resolveModuleNames) {
111488             var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
111489             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
111490                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
111491             };
111492         }
111493         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
111494         var state = {
111495             host: host,
111496             hostWithWatch: hostWithWatch,
111497             currentDirectory: currentDirectory,
111498             getCanonicalFileName: getCanonicalFileName,
111499             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
111500             writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
111501             // State of solution
111502             options: options,
111503             baseCompilerOptions: baseCompilerOptions,
111504             rootNames: rootNames,
111505             baseWatchOptions: baseWatchOptions,
111506             resolvedConfigFilePaths: new ts.Map(),
111507             configFileCache: new ts.Map(),
111508             projectStatus: new ts.Map(),
111509             buildInfoChecked: new ts.Map(),
111510             extendedConfigCache: new ts.Map(),
111511             builderPrograms: new ts.Map(),
111512             diagnostics: new ts.Map(),
111513             projectPendingBuild: new ts.Map(),
111514             projectErrorsReported: new ts.Map(),
111515             compilerHost: compilerHost,
111516             moduleResolutionCache: moduleResolutionCache,
111517             // Mutable state
111518             buildOrder: undefined,
111519             readFileWithCache: function (f) { return host.readFile(f); },
111520             projectCompilerOptions: baseCompilerOptions,
111521             cache: undefined,
111522             allProjectBuildPending: true,
111523             needsSummary: true,
111524             watchAllProjectsPending: watch,
111525             currentInvalidatedProject: undefined,
111526             // Watch state
111527             watch: watch,
111528             allWatchedWildcardDirectories: new ts.Map(),
111529             allWatchedInputFiles: new ts.Map(),
111530             allWatchedConfigFiles: new ts.Map(),
111531             timerToBuildInvalidatedProject: undefined,
111532             reportFileChangeDetected: false,
111533             watchFile: watchFile,
111534             watchFilePath: watchFilePath,
111535             watchDirectory: watchDirectory,
111536             writeLog: writeLog,
111537         };
111538         return state;
111539     }
111540     function toPath(state, fileName) {
111541         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
111542     }
111543     function toResolvedConfigFilePath(state, fileName) {
111544         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
111545         var path = resolvedConfigFilePaths.get(fileName);
111546         if (path !== undefined)
111547             return path;
111548         var resolvedPath = toPath(state, fileName);
111549         resolvedConfigFilePaths.set(fileName, resolvedPath);
111550         return resolvedPath;
111551     }
111552     function isParsedCommandLine(entry) {
111553         return !!entry.options;
111554     }
111555     function parseConfigFile(state, configFileName, configFilePath) {
111556         var configFileCache = state.configFileCache;
111557         var value = configFileCache.get(configFilePath);
111558         if (value) {
111559             return isParsedCommandLine(value) ? value : undefined;
111560         }
111561         var diagnostic;
111562         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
111563         var parsed;
111564         if (host.getParsedCommandLine) {
111565             parsed = host.getParsedCommandLine(configFileName);
111566             if (!parsed)
111567                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
111568         }
111569         else {
111570             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
111571             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
111572             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
111573         }
111574         configFileCache.set(configFilePath, parsed || diagnostic);
111575         return parsed;
111576     }
111577     function resolveProjectName(state, name) {
111578         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
111579     }
111580     function createBuildOrder(state, roots) {
111581         var temporaryMarks = new ts.Map();
111582         var permanentMarks = new ts.Map();
111583         var circularityReportStack = [];
111584         var buildOrder;
111585         var circularDiagnostics;
111586         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
111587             var root = roots_1[_i];
111588             visit(root);
111589         }
111590         return circularDiagnostics ?
111591             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
111592             buildOrder || ts.emptyArray;
111593         function visit(configFileName, inCircularContext) {
111594             var projPath = toResolvedConfigFilePath(state, configFileName);
111595             // Already visited
111596             if (permanentMarks.has(projPath))
111597                 return;
111598             // Circular
111599             if (temporaryMarks.has(projPath)) {
111600                 if (!inCircularContext) {
111601                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
111602                 }
111603                 return;
111604             }
111605             temporaryMarks.set(projPath, true);
111606             circularityReportStack.push(configFileName);
111607             var parsed = parseConfigFile(state, configFileName, projPath);
111608             if (parsed && parsed.projectReferences) {
111609                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
111610                     var ref = _a[_i];
111611                     var resolvedRefPath = resolveProjectName(state, ref.path);
111612                     visit(resolvedRefPath, inCircularContext || ref.circular);
111613                 }
111614             }
111615             circularityReportStack.pop();
111616             permanentMarks.set(projPath, true);
111617             (buildOrder || (buildOrder = [])).push(configFileName);
111618         }
111619     }
111620     function getBuildOrder(state) {
111621         return state.buildOrder || createStateBuildOrder(state);
111622     }
111623     function createStateBuildOrder(state) {
111624         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
111625         // Clear all to ResolvedConfigFilePaths cache to start fresh
111626         state.resolvedConfigFilePaths.clear();
111627         // TODO(rbuckton): Should be a `Set`, but that requires changing the code below that uses `mutateMapSkippingNewValues`
111628         var currentProjects = new ts.Map(getBuildOrderFromAnyBuildOrder(buildOrder).map(function (resolved) { return [toResolvedConfigFilePath(state, resolved), true]; }));
111629         var noopOnDelete = { onDeleteValue: ts.noop };
111630         // Config file cache
111631         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
111632         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
111633         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
111634         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
111635         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
111636         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
111637         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
111638         // Remove watches for the program no longer in the solution
111639         if (state.watch) {
111640             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
111641             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
111642             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
111643         }
111644         return state.buildOrder = buildOrder;
111645     }
111646     function getBuildOrderFor(state, project, onlyReferences) {
111647         var resolvedProject = project && resolveProjectName(state, project);
111648         var buildOrderFromState = getBuildOrder(state);
111649         if (isCircularBuildOrder(buildOrderFromState))
111650             return buildOrderFromState;
111651         if (resolvedProject) {
111652             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
111653             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
111654             if (projectIndex === -1)
111655                 return undefined;
111656         }
111657         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
111658         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
111659         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
111660         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
111661         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
111662     }
111663     function enableCache(state) {
111664         if (state.cache) {
111665             disableCache(state);
111666         }
111667         var compilerHost = state.compilerHost, host = state.host;
111668         var originalReadFileWithCache = state.readFileWithCache;
111669         var originalGetSourceFile = compilerHost.getSourceFile;
111670         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
111671             var args = [];
111672             for (var _i = 0; _i < arguments.length; _i++) {
111673                 args[_i] = arguments[_i];
111674             }
111675             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
111676         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
111677         state.readFileWithCache = readFileWithCache;
111678         compilerHost.getSourceFile = getSourceFileWithCache;
111679         state.cache = {
111680             originalReadFile: originalReadFile,
111681             originalFileExists: originalFileExists,
111682             originalDirectoryExists: originalDirectoryExists,
111683             originalCreateDirectory: originalCreateDirectory,
111684             originalWriteFile: originalWriteFile,
111685             originalReadFileWithCache: originalReadFileWithCache,
111686             originalGetSourceFile: originalGetSourceFile,
111687         };
111688     }
111689     function disableCache(state) {
111690         if (!state.cache)
111691             return;
111692         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
111693         host.readFile = cache.originalReadFile;
111694         host.fileExists = cache.originalFileExists;
111695         host.directoryExists = cache.originalDirectoryExists;
111696         host.createDirectory = cache.originalCreateDirectory;
111697         host.writeFile = cache.originalWriteFile;
111698         compilerHost.getSourceFile = cache.originalGetSourceFile;
111699         state.readFileWithCache = cache.originalReadFileWithCache;
111700         extendedConfigCache.clear();
111701         if (moduleResolutionCache) {
111702             moduleResolutionCache.directoryToModuleNameMap.clear();
111703             moduleResolutionCache.moduleNameToDirectoryMap.clear();
111704         }
111705         state.cache = undefined;
111706     }
111707     function clearProjectStatus(state, resolved) {
111708         state.projectStatus.delete(resolved);
111709         state.diagnostics.delete(resolved);
111710     }
111711     function addProjToQueue(_a, proj, reloadLevel) {
111712         var projectPendingBuild = _a.projectPendingBuild;
111713         var value = projectPendingBuild.get(proj);
111714         if (value === undefined) {
111715             projectPendingBuild.set(proj, reloadLevel);
111716         }
111717         else if (value < reloadLevel) {
111718             projectPendingBuild.set(proj, reloadLevel);
111719         }
111720     }
111721     function setupInitialBuild(state, cancellationToken) {
111722         // Set initial build if not already built
111723         if (!state.allProjectBuildPending)
111724             return;
111725         state.allProjectBuildPending = false;
111726         if (state.options.watch) {
111727             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
111728         }
111729         enableCache(state);
111730         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
111731         buildOrder.forEach(function (configFileName) {
111732             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
111733         });
111734         if (cancellationToken) {
111735             cancellationToken.throwIfCancellationRequested();
111736         }
111737     }
111738     var InvalidatedProjectKind;
111739     (function (InvalidatedProjectKind) {
111740         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
111741         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
111742         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
111743     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
111744     function doneInvalidatedProject(state, projectPath) {
111745         state.projectPendingBuild.delete(projectPath);
111746         state.currentInvalidatedProject = undefined;
111747         return state.diagnostics.has(projectPath) ?
111748             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
111749             ts.ExitStatus.Success;
111750     }
111751     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
111752         var updateOutputFileStampsPending = true;
111753         return {
111754             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
111755             project: project,
111756             projectPath: projectPath,
111757             buildOrder: buildOrder,
111758             getCompilerOptions: function () { return config.options; },
111759             getCurrentDirectory: function () { return state.currentDirectory; },
111760             updateOutputFileStatmps: function () {
111761                 updateOutputTimestamps(state, config, projectPath);
111762                 updateOutputFileStampsPending = false;
111763             },
111764             done: function () {
111765                 if (updateOutputFileStampsPending) {
111766                     updateOutputTimestamps(state, config, projectPath);
111767                 }
111768                 return doneInvalidatedProject(state, projectPath);
111769             }
111770         };
111771     }
111772     var BuildStep;
111773     (function (BuildStep) {
111774         BuildStep[BuildStep["CreateProgram"] = 0] = "CreateProgram";
111775         BuildStep[BuildStep["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
111776         BuildStep[BuildStep["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
111777         BuildStep[BuildStep["Emit"] = 3] = "Emit";
111778         BuildStep[BuildStep["EmitBundle"] = 4] = "EmitBundle";
111779         BuildStep[BuildStep["EmitBuildInfo"] = 5] = "EmitBuildInfo";
111780         BuildStep[BuildStep["BuildInvalidatedProjectOfBundle"] = 6] = "BuildInvalidatedProjectOfBundle";
111781         BuildStep[BuildStep["QueueReferencingProjects"] = 7] = "QueueReferencingProjects";
111782         BuildStep[BuildStep["Done"] = 8] = "Done";
111783     })(BuildStep || (BuildStep = {}));
111784     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
111785         var step = kind === InvalidatedProjectKind.Build ? BuildStep.CreateProgram : BuildStep.EmitBundle;
111786         var program;
111787         var buildResult;
111788         var invalidatedProjectOfBundle;
111789         return kind === InvalidatedProjectKind.Build ?
111790             {
111791                 kind: kind,
111792                 project: project,
111793                 projectPath: projectPath,
111794                 buildOrder: buildOrder,
111795                 getCompilerOptions: function () { return config.options; },
111796                 getCurrentDirectory: function () { return state.currentDirectory; },
111797                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
111798                 getProgram: function () {
111799                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
111800                 },
111801                 getSourceFile: function (fileName) {
111802                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
111803                 },
111804                 getSourceFiles: function () {
111805                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
111806                 },
111807                 getOptionsDiagnostics: function (cancellationToken) {
111808                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
111809                 },
111810                 getGlobalDiagnostics: function (cancellationToken) {
111811                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
111812                 },
111813                 getConfigFileParsingDiagnostics: function () {
111814                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
111815                 },
111816                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
111817                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
111818                 },
111819                 getAllDependencies: function (sourceFile) {
111820                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
111821                 },
111822                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
111823                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
111824                 },
111825                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
111826                     return withProgramOrUndefined(function (program) {
111827                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
111828                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
111829                     });
111830                 },
111831                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
111832                     if (targetSourceFile || emitOnlyDtsFiles) {
111833                         return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
111834                     }
111835                     executeSteps(BuildStep.SemanticDiagnostics, cancellationToken);
111836                     if (step === BuildStep.EmitBuildInfo) {
111837                         return emitBuildInfo(writeFile, cancellationToken);
111838                     }
111839                     if (step !== BuildStep.Emit)
111840                         return undefined;
111841                     return emit(writeFile, cancellationToken, customTransformers);
111842                 },
111843                 done: done
111844             } :
111845             {
111846                 kind: kind,
111847                 project: project,
111848                 projectPath: projectPath,
111849                 buildOrder: buildOrder,
111850                 getCompilerOptions: function () { return config.options; },
111851                 getCurrentDirectory: function () { return state.currentDirectory; },
111852                 emit: function (writeFile, customTransformers) {
111853                     if (step !== BuildStep.EmitBundle)
111854                         return invalidatedProjectOfBundle;
111855                     return emitBundle(writeFile, customTransformers);
111856                 },
111857                 done: done,
111858             };
111859         function done(cancellationToken, writeFile, customTransformers) {
111860             executeSteps(BuildStep.Done, cancellationToken, writeFile, customTransformers);
111861             return doneInvalidatedProject(state, projectPath);
111862         }
111863         function withProgramOrUndefined(action) {
111864             executeSteps(BuildStep.CreateProgram);
111865             return program && action(program);
111866         }
111867         function withProgramOrEmptyArray(action) {
111868             return withProgramOrUndefined(action) || ts.emptyArray;
111869         }
111870         function createProgram() {
111871             ts.Debug.assert(program === undefined);
111872             if (state.options.dry) {
111873                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
111874                 buildResult = BuildResultFlags.Success;
111875                 step = BuildStep.QueueReferencingProjects;
111876                 return;
111877             }
111878             if (state.options.verbose)
111879                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
111880             if (config.fileNames.length === 0) {
111881                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
111882                 // Nothing to build - must be a solution file, basically
111883                 buildResult = BuildResultFlags.None;
111884                 step = BuildStep.QueueReferencingProjects;
111885                 return;
111886             }
111887             var host = state.host, compilerHost = state.compilerHost;
111888             state.projectCompilerOptions = config.options;
111889             // Update module resolution cache if needed
111890             updateModuleResolutionCache(state, project, config);
111891             // Create program
111892             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
111893             if (state.watch) {
111894                 state.builderPrograms.set(projectPath, program);
111895             }
111896             step++;
111897         }
111898         function handleDiagnostics(diagnostics, errorFlags, errorType) {
111899             var _a;
111900             if (diagnostics.length) {
111901                 (_a = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType), buildResult = _a.buildResult, step = _a.step);
111902             }
111903             else {
111904                 step++;
111905             }
111906         }
111907         function getSyntaxDiagnostics(cancellationToken) {
111908             ts.Debug.assertIsDefined(program);
111909             handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
111910         }
111911         function getSemanticDiagnostics(cancellationToken) {
111912             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
111913         }
111914         function emit(writeFileCallback, cancellationToken, customTransformers) {
111915             var _a;
111916             ts.Debug.assertIsDefined(program);
111917             ts.Debug.assert(step === BuildStep.Emit);
111918             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
111919             program.backupState();
111920             var declDiagnostics;
111921             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
111922             var outputFiles = [];
111923             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
111924             /*writeFileName*/ undefined, 
111925             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
111926             /*emitOnlyDts*/ false, customTransformers).emitResult;
111927             // Don't emit .d.ts if there are decl file errors
111928             if (declDiagnostics) {
111929                 program.restoreState();
111930                 (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step);
111931                 return {
111932                     emitSkipped: true,
111933                     diagnostics: emitResult.diagnostics
111934                 };
111935             }
111936             // Actual Emit
111937             var host = state.host, compilerHost = state.compilerHost;
111938             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
111939             var newestDeclarationFileContentChangedTime = minimumDate;
111940             var anyDtsChanged = false;
111941             var emitterDiagnostics = ts.createDiagnosticCollection();
111942             var emittedOutputs = new ts.Map();
111943             outputFiles.forEach(function (_a) {
111944                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
111945                 var priorChangeTime;
111946                 if (!anyDtsChanged && isDeclarationFile(name)) {
111947                     // Check for unchanged .d.ts files
111948                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
111949                         priorChangeTime = host.getModifiedTime(name);
111950                     }
111951                     else {
111952                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
111953                         anyDtsChanged = true;
111954                     }
111955                 }
111956                 emittedOutputs.set(toPath(state, name), name);
111957                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
111958                 if (priorChangeTime !== undefined) {
111959                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
111960                 }
111961             });
111962             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
111963             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
111964             return emitResult;
111965         }
111966         function emitBuildInfo(writeFileCallback, cancellationToken) {
111967             ts.Debug.assertIsDefined(program);
111968             ts.Debug.assert(step === BuildStep.EmitBuildInfo);
111969             var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken);
111970             if (emitResult.diagnostics.length) {
111971                 reportErrors(state, emitResult.diagnostics);
111972                 state.diagnostics.set(projectPath, __spreadArrays(state.diagnostics.get(projectPath), emitResult.diagnostics));
111973                 buildResult = BuildResultFlags.EmitErrors & buildResult;
111974             }
111975             if (emitResult.emittedFiles && state.writeFileName) {
111976                 emitResult.emittedFiles.forEach(function (name) { return listEmittedFile(state, config, name); });
111977             }
111978             afterProgramDone(state, program, config);
111979             step = BuildStep.QueueReferencingProjects;
111980             return emitResult;
111981         }
111982         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
111983             var _a;
111984             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
111985             if (emitDiagnostics.length) {
111986                 (_a = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"), buildResult = _a.buildResult, step = _a.step);
111987                 return emitDiagnostics;
111988             }
111989             if (state.writeFileName) {
111990                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
111991             }
111992             // Update time stamps for rest of the outputs
111993             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
111994             state.diagnostics.delete(projectPath);
111995             state.projectStatus.set(projectPath, {
111996                 type: ts.UpToDateStatusType.UpToDate,
111997                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
111998                     maximumDate :
111999                     newestDeclarationFileContentChangedTime,
112000                 oldestOutputFileName: oldestOutputFileName
112001             });
112002             afterProgramDone(state, program, config);
112003             step = BuildStep.QueueReferencingProjects;
112004             buildResult = resultFlags;
112005             return emitDiagnostics;
112006         }
112007         function emitBundle(writeFileCallback, customTransformers) {
112008             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
112009             if (state.options.dry) {
112010                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
112011                 buildResult = BuildResultFlags.Success;
112012                 step = BuildStep.QueueReferencingProjects;
112013                 return undefined;
112014             }
112015             if (state.options.verbose)
112016                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
112017             // Update js, and source map
112018             var compilerHost = state.compilerHost;
112019             state.projectCompilerOptions = config.options;
112020             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
112021                 var refName = resolveProjectName(state, ref.path);
112022                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
112023             }, customTransformers);
112024             if (ts.isString(outputFiles)) {
112025                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
112026                 step = BuildStep.BuildInvalidatedProjectOfBundle;
112027                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
112028             }
112029             // Actual Emit
112030             ts.Debug.assert(!!outputFiles.length);
112031             var emitterDiagnostics = ts.createDiagnosticCollection();
112032             var emittedOutputs = new ts.Map();
112033             outputFiles.forEach(function (_a) {
112034                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
112035                 emittedOutputs.set(toPath(state, name), name);
112036                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
112037             });
112038             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
112039             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
112040             return { emitSkipped: false, diagnostics: emitDiagnostics };
112041         }
112042         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
112043             while (step <= till && step < BuildStep.Done) {
112044                 var currentStep = step;
112045                 switch (step) {
112046                     case BuildStep.CreateProgram:
112047                         createProgram();
112048                         break;
112049                     case BuildStep.SyntaxDiagnostics:
112050                         getSyntaxDiagnostics(cancellationToken);
112051                         break;
112052                     case BuildStep.SemanticDiagnostics:
112053                         getSemanticDiagnostics(cancellationToken);
112054                         break;
112055                     case BuildStep.Emit:
112056                         emit(writeFile, cancellationToken, customTransformers);
112057                         break;
112058                     case BuildStep.EmitBuildInfo:
112059                         emitBuildInfo(writeFile, cancellationToken);
112060                         break;
112061                     case BuildStep.EmitBundle:
112062                         emitBundle(writeFile, customTransformers);
112063                         break;
112064                     case BuildStep.BuildInvalidatedProjectOfBundle:
112065                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
112066                         step = BuildStep.Done;
112067                         break;
112068                     case BuildStep.QueueReferencingProjects:
112069                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
112070                         step++;
112071                         break;
112072                     // Should never be done
112073                     case BuildStep.Done:
112074                     default:
112075                         ts.assertType(step);
112076                 }
112077                 ts.Debug.assert(step > currentStep);
112078             }
112079         }
112080     }
112081     function needsBuild(_a, status, config) {
112082         var options = _a.options;
112083         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
112084             return true;
112085         return config.fileNames.length === 0 ||
112086             !!ts.getConfigFileParsingDiagnostics(config).length ||
112087             !ts.isIncrementalCompilation(config.options);
112088     }
112089     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
112090         if (!state.projectPendingBuild.size)
112091             return undefined;
112092         if (isCircularBuildOrder(buildOrder))
112093             return undefined;
112094         if (state.currentInvalidatedProject) {
112095             // Only if same buildOrder the currentInvalidated project can be sent again
112096             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
112097                 state.currentInvalidatedProject :
112098                 undefined;
112099         }
112100         var options = state.options, projectPendingBuild = state.projectPendingBuild;
112101         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
112102             var project = buildOrder[projectIndex];
112103             var projectPath = toResolvedConfigFilePath(state, project);
112104             var reloadLevel = state.projectPendingBuild.get(projectPath);
112105             if (reloadLevel === undefined)
112106                 continue;
112107             if (reportQueue) {
112108                 reportQueue = false;
112109                 reportBuildQueue(state, buildOrder);
112110             }
112111             var config = parseConfigFile(state, project, projectPath);
112112             if (!config) {
112113                 reportParseConfigFileDiagnostic(state, projectPath);
112114                 projectPendingBuild.delete(projectPath);
112115                 continue;
112116             }
112117             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
112118                 watchConfigFile(state, project, projectPath, config);
112119                 watchWildCardDirectories(state, project, projectPath, config);
112120                 watchInputFiles(state, project, projectPath, config);
112121             }
112122             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
112123                 // Update file names
112124                 var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
112125                 ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInputFiles(config.raw));
112126                 config.fileNames = result.fileNames;
112127                 watchInputFiles(state, project, projectPath, config);
112128             }
112129             var status = getUpToDateStatus(state, config, projectPath);
112130             verboseReportProjectStatus(state, project, status);
112131             if (!options.force) {
112132                 if (status.type === ts.UpToDateStatusType.UpToDate) {
112133                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
112134                     projectPendingBuild.delete(projectPath);
112135                     // Up to date, skip
112136                     if (options.dry) {
112137                         // In a dry build, inform the user of this fact
112138                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
112139                     }
112140                     continue;
112141                 }
112142                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
112143                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
112144                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
112145                 }
112146             }
112147             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
112148                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
112149                 projectPendingBuild.delete(projectPath);
112150                 if (options.verbose) {
112151                     reportStatus(state, status.upstreamProjectBlocked ?
112152                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
112153                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
112154                 }
112155                 continue;
112156             }
112157             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
112158                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
112159                 projectPendingBuild.delete(projectPath);
112160                 // Do nothing
112161                 continue;
112162             }
112163             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
112164                 InvalidatedProjectKind.Build :
112165                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
112166         }
112167         return undefined;
112168     }
112169     function listEmittedFile(_a, proj, file) {
112170         var writeFileName = _a.writeFileName;
112171         if (writeFileName && proj.options.listEmittedFiles) {
112172             writeFileName("TSFILE: " + file);
112173         }
112174     }
112175     function getOldProgram(_a, proj, parsed) {
112176         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
112177         if (options.force)
112178             return undefined;
112179         var value = builderPrograms.get(proj);
112180         if (value)
112181             return value;
112182         return ts.readBuilderProgram(parsed.options, compilerHost);
112183     }
112184     function afterProgramDone(state, program, config) {
112185         if (program) {
112186             if (program && state.writeFileName)
112187                 ts.listFiles(program, state.writeFileName);
112188             if (state.host.afterProgramEmitAndDiagnostics) {
112189                 state.host.afterProgramEmitAndDiagnostics(program);
112190             }
112191             program.releaseProgram();
112192         }
112193         else if (state.host.afterEmitBundle) {
112194             state.host.afterEmitBundle(config);
112195         }
112196         state.projectCompilerOptions = state.baseCompilerOptions;
112197     }
112198     function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) {
112199         var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions());
112200         reportAndStoreErrors(state, resolvedPath, diagnostics);
112201         // List files if any other build error using program (emit errors already report files)
112202         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
112203         if (canEmitBuildInfo)
112204             return { buildResult: buildResult, step: BuildStep.EmitBuildInfo };
112205         afterProgramDone(state, program, config);
112206         return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects };
112207     }
112208     function updateModuleResolutionCache(state, proj, config) {
112209         if (!state.moduleResolutionCache)
112210             return;
112211         // Update module resolution cache if needed
112212         var moduleResolutionCache = state.moduleResolutionCache;
112213         var projPath = toPath(state, proj);
112214         if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
112215             // The own map will be for projectCompilerOptions
112216             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
112217             moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
112218             moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
112219         }
112220         else {
112221             // Set correct own map
112222             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
112223             var ref = {
112224                 sourceFile: config.options.configFile,
112225                 commandLine: config
112226             };
112227             moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
112228             moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
112229         }
112230         moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
112231         moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
112232     }
112233     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
112234         // Check tsconfig time
112235         var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
112236         if (oldestOutputFileTime < tsconfigTime) {
112237             return {
112238                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
112239                 outOfDateOutputFileName: oldestOutputFileName,
112240                 newerInputFileName: configFile
112241             };
112242         }
112243     }
112244     function getUpToDateStatusWorker(state, project, resolvedPath) {
112245         var newestInputFileName = undefined;
112246         var newestInputFileTime = minimumDate;
112247         var host = state.host;
112248         // Get timestamps of input files
112249         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
112250             var inputFile = _a[_i];
112251             if (!host.fileExists(inputFile)) {
112252                 return {
112253                     type: ts.UpToDateStatusType.Unbuildable,
112254                     reason: inputFile + " does not exist"
112255                 };
112256             }
112257             var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
112258             if (inputTime > newestInputFileTime) {
112259                 newestInputFileName = inputFile;
112260                 newestInputFileTime = inputTime;
112261             }
112262         }
112263         // Container if no files are specified in the project
112264         if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) {
112265             return {
112266                 type: ts.UpToDateStatusType.ContainerOnly
112267             };
112268         }
112269         // Collect the expected outputs of this project
112270         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
112271         // Now see if all outputs are newer than the newest input
112272         var oldestOutputFileName = "(none)";
112273         var oldestOutputFileTime = maximumDate;
112274         var newestOutputFileName = "(none)";
112275         var newestOutputFileTime = minimumDate;
112276         var missingOutputFileName;
112277         var newestDeclarationFileContentChangedTime = minimumDate;
112278         var isOutOfDateWithInputs = false;
112279         for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
112280             var output = outputs_1[_b];
112281             // Output is missing; can stop checking
112282             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
112283             if (!host.fileExists(output)) {
112284                 missingOutputFileName = output;
112285                 break;
112286             }
112287             var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
112288             if (outputTime < oldestOutputFileTime) {
112289                 oldestOutputFileTime = outputTime;
112290                 oldestOutputFileName = output;
112291             }
112292             // If an output is older than the newest input, we can stop checking
112293             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
112294             if (outputTime < newestInputFileTime) {
112295                 isOutOfDateWithInputs = true;
112296                 break;
112297             }
112298             if (outputTime > newestOutputFileTime) {
112299                 newestOutputFileTime = outputTime;
112300                 newestOutputFileName = output;
112301             }
112302             // Keep track of when the most recent time a .d.ts file was changed.
112303             // In addition to file timestamps, we also keep track of when a .d.ts file
112304             // had its file touched but not had its contents changed - this allows us
112305             // to skip a downstream typecheck
112306             if (isDeclarationFile(output)) {
112307                 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
112308                 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
112309             }
112310         }
112311         var pseudoUpToDate = false;
112312         var usesPrepend = false;
112313         var upstreamChangedProject;
112314         if (project.projectReferences) {
112315             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
112316             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
112317                 var ref = _d[_c];
112318                 usesPrepend = usesPrepend || !!(ref.prepend);
112319                 var resolvedRef = ts.resolveProjectReferencePath(ref);
112320                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
112321                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
112322                 // Its a circular reference ignore the status of this project
112323                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
112324                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
112325                     continue;
112326                 }
112327                 // An upstream project is blocked
112328                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
112329                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
112330                     return {
112331                         type: ts.UpToDateStatusType.UpstreamBlocked,
112332                         upstreamProjectName: ref.path,
112333                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
112334                     };
112335                 }
112336                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
112337                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
112338                     return {
112339                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
112340                         upstreamProjectName: ref.path
112341                     };
112342                 }
112343                 // Check oldest output file name only if there is no missing output file name
112344                 if (!missingOutputFileName) {
112345                     // If the upstream project's newest file is older than our oldest output, we
112346                     // can't be out of date because of it
112347                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
112348                         continue;
112349                     }
112350                     // If the upstream project has only change .d.ts files, and we've built
112351                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
112352                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
112353                         pseudoUpToDate = true;
112354                         upstreamChangedProject = ref.path;
112355                         continue;
112356                     }
112357                     // We have an output older than an upstream output - we are out of date
112358                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
112359                     return {
112360                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
112361                         outOfDateOutputFileName: oldestOutputFileName,
112362                         newerProjectName: ref.path
112363                     };
112364                 }
112365             }
112366         }
112367         if (missingOutputFileName !== undefined) {
112368             return {
112369                 type: ts.UpToDateStatusType.OutputMissing,
112370                 missingOutputFileName: missingOutputFileName
112371             };
112372         }
112373         if (isOutOfDateWithInputs) {
112374             return {
112375                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
112376                 outOfDateOutputFileName: oldestOutputFileName,
112377                 newerInputFileName: newestInputFileName
112378             };
112379         }
112380         else {
112381             // Check tsconfig time
112382             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
112383             if (configStatus)
112384                 return configStatus;
112385             // Check extended config time
112386             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
112387             if (extendedConfigStatus)
112388                 return extendedConfigStatus;
112389         }
112390         if (!state.buildInfoChecked.has(resolvedPath)) {
112391             state.buildInfoChecked.set(resolvedPath, true);
112392             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
112393             if (buildInfoPath) {
112394                 var value = state.readFileWithCache(buildInfoPath);
112395                 var buildInfo = value && ts.getBuildInfo(value);
112396                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
112397                     return {
112398                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
112399                         version: buildInfo.version
112400                     };
112401                 }
112402             }
112403         }
112404         if (usesPrepend && pseudoUpToDate) {
112405             return {
112406                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
112407                 outOfDateOutputFileName: oldestOutputFileName,
112408                 newerProjectName: upstreamChangedProject
112409             };
112410         }
112411         // Up to date
112412         return {
112413             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
112414             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
112415             newestInputFileTime: newestInputFileTime,
112416             newestOutputFileTime: newestOutputFileTime,
112417             newestInputFileName: newestInputFileName,
112418             newestOutputFileName: newestOutputFileName,
112419             oldestOutputFileName: oldestOutputFileName
112420         };
112421     }
112422     function getUpToDateStatus(state, project, resolvedPath) {
112423         if (project === undefined) {
112424             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
112425         }
112426         var prior = state.projectStatus.get(resolvedPath);
112427         if (prior !== undefined) {
112428             return prior;
112429         }
112430         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
112431         state.projectStatus.set(resolvedPath, actual);
112432         return actual;
112433     }
112434     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
112435         var host = state.host;
112436         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
112437         if (!skipOutputs || outputs.length !== skipOutputs.size) {
112438             var reportVerbose = !!state.options.verbose;
112439             var now = host.now ? host.now() : new Date();
112440             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
112441                 var file = outputs_2[_i];
112442                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
112443                     continue;
112444                 }
112445                 if (reportVerbose) {
112446                     reportVerbose = false;
112447                     reportStatus(state, verboseMessage, proj.options.configFilePath);
112448                 }
112449                 if (isDeclarationFile(file)) {
112450                     priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
112451                 }
112452                 host.setModifiedTime(file, now);
112453             }
112454         }
112455         return priorNewestUpdateTime;
112456     }
112457     function updateOutputTimestamps(state, proj, resolvedPath) {
112458         if (state.options.dry) {
112459             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
112460         }
112461         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
112462         state.projectStatus.set(resolvedPath, {
112463             type: ts.UpToDateStatusType.UpToDate,
112464             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
112465             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
112466         });
112467     }
112468     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
112469         // Queue only if there are no errors
112470         if (buildResult & BuildResultFlags.AnyErrors)
112471             return;
112472         // Only composite projects can be referenced by other projects
112473         if (!config.options.composite)
112474             return;
112475         // Always use build order to queue projects
112476         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
112477             var nextProject = buildOrder[index];
112478             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
112479             if (state.projectPendingBuild.has(nextProjectPath))
112480                 continue;
112481             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
112482             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
112483                 continue;
112484             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
112485                 var ref = _a[_i];
112486                 var resolvedRefPath = resolveProjectName(state, ref.path);
112487                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
112488                     continue;
112489                 // If the project is referenced with prepend, always build downstream projects,
112490                 // If declaration output is changed, build the project
112491                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
112492                 var status = state.projectStatus.get(nextProjectPath);
112493                 if (status) {
112494                     switch (status.type) {
112495                         case ts.UpToDateStatusType.UpToDate:
112496                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
112497                                 if (ref.prepend) {
112498                                     state.projectStatus.set(nextProjectPath, {
112499                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
112500                                         outOfDateOutputFileName: status.oldestOutputFileName,
112501                                         newerProjectName: project
112502                                     });
112503                                 }
112504                                 else {
112505                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
112506                                 }
112507                                 break;
112508                             }
112509                         // falls through
112510                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
112511                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
112512                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
112513                                 state.projectStatus.set(nextProjectPath, {
112514                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
112515                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
112516                                     newerProjectName: project
112517                                 });
112518                             }
112519                             break;
112520                         case ts.UpToDateStatusType.UpstreamBlocked:
112521                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
112522                                 clearProjectStatus(state, nextProjectPath);
112523                             }
112524                             break;
112525                     }
112526                 }
112527                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
112528                 break;
112529             }
112530         }
112531     }
112532     function build(state, project, cancellationToken, onlyReferences) {
112533         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
112534         if (!buildOrder)
112535             return ts.ExitStatus.InvalidProject_OutputsSkipped;
112536         setupInitialBuild(state, cancellationToken);
112537         var reportQueue = true;
112538         var successfulProjects = 0;
112539         while (true) {
112540             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
112541             if (!invalidatedProject)
112542                 break;
112543             reportQueue = false;
112544             invalidatedProject.done(cancellationToken);
112545             if (!state.diagnostics.has(invalidatedProject.projectPath))
112546                 successfulProjects++;
112547         }
112548         disableCache(state);
112549         reportErrorSummary(state, buildOrder);
112550         startWatching(state, buildOrder);
112551         return isCircularBuildOrder(buildOrder)
112552             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
112553             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
112554                 ? ts.ExitStatus.Success
112555                 : successfulProjects
112556                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
112557                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
112558     }
112559     function clean(state, project, onlyReferences) {
112560         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
112561         if (!buildOrder)
112562             return ts.ExitStatus.InvalidProject_OutputsSkipped;
112563         if (isCircularBuildOrder(buildOrder)) {
112564             reportErrors(state, buildOrder.circularDiagnostics);
112565             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
112566         }
112567         var options = state.options, host = state.host;
112568         var filesToDelete = options.dry ? [] : undefined;
112569         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
112570             var proj = buildOrder_1[_i];
112571             var resolvedPath = toResolvedConfigFilePath(state, proj);
112572             var parsed = parseConfigFile(state, proj, resolvedPath);
112573             if (parsed === undefined) {
112574                 // File has gone missing; fine to ignore here
112575                 reportParseConfigFileDiagnostic(state, resolvedPath);
112576                 continue;
112577             }
112578             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
112579             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
112580                 var output = outputs_3[_a];
112581                 if (host.fileExists(output)) {
112582                     if (filesToDelete) {
112583                         filesToDelete.push(output);
112584                     }
112585                     else {
112586                         host.deleteFile(output);
112587                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
112588                     }
112589                 }
112590             }
112591         }
112592         if (filesToDelete) {
112593             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
112594         }
112595         return ts.ExitStatus.Success;
112596     }
112597     function invalidateProject(state, resolved, reloadLevel) {
112598         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
112599         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
112600             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
112601         }
112602         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
112603             state.configFileCache.delete(resolved);
112604             state.buildOrder = undefined;
112605         }
112606         state.needsSummary = true;
112607         clearProjectStatus(state, resolved);
112608         addProjToQueue(state, resolved, reloadLevel);
112609         enableCache(state);
112610     }
112611     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
112612         state.reportFileChangeDetected = true;
112613         invalidateProject(state, resolvedPath, reloadLevel);
112614         scheduleBuildInvalidatedProject(state);
112615     }
112616     function scheduleBuildInvalidatedProject(state) {
112617         var hostWithWatch = state.hostWithWatch;
112618         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
112619             return;
112620         }
112621         if (state.timerToBuildInvalidatedProject) {
112622             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
112623         }
112624         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
112625     }
112626     function buildNextInvalidatedProject(state) {
112627         state.timerToBuildInvalidatedProject = undefined;
112628         if (state.reportFileChangeDetected) {
112629             state.reportFileChangeDetected = false;
112630             state.projectErrorsReported.clear();
112631             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
112632         }
112633         var buildOrder = getBuildOrder(state);
112634         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
112635         if (invalidatedProject) {
112636             invalidatedProject.done();
112637             if (state.projectPendingBuild.size) {
112638                 // Schedule next project for build
112639                 if (state.watch && !state.timerToBuildInvalidatedProject) {
112640                     scheduleBuildInvalidatedProject(state);
112641                 }
112642                 return;
112643             }
112644         }
112645         disableCache(state);
112646         reportErrorSummary(state, buildOrder);
112647     }
112648     function watchConfigFile(state, resolved, resolvedPath, parsed) {
112649         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
112650             return;
112651         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
112652             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
112653         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
112654     }
112655     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
112656         if (!state.watch)
112657             return;
112658         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.configFileSpecs.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
112659             if (ts.isIgnoredFileFromWildCardWatching({
112660                 watchedDirPath: toPath(state, dir),
112661                 fileOrDirectory: fileOrDirectory,
112662                 fileOrDirectoryPath: toPath(state, fileOrDirectory),
112663                 configFileName: resolved,
112664                 configFileSpecs: parsed.configFileSpecs,
112665                 currentDirectory: state.currentDirectory,
112666                 options: parsed.options,
112667                 program: state.builderPrograms.get(resolvedPath),
112668                 useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames,
112669                 writeLog: function (s) { return state.writeLog(s); }
112670             }))
112671                 return;
112672             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
112673         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
112674     }
112675     function watchInputFiles(state, resolved, resolvedPath, parsed) {
112676         if (!state.watch)
112677             return;
112678         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
112679             createNewValue: function (path, input) { return state.watchFilePath(state.hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, path, ts.WatchType.SourceFile, resolved); },
112680             onDeleteValue: ts.closeFileWatcher,
112681         });
112682     }
112683     function startWatching(state, buildOrder) {
112684         if (!state.watchAllProjectsPending)
112685             return;
112686         state.watchAllProjectsPending = false;
112687         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
112688             var resolved = _a[_i];
112689             var resolvedPath = toResolvedConfigFilePath(state, resolved);
112690             var cfg = parseConfigFile(state, resolved, resolvedPath);
112691             // Watch this file
112692             watchConfigFile(state, resolved, resolvedPath, cfg);
112693             if (cfg) {
112694                 // Update watchers for wildcard directories
112695                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
112696                 // Watch input files
112697                 watchInputFiles(state, resolved, resolvedPath, cfg);
112698             }
112699         }
112700     }
112701     function stopWatching(state) {
112702         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
112703         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
112704         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
112705     }
112706     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
112707         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
112708         return {
112709             build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
112710             clean: function (project) { return clean(state, project); },
112711             buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
112712             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
112713             getNextInvalidatedProject: function (cancellationToken) {
112714                 setupInitialBuild(state, cancellationToken);
112715                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
112716             },
112717             getBuildOrder: function () { return getBuildOrder(state); },
112718             getUpToDateStatusOfProject: function (project) {
112719                 var configFileName = resolveProjectName(state, project);
112720                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
112721                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
112722             },
112723             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
112724             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
112725             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
112726             close: function () { return stopWatching(state); },
112727         };
112728     }
112729     function relName(state, path) {
112730         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
112731     }
112732     function reportStatus(state, message) {
112733         var args = [];
112734         for (var _i = 2; _i < arguments.length; _i++) {
112735             args[_i - 2] = arguments[_i];
112736         }
112737         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
112738     }
112739     function reportWatchStatus(state, message) {
112740         var args = [];
112741         for (var _i = 2; _i < arguments.length; _i++) {
112742             args[_i - 2] = arguments[_i];
112743         }
112744         if (state.hostWithWatch.onWatchStatusChange) {
112745             state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
112746         }
112747     }
112748     function reportErrors(_a, errors) {
112749         var host = _a.host;
112750         errors.forEach(function (err) { return host.reportDiagnostic(err); });
112751     }
112752     function reportAndStoreErrors(state, proj, errors) {
112753         reportErrors(state, errors);
112754         state.projectErrorsReported.set(proj, true);
112755         if (errors.length) {
112756             state.diagnostics.set(proj, errors);
112757         }
112758     }
112759     function reportParseConfigFileDiagnostic(state, proj) {
112760         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
112761     }
112762     function reportErrorSummary(state, buildOrder) {
112763         if (!state.needsSummary)
112764             return;
112765         state.needsSummary = false;
112766         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
112767         var diagnostics = state.diagnostics;
112768         var totalErrors = 0;
112769         if (isCircularBuildOrder(buildOrder)) {
112770             reportBuildQueue(state, buildOrder.buildOrder);
112771             reportErrors(state, buildOrder.circularDiagnostics);
112772             if (canReportSummary)
112773                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
112774         }
112775         else {
112776             // Report errors from the other projects
112777             buildOrder.forEach(function (project) {
112778                 var projectPath = toResolvedConfigFilePath(state, project);
112779                 if (!state.projectErrorsReported.has(projectPath)) {
112780                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
112781                 }
112782             });
112783             if (canReportSummary)
112784                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
112785         }
112786         if (state.watch) {
112787             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
112788         }
112789         else if (state.host.reportErrorSummary) {
112790             state.host.reportErrorSummary(totalErrors);
112791         }
112792     }
112793     /**
112794      * Report the build ordering inferred from the current project graph if we're in verbose mode
112795      */
112796     function reportBuildQueue(state, buildQueue) {
112797         if (state.options.verbose) {
112798             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
112799         }
112800     }
112801     function reportUpToDateStatus(state, configFileName, status) {
112802         switch (status.type) {
112803             case ts.UpToDateStatusType.OutOfDateWithSelf:
112804                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName));
112805             case ts.UpToDateStatusType.OutOfDateWithUpstream:
112806                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName));
112807             case ts.UpToDateStatusType.OutputMissing:
112808                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName));
112809             case ts.UpToDateStatusType.UpToDate:
112810                 if (status.newestInputFileTime !== undefined) {
112811                     return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || ""));
112812                 }
112813                 // Don't report anything for "up to date because it was already built" -- too verbose
112814                 break;
112815             case ts.UpToDateStatusType.OutOfDateWithPrepend:
112816                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName));
112817             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
112818                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
112819             case ts.UpToDateStatusType.UpstreamOutOfDate:
112820                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName));
112821             case ts.UpToDateStatusType.UpstreamBlocked:
112822                 return reportStatus(state, status.upstreamProjectBlocked ?
112823                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
112824                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
112825             case ts.UpToDateStatusType.Unbuildable:
112826                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
112827             case ts.UpToDateStatusType.TsVersionOutputOfDate:
112828                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, ts.version);
112829             case ts.UpToDateStatusType.ContainerOnly:
112830             // Don't report status on "solution" projects
112831             // falls through
112832             case ts.UpToDateStatusType.ComputingUpstream:
112833                 // Should never leak from getUptoDateStatusWorker
112834                 break;
112835             default:
112836                 ts.assertType(status);
112837         }
112838     }
112839     /**
112840      * Report the up-to-date status of a project if we're in verbose mode
112841      */
112842     function verboseReportProjectStatus(state, configFileName, status) {
112843         if (state.options.verbose) {
112844             reportUpToDateStatus(state, configFileName, status);
112845         }
112846     }
112847 })(ts || (ts = {}));
112848 var ts;
112849 (function (ts) {
112850     var server;
112851     (function (server) {
112852         /* @internal */
112853         server.ActionSet = "action::set";
112854         /* @internal */
112855         server.ActionInvalidate = "action::invalidate";
112856         /* @internal */
112857         server.ActionPackageInstalled = "action::packageInstalled";
112858         /* @internal */
112859         server.EventTypesRegistry = "event::typesRegistry";
112860         /* @internal */
112861         server.EventBeginInstallTypes = "event::beginInstallTypes";
112862         /* @internal */
112863         server.EventEndInstallTypes = "event::endInstallTypes";
112864         /* @internal */
112865         server.EventInitializationFailed = "event::initializationFailed";
112866         /* @internal */
112867         var Arguments;
112868         (function (Arguments) {
112869             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
112870             Arguments.LogFile = "--logFile";
112871             Arguments.EnableTelemetry = "--enableTelemetry";
112872             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
112873             Arguments.TypesMapLocation = "--typesMapLocation";
112874             /**
112875              * This argument specifies the location of the NPM executable.
112876              * typingsInstaller will run the command with `${npmLocation} install ...`.
112877              */
112878             Arguments.NpmLocation = "--npmLocation";
112879             /**
112880              * Flag indicating that the typings installer should try to validate the default npm location.
112881              * If the default npm is not found when this flag is enabled, fallback to `npm install`
112882              */
112883             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
112884         })(Arguments = server.Arguments || (server.Arguments = {}));
112885         /* @internal */
112886         function hasArgument(argumentName) {
112887             return ts.sys.args.indexOf(argumentName) >= 0;
112888         }
112889         server.hasArgument = hasArgument;
112890         /* @internal */
112891         function findArgument(argumentName) {
112892             var index = ts.sys.args.indexOf(argumentName);
112893             return index >= 0 && index < ts.sys.args.length - 1
112894                 ? ts.sys.args[index + 1]
112895                 : undefined;
112896         }
112897         server.findArgument = findArgument;
112898         /* @internal */
112899         function nowString() {
112900             // E.g. "12:34:56.789"
112901             var d = new Date();
112902             return ts.padLeft(d.getHours().toString(), 2, "0") + ":" + ts.padLeft(d.getMinutes().toString(), 2, "0") + ":" + ts.padLeft(d.getSeconds().toString(), 2, "0") + "." + ts.padLeft(d.getMilliseconds().toString(), 3, "0");
112903         }
112904         server.nowString = nowString;
112905     })(server = ts.server || (ts.server = {}));
112906 })(ts || (ts = {}));
112907 /* @internal */
112908 var ts;
112909 (function (ts) {
112910     var JsTyping;
112911     (function (JsTyping) {
112912         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
112913             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
112914             return availableVersion.compareTo(cachedTyping.version) <= 0;
112915         }
112916         JsTyping.isTypingUpToDate = isTypingUpToDate;
112917         JsTyping.nodeCoreModuleList = [
112918             "assert",
112919             "async_hooks",
112920             "buffer",
112921             "child_process",
112922             "cluster",
112923             "console",
112924             "constants",
112925             "crypto",
112926             "dgram",
112927             "dns",
112928             "domain",
112929             "events",
112930             "fs",
112931             "http",
112932             "https",
112933             "http2",
112934             "inspector",
112935             "net",
112936             "os",
112937             "path",
112938             "perf_hooks",
112939             "process",
112940             "punycode",
112941             "querystring",
112942             "readline",
112943             "repl",
112944             "stream",
112945             "string_decoder",
112946             "timers",
112947             "tls",
112948             "tty",
112949             "url",
112950             "util",
112951             "v8",
112952             "vm",
112953             "zlib"
112954         ];
112955         JsTyping.nodeCoreModules = new ts.Set(JsTyping.nodeCoreModuleList);
112956         function nonRelativeModuleNameForTypingCache(moduleName) {
112957             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
112958         }
112959         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
112960         function loadSafeList(host, safeListPath) {
112961             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
112962             return new ts.Map(ts.getEntries(result.config));
112963         }
112964         JsTyping.loadSafeList = loadSafeList;
112965         function loadTypesMap(host, typesMapPath) {
112966             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
112967             if (result.config) {
112968                 return new ts.Map(ts.getEntries(result.config.simpleMap));
112969             }
112970             return undefined;
112971         }
112972         JsTyping.loadTypesMap = loadTypesMap;
112973         /**
112974          * @param host is the object providing I/O related operations.
112975          * @param fileNames are the file names that belong to the same project
112976          * @param projectRootPath is the path to the project root directory
112977          * @param safeListPath is the path used to retrieve the safe list
112978          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
112979          * @param typeAcquisition is used to customize the typing acquisition process
112980          * @param compilerOptions are used as a source for typing inference
112981          */
112982         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
112983             if (!typeAcquisition || !typeAcquisition.enable) {
112984                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
112985             }
112986             // A typing name to typing file path mapping
112987             var inferredTypings = new ts.Map();
112988             // Only infer typings for .js and .jsx files
112989             fileNames = ts.mapDefined(fileNames, function (fileName) {
112990                 var path = ts.normalizePath(fileName);
112991                 if (ts.hasJSFileExtension(path)) {
112992                     return path;
112993                 }
112994             });
112995             var filesToWatch = [];
112996             if (typeAcquisition.include)
112997                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
112998             var exclude = typeAcquisition.exclude || [];
112999             // Directories to search for package.json, bower.json and other typing information
113000             var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath));
113001             possibleSearchDirs.add(projectRootPath);
113002             possibleSearchDirs.forEach(function (searchDir) {
113003                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
113004                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
113005                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
113006                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
113007                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
113008                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
113009                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
113010                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
113011             });
113012             if (!typeAcquisition.disableFilenameBasedTypeAcquisition) {
113013                 getTypingNamesFromSourceFileNames(fileNames);
113014             }
113015             // add typings for unresolved imports
113016             if (unresolvedImports) {
113017                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
113018                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
113019             }
113020             // Add the cached typing locations for inferred typings that are already installed
113021             packageNameToTypingLocation.forEach(function (typing, name) {
113022                 var registryEntry = typesRegistry.get(name);
113023                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
113024                     inferredTypings.set(name, typing.typingLocation);
113025                 }
113026             });
113027             // Remove typings that the user has added to the exclude list
113028             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
113029                 var excludeTypingName = exclude_1[_i];
113030                 var didDelete = inferredTypings.delete(excludeTypingName);
113031                 if (didDelete && log)
113032                     log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
113033             }
113034             var newTypingNames = [];
113035             var cachedTypingPaths = [];
113036             inferredTypings.forEach(function (inferred, typing) {
113037                 if (inferred !== undefined) {
113038                     cachedTypingPaths.push(inferred);
113039                 }
113040                 else {
113041                     newTypingNames.push(typing);
113042                 }
113043             });
113044             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
113045             if (log)
113046                 log("Result: " + JSON.stringify(result));
113047             return result;
113048             function addInferredTyping(typingName) {
113049                 if (!inferredTypings.has(typingName)) {
113050                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
113051                 }
113052             }
113053             function addInferredTypings(typingNames, message) {
113054                 if (log)
113055                     log(message + ": " + JSON.stringify(typingNames));
113056                 ts.forEach(typingNames, addInferredTyping);
113057             }
113058             /**
113059              * Get the typing info from common package manager json files like package.json or bower.json
113060              */
113061             function getTypingNamesFromJson(jsonPath, filesToWatch) {
113062                 if (!host.fileExists(jsonPath)) {
113063                     return;
113064                 }
113065                 filesToWatch.push(jsonPath);
113066                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
113067                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
113068                 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
113069             }
113070             /**
113071              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
113072              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
113073              * to the 'angular-route' typing name.
113074              * @param fileNames are the names for source files in the project
113075              */
113076             function getTypingNamesFromSourceFileNames(fileNames) {
113077                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
113078                     if (!ts.hasJSFileExtension(j))
113079                         return undefined;
113080                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
113081                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
113082                     return safeList.get(cleanedTypingName);
113083                 });
113084                 if (fromFileNames.length) {
113085                     addInferredTypings(fromFileNames, "Inferred typings from file names");
113086                 }
113087                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
113088                 if (hasJsxFile) {
113089                     if (log)
113090                         log("Inferred 'react' typings due to presence of '.jsx' extension");
113091                     addInferredTyping("react");
113092                 }
113093             }
113094             /**
113095              * Infer typing names from packages folder (ex: node_module, bower_components)
113096              * @param packagesFolderPath is the path to the packages folder
113097              */
113098             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
113099                 filesToWatch.push(packagesFolderPath);
113100                 // Todo: add support for ModuleResolutionHost too
113101                 if (!host.directoryExists(packagesFolderPath)) {
113102                     return;
113103                 }
113104                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
113105                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
113106                 if (log)
113107                     log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
113108                 var packageNames = [];
113109                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
113110                     var fileName = fileNames_1[_i];
113111                     var normalizedFileName = ts.normalizePath(fileName);
113112                     var baseFileName = ts.getBaseFileName(normalizedFileName);
113113                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
113114                         continue;
113115                     }
113116                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
113117                     var packageJson = result_1.config;
113118                     // npm 3's package.json contains a "_requiredBy" field
113119                     // we should include all the top level module names for npm 2, and only module names whose
113120                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
113121                     if (baseFileName === "package.json" && packageJson._requiredBy &&
113122                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
113123                         continue;
113124                     }
113125                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
113126                     // to download d.ts files from DefinitelyTyped
113127                     if (!packageJson.name) {
113128                         continue;
113129                     }
113130                     var ownTypes = packageJson.types || packageJson.typings;
113131                     if (ownTypes) {
113132                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
113133                         if (log)
113134                             log("    Package '" + packageJson.name + "' provides its own types.");
113135                         inferredTypings.set(packageJson.name, absolutePath);
113136                     }
113137                     else {
113138                         packageNames.push(packageJson.name);
113139                     }
113140                 }
113141                 addInferredTypings(packageNames, "    Found package names");
113142             }
113143         }
113144         JsTyping.discoverTypings = discoverTypings;
113145         var NameValidationResult;
113146         (function (NameValidationResult) {
113147             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
113148             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
113149             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
113150             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
113151             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
113152             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
113153         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
113154         var maxPackageNameLength = 214;
113155         /**
113156          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
113157          */
113158         function validatePackageName(packageName) {
113159             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
113160         }
113161         JsTyping.validatePackageName = validatePackageName;
113162         function validatePackageNameWorker(packageName, supportScopedPackage) {
113163             if (!packageName) {
113164                 return 1 /* EmptyName */;
113165             }
113166             if (packageName.length > maxPackageNameLength) {
113167                 return 2 /* NameTooLong */;
113168             }
113169             if (packageName.charCodeAt(0) === 46 /* dot */) {
113170                 return 3 /* NameStartsWithDot */;
113171             }
113172             if (packageName.charCodeAt(0) === 95 /* _ */) {
113173                 return 4 /* NameStartsWithUnderscore */;
113174             }
113175             // check if name is scope package like: starts with @ and has one '/' in the middle
113176             // scoped packages are not currently supported
113177             if (supportScopedPackage) {
113178                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
113179                 if (matches) {
113180                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
113181                     if (scopeResult !== 0 /* Ok */) {
113182                         return { name: matches[1], isScopeName: true, result: scopeResult };
113183                     }
113184                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
113185                     if (packageResult !== 0 /* Ok */) {
113186                         return { name: matches[2], isScopeName: false, result: packageResult };
113187                     }
113188                     return 0 /* Ok */;
113189                 }
113190             }
113191             if (encodeURIComponent(packageName) !== packageName) {
113192                 return 5 /* NameContainsNonURISafeCharacters */;
113193             }
113194             return 0 /* Ok */;
113195         }
113196         function renderPackageNameValidationFailure(result, typing) {
113197             return typeof result === "object" ?
113198                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
113199                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
113200         }
113201         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
113202         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
113203             var kind = isScopeName ? "Scope" : "Package";
113204             switch (result) {
113205                 case 1 /* EmptyName */:
113206                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
113207                 case 2 /* NameTooLong */:
113208                     return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
113209                 case 3 /* NameStartsWithDot */:
113210                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
113211                 case 4 /* NameStartsWithUnderscore */:
113212                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
113213                 case 5 /* NameContainsNonURISafeCharacters */:
113214                     return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
113215                 case 0 /* Ok */:
113216                     return ts.Debug.fail(); // Shouldn't have called this.
113217                 default:
113218                     throw ts.Debug.assertNever(result);
113219             }
113220         }
113221     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
113222 })(ts || (ts = {}));
113223 var ts;
113224 (function (ts) {
113225     var server;
113226     (function (server) {
113227         var typingsInstaller;
113228         (function (typingsInstaller) {
113229             var nullLog = {
113230                 isEnabled: function () { return false; },
113231                 writeLine: ts.noop
113232             };
113233             function typingToFileName(cachePath, packageName, installTypingHost, log) {
113234                 try {
113235                     var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
113236                     return result.resolvedModule && result.resolvedModule.resolvedFileName;
113237                 }
113238                 catch (e) {
113239                     if (log.isEnabled()) {
113240                         log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
113241                     }
113242                     return undefined;
113243                 }
113244             }
113245             /*@internal*/
113246             function installNpmPackages(npmPath, tsVersion, packageNames, install) {
113247                 var hasError = false;
113248                 for (var remaining = packageNames.length; remaining > 0;) {
113249                     var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
113250                     remaining = result.remaining;
113251                     hasError = install(result.command) || hasError;
113252                 }
113253                 return hasError;
113254             }
113255             typingsInstaller.installNpmPackages = installNpmPackages;
113256             /*@internal*/
113257             function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
113258                 var sliceStart = packageNames.length - remaining;
113259                 var command, toSlice = remaining;
113260                 while (true) {
113261                     command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\"";
113262                     if (command.length < 8000) {
113263                         break;
113264                     }
113265                     toSlice = toSlice - Math.floor(toSlice / 2);
113266                 }
113267                 return { command: command, remaining: remaining - toSlice };
113268             }
113269             typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
113270             function endsWith(str, suffix, caseSensitive) {
113271                 var expectedPos = str.length - suffix.length;
113272                 return expectedPos >= 0 &&
113273                     (str.indexOf(suffix, expectedPos) === expectedPos ||
113274                         (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
113275             }
113276             function isPackageOrBowerJson(fileName, caseSensitive) {
113277                 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
113278             }
113279             function sameFiles(a, b, caseSensitive) {
113280                 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
113281             }
113282             var ProjectWatcherType;
113283             (function (ProjectWatcherType) {
113284                 ProjectWatcherType["FileWatcher"] = "FileWatcher";
113285                 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
113286             })(ProjectWatcherType || (ProjectWatcherType = {}));
113287             var TypingsInstaller = /** @class */ (function () {
113288                 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
113289                     if (log === void 0) { log = nullLog; }
113290                     this.installTypingHost = installTypingHost;
113291                     this.globalCachePath = globalCachePath;
113292                     this.safeListPath = safeListPath;
113293                     this.typesMapLocation = typesMapLocation;
113294                     this.throttleLimit = throttleLimit;
113295                     this.log = log;
113296                     this.packageNameToTypingLocation = new ts.Map();
113297                     this.missingTypingsSet = new ts.Set();
113298                     this.knownCachesSet = new ts.Set();
113299                     this.projectWatchers = new ts.Map();
113300                     this.pendingRunRequests = [];
113301                     this.installRunCount = 1;
113302                     this.inFlightRequestCount = 0;
113303                     this.latestDistTag = "latest";
113304                     this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
113305                     this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
113306                     if (this.log.isEnabled()) {
113307                         this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation);
113308                     }
113309                     this.processCacheLocation(this.globalCachePath);
113310                 }
113311                 TypingsInstaller.prototype.closeProject = function (req) {
113312                     this.closeWatchers(req.projectName);
113313                 };
113314                 TypingsInstaller.prototype.closeWatchers = function (projectName) {
113315                     if (this.log.isEnabled()) {
113316                         this.log.writeLine("Closing file watchers for project '" + projectName + "'");
113317                     }
113318                     var watchers = this.projectWatchers.get(projectName);
113319                     if (!watchers) {
113320                         if (this.log.isEnabled()) {
113321                             this.log.writeLine("No watchers are registered for project '" + projectName + "'");
113322                         }
113323                         return;
113324                     }
113325                     ts.clearMap(watchers, ts.closeFileWatcher);
113326                     this.projectWatchers.delete(projectName);
113327                     if (this.log.isEnabled()) {
113328                         this.log.writeLine("Closing file watchers for project '" + projectName + "' - done.");
113329                     }
113330                 };
113331                 TypingsInstaller.prototype.install = function (req) {
113332                     var _this = this;
113333                     if (this.log.isEnabled()) {
113334                         this.log.writeLine("Got install request " + JSON.stringify(req));
113335                     }
113336                     // load existing typing information from the cache
113337                     if (req.cachePath) {
113338                         if (this.log.isEnabled()) {
113339                             this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information...");
113340                         }
113341                         this.processCacheLocation(req.cachePath);
113342                     }
113343                     if (this.safeList === undefined) {
113344                         this.initializeSafeList();
113345                     }
113346                     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);
113347                     if (this.log.isEnabled()) {
113348                         this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult));
113349                     }
113350                     // start watching files
113351                     this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions);
113352                     // install typings
113353                     if (discoverTypingsResult.newTypingNames.length) {
113354                         this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
113355                     }
113356                     else {
113357                         this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
113358                         if (this.log.isEnabled()) {
113359                             this.log.writeLine("No new typings were requested as a result of typings discovery");
113360                         }
113361                     }
113362                 };
113363                 TypingsInstaller.prototype.initializeSafeList = function () {
113364                     // Prefer the safe list from the types map if it exists
113365                     if (this.typesMapLocation) {
113366                         var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
113367                         if (safeListFromMap) {
113368                             this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'");
113369                             this.safeList = safeListFromMap;
113370                             return;
113371                         }
113372                         this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'");
113373                     }
113374                     this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
113375                 };
113376                 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
113377                     if (this.log.isEnabled()) {
113378                         this.log.writeLine("Processing cache location '" + cacheLocation + "'");
113379                     }
113380                     if (this.knownCachesSet.has(cacheLocation)) {
113381                         if (this.log.isEnabled()) {
113382                             this.log.writeLine("Cache location was already processed...");
113383                         }
113384                         return;
113385                     }
113386                     var packageJson = ts.combinePaths(cacheLocation, "package.json");
113387                     var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
113388                     if (this.log.isEnabled()) {
113389                         this.log.writeLine("Trying to find '" + packageJson + "'...");
113390                     }
113391                     if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
113392                         var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
113393                         var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
113394                         if (this.log.isEnabled()) {
113395                             this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig));
113396                             this.log.writeLine("Loaded content of '" + packageLockJson + "'");
113397                         }
113398                         if (npmConfig.devDependencies && npmLock.dependencies) {
113399                             for (var key in npmConfig.devDependencies) {
113400                                 if (!ts.hasProperty(npmLock.dependencies, key)) {
113401                                     // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
113402                                     continue;
113403                                 }
113404                                 // key is @types/<package name>
113405                                 var packageName = ts.getBaseFileName(key);
113406                                 if (!packageName) {
113407                                     continue;
113408                                 }
113409                                 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
113410                                 if (!typingFile) {
113411                                     this.missingTypingsSet.add(packageName);
113412                                     continue;
113413                                 }
113414                                 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
113415                                 if (existingTypingFile) {
113416                                     if (existingTypingFile.typingLocation === typingFile) {
113417                                         continue;
113418                                     }
113419                                     if (this.log.isEnabled()) {
113420                                         this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'");
113421                                     }
113422                                 }
113423                                 if (this.log.isEnabled()) {
113424                                     this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'");
113425                                 }
113426                                 var info = ts.getProperty(npmLock.dependencies, key);
113427                                 var version_1 = info && info.version;
113428                                 if (!version_1) {
113429                                     continue;
113430                                 }
113431                                 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
113432                                 this.packageNameToTypingLocation.set(packageName, newTyping);
113433                             }
113434                         }
113435                     }
113436                     if (this.log.isEnabled()) {
113437                         this.log.writeLine("Finished processing cache location '" + cacheLocation + "'");
113438                     }
113439                     this.knownCachesSet.add(cacheLocation);
113440                 };
113441                 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
113442                     var _this = this;
113443                     return ts.mapDefined(typingsToInstall, function (typing) {
113444                         var typingKey = ts.mangleScopedPackageName(typing);
113445                         if (_this.missingTypingsSet.has(typingKey)) {
113446                             if (_this.log.isEnabled())
113447                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' is in missingTypingsSet - skipping...");
113448                             return undefined;
113449                         }
113450                         var validationResult = ts.JsTyping.validatePackageName(typing);
113451                         if (validationResult !== 0 /* Ok */) {
113452                             // add typing name to missing set so we won't process it again
113453                             _this.missingTypingsSet.add(typingKey);
113454                             if (_this.log.isEnabled())
113455                                 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
113456                             return undefined;
113457                         }
113458                         if (!_this.typesRegistry.has(typingKey)) {
113459                             if (_this.log.isEnabled())
113460                                 _this.log.writeLine("'" + typing + "':: Entry for package '" + typingKey + "' does not exist in local types registry - skipping...");
113461                             return undefined;
113462                         }
113463                         if (_this.packageNameToTypingLocation.get(typingKey) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typingKey), _this.typesRegistry.get(typingKey))) {
113464                             if (_this.log.isEnabled())
113465                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' already has an up-to-date typing - skipping...");
113466                             return undefined;
113467                         }
113468                         return typingKey;
113469                     });
113470                 };
113471                 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
113472                     var npmConfigPath = ts.combinePaths(directory, "package.json");
113473                     if (this.log.isEnabled()) {
113474                         this.log.writeLine("Npm config file: " + npmConfigPath);
113475                     }
113476                     if (!this.installTypingHost.fileExists(npmConfigPath)) {
113477                         if (this.log.isEnabled()) {
113478                             this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one...");
113479                         }
113480                         this.ensureDirectoryExists(directory, this.installTypingHost);
113481                         this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
113482                     }
113483                 };
113484                 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
113485                     var _this = this;
113486                     if (this.log.isEnabled()) {
113487                         this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
113488                     }
113489                     var filteredTypings = this.filterTypings(typingsToInstall);
113490                     if (filteredTypings.length === 0) {
113491                         if (this.log.isEnabled()) {
113492                             this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
113493                         }
113494                         this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
113495                         return;
113496                     }
113497                     this.ensurePackageDirectoryExists(cachePath);
113498                     var requestId = this.installRunCount;
113499                     this.installRunCount++;
113500                     // send progress event
113501                     this.sendResponse({
113502                         kind: server.EventBeginInstallTypes,
113503                         eventId: requestId,
113504                         // qualified explicitly to prevent occasional shadowing
113505                         // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
113506                         typingsInstallerVersion: ts.version,
113507                         projectName: req.projectName
113508                     });
113509                     var scopedTypings = filteredTypings.map(typingsName);
113510                     this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
113511                         try {
113512                             if (!ok) {
113513                                 if (_this.log.isEnabled()) {
113514                                     _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings));
113515                                 }
113516                                 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
113517                                     var typing = filteredTypings_1[_i];
113518                                     _this.missingTypingsSet.add(typing);
113519                                 }
113520                                 return;
113521                             }
113522                             // TODO: watch project directory
113523                             if (_this.log.isEnabled()) {
113524                                 _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
113525                             }
113526                             var installedTypingFiles = [];
113527                             for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
113528                                 var packageName = filteredTypings_2[_a];
113529                                 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
113530                                 if (!typingFile) {
113531                                     _this.missingTypingsSet.add(packageName);
113532                                     continue;
113533                                 }
113534                                 // packageName is guaranteed to exist in typesRegistry by filterTypings
113535                                 var distTags = _this.typesRegistry.get(packageName);
113536                                 var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
113537                                 var newTyping = { typingLocation: typingFile, version: newVersion };
113538                                 _this.packageNameToTypingLocation.set(packageName, newTyping);
113539                                 installedTypingFiles.push(typingFile);
113540                             }
113541                             if (_this.log.isEnabled()) {
113542                                 _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
113543                             }
113544                             _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
113545                         }
113546                         finally {
113547                             var response = {
113548                                 kind: server.EventEndInstallTypes,
113549                                 eventId: requestId,
113550                                 projectName: req.projectName,
113551                                 packagesToInstall: scopedTypings,
113552                                 installSuccess: ok,
113553                                 // qualified explicitly to prevent occasional shadowing
113554                                 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
113555                                 typingsInstallerVersion: ts.version
113556                             };
113557                             _this.sendResponse(response);
113558                         }
113559                     });
113560                 };
113561                 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
113562                     var directoryName = ts.getDirectoryPath(directory);
113563                     if (!host.directoryExists(directoryName)) {
113564                         this.ensureDirectoryExists(directoryName, host);
113565                     }
113566                     if (!host.directoryExists(directory)) {
113567                         host.createDirectory(directory);
113568                     }
113569                 };
113570                 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath, options) {
113571                     var _this = this;
113572                     if (!files.length) {
113573                         // shut down existing watchers
113574                         this.closeWatchers(projectName);
113575                         return;
113576                     }
113577                     var watchers = this.projectWatchers.get(projectName);
113578                     var toRemove = new ts.Map();
113579                     if (!watchers) {
113580                         watchers = new ts.Map();
113581                         this.projectWatchers.set(projectName, watchers);
113582                     }
113583                     else {
113584                         ts.copyEntries(watchers, toRemove);
113585                     }
113586                     // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
113587                     watchers.isInvoked = false;
113588                     var isLoggingEnabled = this.log.isEnabled();
113589                     var createProjectWatcher = function (path, projectWatcherType) {
113590                         var canonicalPath = _this.toCanonicalFileName(path);
113591                         toRemove.delete(canonicalPath);
113592                         if (watchers.has(canonicalPath)) {
113593                             return;
113594                         }
113595                         if (isLoggingEnabled) {
113596                             _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path);
113597                         }
113598                         var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
113599                             _this.installTypingHost.watchFile(path, function (f, eventKind) {
113600                                 if (isLoggingEnabled) {
113601                                     _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'");
113602                                 }
113603                                 if (!watchers.isInvoked) {
113604                                     watchers.isInvoked = true;
113605                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
113606                                 }
113607                             }, /*pollingInterval*/ 2000, options) :
113608                             _this.installTypingHost.watchDirectory(path, function (f) {
113609                                 if (isLoggingEnabled) {
113610                                     _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'");
113611                                 }
113612                                 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
113613                                     return;
113614                                 }
113615                                 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
113616                                     !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
113617                                     watchers.isInvoked = true;
113618                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
113619                                 }
113620                             }, /*recursive*/ true, options);
113621                         watchers.set(canonicalPath, isLoggingEnabled ? {
113622                             close: function () {
113623                                 _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path);
113624                                 watcher.close();
113625                             }
113626                         } : watcher);
113627                     };
113628                     // Create watches from list of files
113629                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
113630                         var file = files_1[_i];
113631                         if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
113632                             // package.json or bower.json exists, watch the file to detect changes and update typings
113633                             createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
113634                             continue;
113635                         }
113636                         // path in projectRoot, watch project root
113637                         if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
113638                             var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
113639                             if (subDirectory !== -1) {
113640                                 // Watch subDirectory
113641                                 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
113642                             }
113643                             else {
113644                                 // Watch the directory itself
113645                                 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
113646                             }
113647                             continue;
113648                         }
113649                         // path in global cache, watch global cache
113650                         if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
113651                             createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
113652                             continue;
113653                         }
113654                         // watch node_modules or bower_components
113655                         createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
113656                     }
113657                     // Remove unused watches
113658                     toRemove.forEach(function (watch, path) {
113659                         watch.close();
113660                         watchers.delete(path);
113661                     });
113662                 };
113663                 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
113664                     return {
113665                         projectName: request.projectName,
113666                         typeAcquisition: request.typeAcquisition,
113667                         compilerOptions: request.compilerOptions,
113668                         typings: typings,
113669                         unresolvedImports: request.unresolvedImports,
113670                         kind: server.ActionSet
113671                     };
113672                 };
113673                 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
113674                     this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
113675                     this.executeWithThrottling();
113676                 };
113677                 TypingsInstaller.prototype.executeWithThrottling = function () {
113678                     var _this = this;
113679                     var _loop_1 = function () {
113680                         this_1.inFlightRequestCount++;
113681                         var request = this_1.pendingRunRequests.pop();
113682                         this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
113683                             _this.inFlightRequestCount--;
113684                             request.onRequestCompleted(ok);
113685                             _this.executeWithThrottling();
113686                         });
113687                     };
113688                     var this_1 = this;
113689                     while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
113690                         _loop_1();
113691                     }
113692                 };
113693                 return TypingsInstaller;
113694             }());
113695             typingsInstaller.TypingsInstaller = TypingsInstaller;
113696             /* @internal */
113697             function typingsName(packageName) {
113698                 return "@types/" + packageName + "@ts" + ts.versionMajorMinor;
113699             }
113700             typingsInstaller.typingsName = typingsName;
113701         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
113702     })(server = ts.server || (ts.server = {}));
113703 })(ts || (ts = {}));
113704 var ts;
113705 (function (ts) {
113706     var server;
113707     (function (server) {
113708         var typingsInstaller;
113709         (function (typingsInstaller) {
113710             var fs = require("fs");
113711             var path = require("path");
113712             var FileLog = (function () {
113713                 function FileLog(logFile) {
113714                     var _this = this;
113715                     this.logFile = logFile;
113716                     this.isEnabled = function () {
113717                         return typeof _this.logFile === "string";
113718                     };
113719                     this.writeLine = function (text) {
113720                         if (typeof _this.logFile !== "string")
113721                             return;
113722                         try {
113723                             fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine);
113724                         }
113725                         catch (e) {
113726                             _this.logFile = undefined;
113727                         }
113728                     };
113729                 }
113730                 return FileLog;
113731             }());
113732             function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
113733                 if (path.basename(processName).indexOf("node") === 0) {
113734                     var npmPath = path.join(path.dirname(process.argv[0]), "npm");
113735                     if (!validateDefaultNpmLocation) {
113736                         return npmPath;
113737                     }
113738                     if (host.fileExists(npmPath)) {
113739                         return "\"" + npmPath + "\"";
113740                     }
113741                 }
113742                 return "npm";
113743             }
113744             function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
113745                 if (!host.fileExists(typesRegistryFilePath)) {
113746                     if (log.isEnabled()) {
113747                         log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist");
113748                     }
113749                     return new ts.Map();
113750                 }
113751                 try {
113752                     var content = JSON.parse(host.readFile(typesRegistryFilePath));
113753                     return new ts.Map(ts.getEntries(content.entries));
113754                 }
113755                 catch (e) {
113756                     if (log.isEnabled()) {
113757                         log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack);
113758                     }
113759                     return new ts.Map();
113760                 }
113761             }
113762             var typesRegistryPackageName = "types-registry";
113763             function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
113764                 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json");
113765             }
113766             var NodeTypingsInstaller = (function (_super) {
113767                 __extends(NodeTypingsInstaller, _super);
113768                 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
113769                     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;
113770                     _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
113771                     if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
113772                         _this.npmPath = "\"" + _this.npmPath + "\"";
113773                     }
113774                     if (_this.log.isEnabled()) {
113775                         _this.log.writeLine("Process id: " + process.pid);
113776                         _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
113777                         _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
113778                     }
113779                     (_this.nodeExecSync = require("child_process").execSync);
113780                     _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
113781                     try {
113782                         if (_this.log.isEnabled()) {
113783                             _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package...");
113784                         }
113785                         _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation });
113786                         if (_this.log.isEnabled()) {
113787                             _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package");
113788                         }
113789                     }
113790                     catch (e) {
113791                         if (_this.log.isEnabled()) {
113792                             _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message);
113793                         }
113794                         _this.delayedInitializationError = {
113795                             kind: "event::initializationFailed",
113796                             message: e.message,
113797                             stack: e.stack,
113798                         };
113799                     }
113800                     _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
113801                     return _this;
113802                 }
113803                 NodeTypingsInstaller.prototype.listen = function () {
113804                     var _this = this;
113805                     process.on("message", function (req) {
113806                         if (_this.delayedInitializationError) {
113807                             _this.sendResponse(_this.delayedInitializationError);
113808                             _this.delayedInitializationError = undefined;
113809                         }
113810                         switch (req.kind) {
113811                             case "discover":
113812                                 _this.install(req);
113813                                 break;
113814                             case "closeProject":
113815                                 _this.closeProject(req);
113816                                 break;
113817                             case "typesRegistry": {
113818                                 var typesRegistry_1 = {};
113819                                 _this.typesRegistry.forEach(function (value, key) {
113820                                     typesRegistry_1[key] = value;
113821                                 });
113822                                 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
113823                                 _this.sendResponse(response);
113824                                 break;
113825                             }
113826                             case "installPackage": {
113827                                 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
113828                                 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
113829                                 if (cwd) {
113830                                     _this.installWorker(-1, [packageName_1], cwd, function (success) {
113831                                         var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + ".";
113832                                         var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
113833                                         _this.sendResponse(response);
113834                                     });
113835                                 }
113836                                 else {
113837                                     var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
113838                                     _this.sendResponse(response);
113839                                 }
113840                                 break;
113841                             }
113842                             default:
113843                                 ts.Debug.assertNever(req);
113844                         }
113845                     });
113846                 };
113847                 NodeTypingsInstaller.prototype.sendResponse = function (response) {
113848                     if (this.log.isEnabled()) {
113849                         this.log.writeLine("Sending response:\n    " + JSON.stringify(response));
113850                     }
113851                     process.send(response);
113852                     if (this.log.isEnabled()) {
113853                         this.log.writeLine("Response has been sent.");
113854                     }
113855                 };
113856                 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
113857                     var _this = this;
113858                     if (this.log.isEnabled()) {
113859                         this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'.");
113860                     }
113861                     var start = Date.now();
113862                     var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
113863                     if (this.log.isEnabled()) {
113864                         this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms");
113865                     }
113866                     onRequestCompleted(!hasError);
113867                 };
113868                 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
113869                     if (this.log.isEnabled()) {
113870                         this.log.writeLine("Exec: " + command);
113871                     }
113872                     try {
113873                         var stdout = this.nodeExecSync(command, __assign(__assign({}, options), { encoding: "utf-8" }));
113874                         if (this.log.isEnabled()) {
113875                             this.log.writeLine("    Succeeded. stdout:" + indent(ts.sys.newLine, stdout));
113876                         }
113877                         return false;
113878                     }
113879                     catch (error) {
113880                         var stdout = error.stdout, stderr = error.stderr;
113881                         this.log.writeLine("    Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + "    stderr:" + indent(ts.sys.newLine, stderr));
113882                         return true;
113883                     }
113884                 };
113885                 return NodeTypingsInstaller;
113886             }(typingsInstaller.TypingsInstaller));
113887             typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
113888             function getDirectoryOfPackageJson(fileName, host) {
113889                 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
113890                     if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
113891                         return directory;
113892                     }
113893                 });
113894             }
113895             var logFilePath = server.findArgument(server.Arguments.LogFile);
113896             var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
113897             var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
113898             var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
113899             var npmLocation = server.findArgument(server.Arguments.NpmLocation);
113900             var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
113901             var log = new FileLog(logFilePath);
113902             if (log.isEnabled()) {
113903                 process.on("uncaughtException", function (e) {
113904                     log.writeLine("Unhandled exception: " + e + " at " + e.stack);
113905                 });
113906             }
113907             process.on("disconnect", function () {
113908                 if (log.isEnabled()) {
113909                     log.writeLine("Parent process has exited, shutting down...");
113910                 }
113911                 process.exit(0);
113912             });
113913             var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
113914             installer.listen();
113915             function indent(newline, str) {
113916                 return str && str.length
113917                     ? newline + "    " + str.replace(/\r?\n/, newline + "    ")
113918                     : "";
113919             }
113920         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
113921     })(server = ts.server || (ts.server = {}));
113922 })(ts || (ts = {}));
113923 //# sourceMappingURL=typingsInstaller.js.map